blob: b421cebc132eb15b64596ae1f040310631287576 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass transforms simple global variables that never have their address
11// taken. If obviously true, it marks read/write globals as constant, deletes
12// variables only stored to, etc.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "globalopt"
17#include "llvm/Transforms/IPO.h"
18#include "llvm/CallingConv.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Instructions.h"
22#include "llvm/IntrinsicInst.h"
Owen Anderson086ea052009-07-06 01:34:54 +000023#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
26#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez48c3c542009-09-18 22:35:49 +000027#include "llvm/Analysis/MallocHelper.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Target/TargetData.h"
Duncan Sands551ec902008-02-18 17:32:13 +000029#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner7bd79da2008-01-14 02:09:12 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner20846272008-04-26 07:40:11 +000033#include "llvm/Support/MathExtras.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner4cd08c22008-12-16 07:34:30 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattnerbdf77462007-09-13 16:30:19 +000036#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/Statistic.h"
Chris Lattner8a2d32e2008-12-17 05:28:49 +000039#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041using namespace llvm;
42
43STATISTIC(NumMarked , "Number of globals marked constant");
44STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
45STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
46STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
47STATISTIC(NumDeleted , "Number of globals deleted");
48STATISTIC(NumFnDeleted , "Number of functions deleted");
49STATISTIC(NumGlobUses , "Number of global uses devirtualized");
50STATISTIC(NumLocalized , "Number of globals localized");
51STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
52STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
53STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sandsafa10bf2008-02-16 20:56:04 +000054STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandse7f431f2009-02-15 09:56:08 +000055STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
56STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057
58namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000059 struct GlobalOpt : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061 }
62 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000063 GlobalOpt() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064
65 bool runOnModule(Module &M);
66
67 private:
68 GlobalVariable *FindGlobalCtors(Module &M);
69 bool OptimizeFunctions(Module &M);
70 bool OptimizeGlobalVars(Module &M);
Duncan Sands0c7b6332009-03-06 10:21:56 +000071 bool OptimizeGlobalAliases(Module &M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
73 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
74 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075}
76
Dan Gohman089efff2008-05-13 00:00:25 +000077char GlobalOpt::ID = 0;
78static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
79
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
81
Dan Gohman089efff2008-05-13 00:00:25 +000082namespace {
83
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084/// GlobalStatus - As we analyze each global, keep track of some information
85/// about it. If we find out that the address of the global is taken, none of
86/// this info will be accurate.
Nick Lewycky492d06e2009-10-25 06:33:48 +000087struct GlobalStatus {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088 /// isLoaded - True if the global is ever loaded. If the global isn't ever
89 /// loaded it can be deleted.
90 bool isLoaded;
91
92 /// StoredType - Keep track of what stores to the global look like.
93 ///
94 enum StoredType {
95 /// NotStored - There is no store to this global. It can thus be marked
96 /// constant.
97 NotStored,
98
99 /// isInitializerStored - This global is stored to, but the only thing
100 /// stored is the constant it was initialized with. This is only tracked
101 /// for scalar globals.
102 isInitializerStored,
103
104 /// isStoredOnce - This global is stored to, but only its initializer and
105 /// one other value is ever stored to it. If this global isStoredOnce, we
106 /// track the value stored to it in StoredOnceValue below. This is only
107 /// tracked for scalar globals.
108 isStoredOnce,
109
110 /// isStored - This global is stored to by multiple values or something else
111 /// that we cannot track.
112 isStored
113 } StoredType;
114
115 /// StoredOnceValue - If only one value (besides the initializer constant) is
116 /// ever stored to this global, keep track of what value it is.
117 Value *StoredOnceValue;
118
119 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
120 /// null/false. When the first accessing function is noticed, it is recorded.
121 /// When a second different accessing function is noticed,
122 /// HasMultipleAccessingFunctions is set to true.
123 Function *AccessingFunction;
124 bool HasMultipleAccessingFunctions;
125
126 /// HasNonInstructionUser - Set to true if this global has a user that is not
127 /// an instruction (e.g. a constant expr or GV initializer).
128 bool HasNonInstructionUser;
129
130 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
131 bool HasPHIUser;
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
134 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattnercad76212008-01-14 01:32:52 +0000135 HasNonInstructionUser(false), HasPHIUser(false) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136};
137
Dan Gohman089efff2008-05-13 00:00:25 +0000138}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139
Jay Foade4914352009-06-09 21:37:11 +0000140// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
141// by constants itself. Note that constants cannot be cyclic, so this test is
142// pretty easy to implement recursively.
143//
144static bool SafeToDestroyConstant(Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 if (isa<GlobalValue>(C)) return false;
146
Devang Patel3b6b19e2009-03-06 01:37:41 +0000147 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
148 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade4914352009-06-09 21:37:11 +0000149 if (!SafeToDestroyConstant(CU)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 } else
151 return false;
152 return true;
153}
154
155
156/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157/// structure. If the global has its address taken, return true to indicate we
158/// can't do anything with it.
159///
160static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner4cd08c22008-12-16 07:34:30 +0000161 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
164 GS.HasNonInstructionUser = true;
165
166 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
168 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
169 if (!GS.HasMultipleAccessingFunctions) {
170 Function *F = I->getParent()->getParent();
171 if (GS.AccessingFunction == 0)
172 GS.AccessingFunction = F;
173 else if (GS.AccessingFunction != F)
174 GS.HasMultipleAccessingFunctions = true;
175 }
Chris Lattner75a2db82008-01-29 19:01:37 +0000176 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 GS.isLoaded = true;
Chris Lattner75a2db82008-01-29 19:01:37 +0000178 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
180 // Don't allow a store OF the address, only stores TO the address.
181 if (SI->getOperand(0) == V) return true;
182
Chris Lattner75a2db82008-01-29 19:01:37 +0000183 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 // If this is a direct store to the global (i.e., the global is a scalar
186 // value, not an aggregate), keep more specific information about
187 // stores.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000188 if (GS.StoredType != GlobalStatus::isStored) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
190 Value *StoredVal = SI->getOperand(0);
191 if (StoredVal == GV->getInitializer()) {
192 if (GS.StoredType < GlobalStatus::isInitializerStored)
193 GS.StoredType = GlobalStatus::isInitializerStored;
194 } else if (isa<LoadInst>(StoredVal) &&
195 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
196 // G = G
197 if (GS.StoredType < GlobalStatus::isInitializerStored)
198 GS.StoredType = GlobalStatus::isInitializerStored;
199 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200 GS.StoredType = GlobalStatus::isStoredOnce;
201 GS.StoredOnceValue = StoredVal;
202 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
203 GS.StoredOnceValue == StoredVal) {
204 // noop.
205 } else {
206 GS.StoredType = GlobalStatus::isStored;
207 }
208 } else {
209 GS.StoredType = GlobalStatus::isStored;
210 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000211 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 } else if (isa<GetElementPtrInst>(I)) {
213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 } else if (isa<SelectInst>(I)) {
215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
217 // PHI nodes we can check just like select or GEP instructions, but we
218 // have to be careful about infinite recursion.
Chris Lattner4cd08c22008-12-16 07:34:30 +0000219 if (PHIUsers.insert(PN)) // Not already visited.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 GS.HasPHIUser = true;
222 } else if (isa<CmpInst>(I)) {
Chris Lattnerb914b952009-03-08 03:37:35 +0000223 } else if (isa<MemTransferInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 if (I->getOperand(1) == V)
225 GS.StoredType = GlobalStatus::isStored;
226 if (I->getOperand(2) == V)
227 GS.isLoaded = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 } else if (isa<MemSetInst>(I)) {
229 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
230 GS.StoredType = GlobalStatus::isStored;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 } else {
232 return true; // Any other non-load instruction might take address!
233 }
234 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
235 GS.HasNonInstructionUser = true;
236 // We might have a dead and dangling constant hanging off of here.
Jay Foade4914352009-06-09 21:37:11 +0000237 if (!SafeToDestroyConstant(C))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 return true;
239 } else {
240 GS.HasNonInstructionUser = true;
241 // Otherwise must be some other user.
242 return true;
243 }
244
245 return false;
246}
247
Owen Anderson086ea052009-07-06 01:34:54 +0000248static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
Owen Anderson175b6542009-07-22 00:24:57 +0000249 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
251 if (!CI) return 0;
252 unsigned IdxV = CI->getZExtValue();
253
254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
255 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
256 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
257 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
258 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
259 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
260 } else if (isa<ConstantAggregateZero>(Agg)) {
261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
Owen Andersonaac28372009-07-31 20:28:14 +0000263 return Constant::getNullValue(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersonaac28372009-07-31 20:28:14 +0000266 return Constant::getNullValue(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 }
268 } else if (isa<UndefValue>(Agg)) {
269 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
270 if (IdxV < STy->getNumElements())
Owen Andersonb99ecca2009-07-30 23:03:37 +0000271 return UndefValue::get(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 } else if (const SequentialType *STy =
273 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersonb99ecca2009-07-30 23:03:37 +0000274 return UndefValue::get(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 }
276 }
277 return 0;
278}
279
280
281/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
282/// users of the global, cleaning up the obvious ones. This is largely just a
283/// quick scan over the use list to clean up the easy and obvious cruft. This
284/// returns true if it made a change.
Owen Andersond4d90a02009-07-06 18:42:36 +0000285static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Owen Anderson175b6542009-07-22 00:24:57 +0000286 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 bool Changed = false;
288 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
289 User *U = *UI++;
290
291 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
292 if (Init) {
293 // Replace the load with the initializer.
294 LI->replaceAllUsesWith(Init);
295 LI->eraseFromParent();
296 Changed = true;
297 }
298 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
299 // Store must be unreachable or storing Init into the global.
300 SI->eraseFromParent();
301 Changed = true;
302 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
303 if (CE->getOpcode() == Instruction::GetElementPtr) {
304 Constant *SubInit = 0;
305 if (Init)
Dan Gohmanf49f7b02009-10-05 16:36:26 +0000306 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Owen Andersond4d90a02009-07-06 18:42:36 +0000307 Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 } else if (CE->getOpcode() == Instruction::BitCast &&
309 isa<PointerType>(CE->getType())) {
310 // Pointer cast, delete any stores and memsets to the global.
Owen Andersond4d90a02009-07-06 18:42:36 +0000311 Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 }
313
314 if (CE->use_empty()) {
315 CE->destroyConstant();
316 Changed = true;
317 }
318 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7ebafca2007-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.
Chris Lattner2dd9c042007-11-13 21:46:23 +0000322 Constant *SubInit = 0;
Chris Lattner7ebafca2007-11-09 17:33:02 +0000323 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
324 ConstantExpr *CE =
Owen Andersond4d90a02009-07-06 18:42:36 +0000325 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
Chris Lattner7ebafca2007-11-09 17:33:02 +0000326 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Dan Gohmanf49f7b02009-10-05 16:36:26 +0000327 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7ebafca2007-11-09 17:33:02 +0000328 }
Owen Andersond4d90a02009-07-06 18:42:36 +0000329 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
331 if (GEP->use_empty()) {
332 GEP->eraseFromParent();
333 Changed = true;
334 }
335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (MI->getRawDest() == V) {
337 MI->eraseFromParent();
338 Changed = true;
339 }
340
341 } else if (Constant *C = dyn_cast<Constant>(U)) {
342 // If we have a chain of dead constantexprs or other things dangling from
343 // us, and if they are all dead, nuke them without remorse.
Jay Foade4914352009-06-09 21:37:11 +0000344 if (SafeToDestroyConstant(C)) {
Devang Patel3b6b19e2009-03-06 01:37:41 +0000345 C->destroyConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 // This could have invalidated UI, start over from scratch.
Owen Andersond4d90a02009-07-06 18:42:36 +0000347 CleanupConstantGlobalUsers(V, Init, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348 return true;
349 }
350 }
351 }
352 return Changed;
353}
354
Chris Lattner7bd79da2008-01-14 02:09:12 +0000355/// isSafeSROAElementUse - Return true if the specified instruction is a safe
356/// user of a derived expression from a global that we want to SROA.
357static bool isSafeSROAElementUse(Value *V) {
358 // We might have a dead and dangling constant hanging off of here.
359 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade4914352009-06-09 21:37:11 +0000360 return SafeToDestroyConstant(C);
Chris Lattner7329c662008-01-14 01:31:05 +0000361
Chris Lattner7bd79da2008-01-14 02:09:12 +0000362 Instruction *I = dyn_cast<Instruction>(V);
363 if (!I) return false;
364
365 // Loads are ok.
366 if (isa<LoadInst>(I)) return true;
367
368 // Stores *to* the pointer are ok.
369 if (StoreInst *SI = dyn_cast<StoreInst>(I))
370 return SI->getOperand(0) != V;
371
372 // Otherwise, it must be a GEP.
373 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
374 if (GEPI == 0) return false;
375
376 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
377 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
378 return false;
379
380 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
381 I != E; ++I)
382 if (!isSafeSROAElementUse(*I))
383 return false;
Chris Lattner7329c662008-01-14 01:31:05 +0000384 return true;
385}
386
Chris Lattner7bd79da2008-01-14 02:09:12 +0000387
388/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
389/// Look at it and its uses and decide whether it is safe to SROA this global.
390///
391static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
392 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
393 if (!isa<GetElementPtrInst>(U) &&
394 (!isa<ConstantExpr>(U) ||
395 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
396 return false;
397
398 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
399 // don't like < 3 operand CE's, and we don't like non-constant integer
400 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
401 // value of C.
402 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
403 !cast<Constant>(U->getOperand(1))->isNullValue() ||
404 !isa<ConstantInt>(U->getOperand(2)))
405 return false;
406
407 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
408 ++GEPI; // Skip over the pointer index.
409
410 // If this is a use of an array allocation, do a bit more checking for sanity.
411 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
412 uint64_t NumElements = AT->getNumElements();
413 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
414
415 // Check to make sure that index falls within the array. If not,
416 // something funny is going on, so we won't do the optimization.
417 //
418 if (Idx->getZExtValue() >= NumElements)
419 return false;
420
421 // We cannot scalar repl this level of the array unless any array
422 // sub-indices are in-range constants. In particular, consider:
423 // A[0][i]. We cannot know that the user isn't doing invalid things like
424 // allowing i to index an out-of-range subscript that accesses A[1].
425 //
426 // Scalar replacing *just* the outer index of the array is probably not
427 // going to be a win anyway, so just give up.
428 for (++GEPI; // Skip array index.
Dan Gohmanf0080a12009-08-18 14:58:19 +0000429 GEPI != E;
Chris Lattner7bd79da2008-01-14 02:09:12 +0000430 ++GEPI) {
431 uint64_t NumElements;
432 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
433 NumElements = SubArrayTy->getNumElements();
Dan Gohmanf0080a12009-08-18 14:58:19 +0000434 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
435 NumElements = SubVectorTy->getNumElements();
436 else {
437 assert(isa<StructType>(*GEPI) &&
438 "Indexed GEP type is not array, vector, or struct!");
439 continue;
440 }
Chris Lattner7bd79da2008-01-14 02:09:12 +0000441
442 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
443 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
444 return false;
445 }
446 }
447
448 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
449 if (!isSafeSROAElementUse(*I))
450 return false;
451 return true;
452}
453
454/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
455/// is safe for us to perform this transformation.
456///
457static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
458 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
459 UI != E; ++UI) {
460 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
461 return false;
462 }
463 return true;
464}
465
466
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
468/// variable. This opens the door for other optimizations by exposing the
469/// behavior of the program in a more fine-grained way. We have determined that
470/// this transformation is safe already. We return the first global variable we
471/// insert so that the caller can reprocess it.
Owen Anderson086ea052009-07-06 01:34:54 +0000472static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
Owen Anderson175b6542009-07-22 00:24:57 +0000473 LLVMContext &Context) {
Chris Lattner7329c662008-01-14 01:31:05 +0000474 // Make sure this global only has simple uses that we can SRA.
Chris Lattner7bd79da2008-01-14 02:09:12 +0000475 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner7329c662008-01-14 01:31:05 +0000476 return 0;
477
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000478 assert(GV->hasLocalLinkage() && !GV->isConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479 Constant *Init = GV->getInitializer();
480 const Type *Ty = Init->getType();
481
482 std::vector<GlobalVariable*> NewGlobals;
483 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
484
Chris Lattner20846272008-04-26 07:40:11 +0000485 // Get the alignment of the global, either explicit or target-specific.
486 unsigned StartAlignment = GV->getAlignment();
487 if (StartAlignment == 0)
488 StartAlignment = TD.getABITypeAlignment(GV->getType());
489
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
491 NewGlobals.reserve(STy->getNumElements());
Chris Lattner20846272008-04-26 07:40:11 +0000492 const StructLayout &Layout = *TD.getStructLayout(STy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
494 Constant *In = getAggregateConstantElement(Init,
Owen Anderson35b47072009-08-13 21:58:54 +0000495 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson086ea052009-07-06 01:34:54 +0000496 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 assert(In && "Couldn't get element of initializer?");
Owen Anderson175b6542009-07-22 00:24:57 +0000498 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000499 STy->getElementType(i), false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 GlobalVariable::InternalLinkage,
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000501 In, GV->getName()+"."+Twine(i),
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000502 GV->isThreadLocal(),
Owen Andersone0f136d2009-07-08 01:26:06 +0000503 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000504 Globals.insert(GV, NGV);
505 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000506
507 // Calculate the known alignment of the field. If the original aggregate
508 // had 256 byte alignment for example, something might depend on that:
509 // propagate info to each field.
510 uint64_t FieldOffset = Layout.getElementOffset(i);
511 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
512 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
513 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 }
515 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
516 unsigned NumElements = 0;
517 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
518 NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 else
Chris Lattner20846272008-04-26 07:40:11 +0000520 NumElements = cast<VectorType>(STy)->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521
522 if (NumElements > 16 && GV->hasNUsesOrMore(16))
523 return 0; // It's not worth it.
524 NewGlobals.reserve(NumElements);
Chris Lattner20846272008-04-26 07:40:11 +0000525
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000526 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner20846272008-04-26 07:40:11 +0000527 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 for (unsigned i = 0, e = NumElements; i != e; ++i) {
529 Constant *In = getAggregateConstantElement(Init,
Owen Anderson35b47072009-08-13 21:58:54 +0000530 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson086ea052009-07-06 01:34:54 +0000531 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 assert(In && "Couldn't get element of initializer?");
533
Owen Anderson175b6542009-07-22 00:24:57 +0000534 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000535 STy->getElementType(), false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 GlobalVariable::InternalLinkage,
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000537 In, GV->getName()+"."+Twine(i),
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000538 GV->isThreadLocal(),
Owen Andersone17fc1d2009-07-08 19:03:57 +0000539 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 Globals.insert(GV, NGV);
541 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000542
543 // Calculate the known alignment of the field. If the original aggregate
544 // had 256 byte alignment for example, something might depend on that:
545 // propagate info to each field.
546 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
547 if (NewAlign > EltAlign)
548 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 }
550 }
551
552 if (NewGlobals.empty())
553 return 0;
554
Chris Lattner8a6411c2009-08-23 04:37:46 +0000555 DEBUG(errs() << "PERFORMING GLOBAL SRA ON: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556
Owen Anderson35b47072009-08-13 21:58:54 +0000557 Constant *NullInt = Constant::getNullValue(Type::getInt32Ty(Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558
559 // Loop over all of the uses of the global, replacing the constantexpr geps,
560 // with smaller constantexpr geps or direct references.
561 while (!GV->use_empty()) {
562 User *GEP = GV->use_back();
563 assert(((isa<ConstantExpr>(GEP) &&
564 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
565 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
566
567 // Ignore the 1th operand, which has to be zero or else the program is quite
568 // broken (undefined). Get the 2nd operand, which is the structure or array
569 // index.
570 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
571 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
572
573 Value *NewPtr = NewGlobals[Val];
574
575 // Form a shorter GEP if needed.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000576 if (GEP->getNumOperands() > 3) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
578 SmallVector<Constant*, 8> Idxs;
579 Idxs.push_back(NullInt);
580 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
581 Idxs.push_back(CE->getOperand(i));
Owen Anderson02b48c32009-07-29 18:55:55 +0000582 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 &Idxs[0], Idxs.size());
584 } else {
585 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
586 SmallVector<Value*, 8> Idxs;
587 Idxs.push_back(NullInt);
588 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
589 Idxs.push_back(GEPI->getOperand(i));
Gabor Greifd6da1d02008-04-06 20:25:17 +0000590 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000591 GEPI->getName()+"."+Twine(Val),GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000592 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000593 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594 GEP->replaceAllUsesWith(NewPtr);
595
596 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
597 GEPI->eraseFromParent();
598 else
599 cast<ConstantExpr>(GEP)->destroyConstant();
600 }
601
602 // Delete the old global, now that it is dead.
603 Globals.erase(GV);
604 ++NumSRA;
605
606 // Loop over the new globals array deleting any globals that are obviously
607 // dead. This can arise due to scalarization of a structure or an array that
608 // has elements that are dead.
609 unsigned FirstGlobal = 0;
610 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
611 if (NewGlobals[i]->use_empty()) {
612 Globals.erase(NewGlobals[i]);
613 if (FirstGlobal == i) ++FirstGlobal;
614 }
615
616 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
617}
618
619/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattnerbdf77462007-09-13 16:30:19 +0000620/// value will trap if the value is dynamically null. PHIs keeps track of any
621/// phi nodes we've seen to avoid reprocessing them.
622static bool AllUsesOfValueWillTrapIfNull(Value *V,
623 SmallPtrSet<PHINode*, 8> &PHIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
625 if (isa<LoadInst>(*UI)) {
626 // Will trap.
627 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
628 if (SI->getOperand(0) == V) {
629 //cerr << "NONTRAPPING USE: " << **UI;
630 return false; // Storing the value.
631 }
632 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
633 if (CI->getOperand(0) != V) {
634 //cerr << "NONTRAPPING USE: " << **UI;
635 return false; // Not calling the ptr
636 }
637 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
638 if (II->getOperand(0) != V) {
639 //cerr << "NONTRAPPING USE: " << **UI;
640 return false; // Not calling the ptr
641 }
Chris Lattnerbdf77462007-09-13 16:30:19 +0000642 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
643 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000645 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
646 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
647 // If we've already seen this phi node, ignore it, it has already been
648 // checked.
649 if (PHIs.insert(PN))
650 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 } else if (isa<ICmpInst>(*UI) &&
652 isa<ConstantPointerNull>(UI->getOperand(1))) {
653 // Ignore setcc X, null
654 } else {
655 //cerr << "NONTRAPPING USE: " << **UI;
656 return false;
657 }
658 return true;
659}
660
661/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
662/// from GV will trap if the loaded value is null. Note that this also permits
663/// comparisons of the loaded value against null, as a special case.
664static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
665 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
666 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000667 SmallPtrSet<PHINode*, 8> PHIs;
668 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 return false;
670 } else if (isa<StoreInst>(*UI)) {
671 // Ignore stores to the global.
672 } else {
673 // We don't know or understand this user, bail out.
674 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
675 return false;
676 }
677
678 return true;
679}
680
Owen Anderson086ea052009-07-06 01:34:54 +0000681static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
Owen Anderson175b6542009-07-22 00:24:57 +0000682 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 bool Changed = false;
684 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
685 Instruction *I = cast<Instruction>(*UI++);
686 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
687 LI->setOperand(0, NewV);
688 Changed = true;
689 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
690 if (SI->getOperand(1) == V) {
691 SI->setOperand(1, NewV);
692 Changed = true;
693 }
694 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
695 if (I->getOperand(0) == V) {
696 // Calling through the pointer! Turn into a direct call, but be careful
697 // that the pointer is not also being passed as an argument.
698 I->setOperand(0, NewV);
699 Changed = true;
700 bool PassedAsArg = false;
701 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
702 if (I->getOperand(i) == V) {
703 PassedAsArg = true;
704 I->setOperand(i, NewV);
705 }
706
707 if (PassedAsArg) {
708 // Being passed as an argument also. Be careful to not invalidate UI!
709 UI = V->use_begin();
710 }
711 }
712 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
713 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson02b48c32009-07-29 18:55:55 +0000714 ConstantExpr::getCast(CI->getOpcode(),
Owen Anderson086ea052009-07-06 01:34:54 +0000715 NewV, CI->getType()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 if (CI->use_empty()) {
717 Changed = true;
718 CI->eraseFromParent();
719 }
720 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
721 // Should handle GEP here.
722 SmallVector<Constant*, 8> Idxs;
723 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif20f03f52008-05-29 01:59:18 +0000724 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
725 i != e; ++i)
726 if (Constant *C = dyn_cast<Constant>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 Idxs.push_back(C);
728 else
729 break;
730 if (Idxs.size() == GEPI->getNumOperands()-1)
731 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Anderson02b48c32009-07-29 18:55:55 +0000732 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Owen Anderson086ea052009-07-06 01:34:54 +0000733 Idxs.size()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 if (GEPI->use_empty()) {
735 Changed = true;
736 GEPI->eraseFromParent();
737 }
738 }
739 }
740
741 return Changed;
742}
743
744
745/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
746/// value stored into it. If there are uses of the loaded value that would trap
747/// if the loaded value is dynamically null, then we know that they cannot be
748/// reachable with a null optimize away the load.
Owen Anderson086ea052009-07-06 01:34:54 +0000749static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Owen Anderson175b6542009-07-22 00:24:57 +0000750 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 bool Changed = false;
752
Chris Lattner9806cc12009-01-14 00:12:58 +0000753 // Keep track of whether we are able to remove all the uses of the global
754 // other than the store that defines it.
755 bool AllNonStoreUsesGone = true;
756
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner9806cc12009-01-14 00:12:58 +0000758 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
759 User *GlobalUser = *GUI++;
760 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson086ea052009-07-06 01:34:54 +0000761 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner9806cc12009-01-14 00:12:58 +0000762 // If we were able to delete all uses of the loads
763 if (LI->use_empty()) {
764 LI->eraseFromParent();
765 Changed = true;
766 } else {
767 AllNonStoreUsesGone = false;
768 }
769 } else if (isa<StoreInst>(GlobalUser)) {
770 // Ignore the store that stores "LV" to the global.
771 assert(GlobalUser->getOperand(1) == GV &&
772 "Must be storing *to* the global");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 } else {
Chris Lattner9806cc12009-01-14 00:12:58 +0000774 AllNonStoreUsesGone = false;
775
776 // If we get here we could have other crazy uses that are transitively
777 // loaded.
778 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
779 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 }
Chris Lattner9806cc12009-01-14 00:12:58 +0000781 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782
783 if (Changed) {
Chris Lattner8a6411c2009-08-23 04:37:46 +0000784 DEBUG(errs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 ++NumGlobUses;
786 }
787
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 // If we nuked all of the loads, then none of the stores are needed either,
789 // nor is the global.
Chris Lattner9806cc12009-01-14 00:12:58 +0000790 if (AllNonStoreUsesGone) {
Chris Lattner8a6411c2009-08-23 04:37:46 +0000791 DEBUG(errs() << " *** GLOBAL NOW DEAD!\n");
Owen Andersond4d90a02009-07-06 18:42:36 +0000792 CleanupConstantGlobalUsers(GV, 0, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793 if (GV->use_empty()) {
794 GV->eraseFromParent();
795 ++NumDeleted;
796 }
797 Changed = true;
798 }
799 return Changed;
800}
801
802/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
803/// instructions that are foldable.
Owen Anderson175b6542009-07-22 00:24:57 +0000804static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
806 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Andersond4d90a02009-07-06 18:42:36 +0000807 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 I->replaceAllUsesWith(NewC);
809
810 // Advance UI to the next non-I use to avoid invalidating it!
811 // Instructions could multiply use V.
812 while (UI != E && *UI == I)
813 ++UI;
814 I->eraseFromParent();
815 }
816}
817
818/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
819/// variable, and transforms the program as if it always contained the result of
820/// the specified malloc. Because it is always the result of the specified
821/// malloc, there is no reason to actually DO the malloc. Instead, turn the
822/// malloc into a global, and any loads of GV as uses of the new global.
823static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Victor Hernandez48c3c542009-09-18 22:35:49 +0000824 CallInst *CI,
825 BitCastInst *BCI,
826 LLVMContext &Context,
827 TargetData* TD) {
Victor Hernandez89058912009-10-15 20:14:52 +0000828 DEBUG(errs() << "PROMOTING MALLOC GLOBAL: " << *GV
829 << " CALL = " << *CI << " BCI = " << *BCI << '\n');
830
Victor Hernandez48c3c542009-09-18 22:35:49 +0000831 const Type *IntPtrTy = TD->getIntPtrType(Context);
832
Victor Hernandez89058912009-10-15 20:14:52 +0000833 Value* ArraySize = getMallocArraySize(CI, Context, TD);
834 assert(ArraySize && "not a malloc whose array size can be determined");
835 ConstantInt *NElements = cast<ConstantInt>(ArraySize);
Victor Hernandez48c3c542009-09-18 22:35:49 +0000836 if (NElements->getZExtValue() != 1) {
837 // If we have an array allocation, transform it to a single element
838 // allocation to make the code below simpler.
839 Type *NewTy = ArrayType::get(getMallocAllocatedType(CI),
840 NElements->getZExtValue());
841 Value* NewM = CallInst::CreateMalloc(CI, IntPtrTy, NewTy);
842 Instruction* NewMI = cast<Instruction>(NewM);
843 Value* Indices[2];
844 Indices[0] = Indices[1] = Constant::getNullValue(IntPtrTy);
845 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
846 NewMI->getName()+".el0", CI);
847 BCI->replaceAllUsesWith(NewGEP);
848 BCI->eraseFromParent();
849 CI->eraseFromParent();
850 BCI = cast<BitCastInst>(NewMI);
851 CI = extractMallocCallFromBitCast(NewMI);
852 }
853
854 // Create the new global variable. The contents of the malloc'd memory is
855 // undefined, so initialize with an undef value.
Victor Hernandez48c3c542009-09-18 22:35:49 +0000856 const Type *MAT = getMallocAllocatedType(CI);
857 Constant *Init = UndefValue::get(MAT);
858 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
859 MAT, false,
860 GlobalValue::InternalLinkage, Init,
861 GV->getName()+".body",
862 GV,
863 GV->isThreadLocal());
864
865 // Anything that used the malloc now uses the global directly.
866 BCI->replaceAllUsesWith(NewGV);
867
868 Constant *RepValue = NewGV;
869 if (NewGV->getType() != GV->getType()->getElementType())
870 RepValue = ConstantExpr::getBitCast(RepValue,
871 GV->getType()->getElementType());
872
873 // If there is a comparison against null, we will insert a global bool to
874 // keep track of whether the global was initialized yet or not.
875 GlobalVariable *InitBool =
876 new GlobalVariable(Context, Type::getInt1Ty(Context), false,
877 GlobalValue::InternalLinkage,
878 ConstantInt::getFalse(Context), GV->getName()+".init",
879 GV->isThreadLocal());
880 bool InitBoolUsed = false;
881
882 // Loop over all uses of GV, processing them in turn.
883 std::vector<StoreInst*> Stores;
884 while (!GV->use_empty())
885 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
886 while (!LI->use_empty()) {
887 Use &LoadUse = LI->use_begin().getUse();
888 if (!isa<ICmpInst>(LoadUse.getUser()))
889 LoadUse = RepValue;
890 else {
891 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
892 // Replace the cmp X, 0 with a use of the bool value.
893 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
894 InitBoolUsed = true;
895 switch (ICI->getPredicate()) {
896 default: llvm_unreachable("Unknown ICmp Predicate!");
897 case ICmpInst::ICMP_ULT:
898 case ICmpInst::ICMP_SLT:
899 LV = ConstantInt::getFalse(Context); // X < null -> always false
900 break;
901 case ICmpInst::ICMP_ULE:
902 case ICmpInst::ICMP_SLE:
903 case ICmpInst::ICMP_EQ:
904 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
905 break;
906 case ICmpInst::ICMP_NE:
907 case ICmpInst::ICMP_UGE:
908 case ICmpInst::ICMP_SGE:
909 case ICmpInst::ICMP_UGT:
910 case ICmpInst::ICMP_SGT:
911 break; // no change.
912 }
913 ICI->replaceAllUsesWith(LV);
914 ICI->eraseFromParent();
915 }
916 }
917 LI->eraseFromParent();
918 } else {
919 StoreInst *SI = cast<StoreInst>(GV->use_back());
920 // The global is initialized when the store to it occurs.
921 new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
922 SI->eraseFromParent();
923 }
924
925 // If the initialization boolean was used, insert it, otherwise delete it.
926 if (!InitBoolUsed) {
927 while (!InitBool->use_empty()) // Delete initializations
928 cast<Instruction>(InitBool->use_back())->eraseFromParent();
929 delete InitBool;
930 } else
931 GV->getParent()->getGlobalList().insert(GV, InitBool);
932
933
934 // Now the GV is dead, nuke it and the malloc.
935 GV->eraseFromParent();
936 BCI->eraseFromParent();
937 CI->eraseFromParent();
938
939 // To further other optimizations, loop over all users of NewGV and try to
940 // constant prop them. This will promote GEP instructions with constant
941 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
942 ConstantPropUsersOf(NewGV, Context);
943 if (RepValue != NewGV)
944 ConstantPropUsersOf(RepValue, Context);
945
946 return NewGV;
947}
948
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
950/// to make sure that there are no complex uses of V. We permit simple things
951/// like dereferencing the pointer, but not storing through the address, unless
952/// it is to the specified global.
953static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnere7606f42007-09-13 16:37:20 +0000954 GlobalVariable *GV,
955 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner183b0cf2008-12-15 21:08:54 +0000956 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foadd1d6a142009-06-06 17:49:35 +0000957 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner183b0cf2008-12-15 21:08:54 +0000958
959 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
960 continue; // Fine, ignore.
961 }
962
963 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
965 return false; // Storing the pointer itself... bad.
Chris Lattner183b0cf2008-12-15 21:08:54 +0000966 continue; // Otherwise, storing through it, or storing into GV... fine.
967 }
968
969 if (isa<GetElementPtrInst>(Inst)) {
970 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000972 continue;
973 }
974
975 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnere7606f42007-09-13 16:37:20 +0000976 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
977 // cycles.
978 if (PHIs.insert(PN))
Chris Lattner4bde3c42007-09-14 03:41:21 +0000979 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
980 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000981 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 }
Chris Lattner183b0cf2008-12-15 21:08:54 +0000983
984 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
985 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
986 return false;
987 continue;
988 }
989
990 return false;
991 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 return true;
993}
994
995/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
996/// somewhere. Transform all uses of the allocation into loads from the
997/// global and uses of the resultant pointer. Further, delete the store into
998/// GV. This assumes that these value pass the
999/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1000static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1001 GlobalVariable *GV) {
1002 while (!Alloc->use_empty()) {
Chris Lattner20eef0f2007-09-13 18:00:31 +00001003 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1004 Instruction *InsertPt = U;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1006 // If this is the store of the allocation into the global, remove it.
1007 if (SI->getOperand(1) == GV) {
1008 SI->eraseFromParent();
1009 continue;
1010 }
Chris Lattner20eef0f2007-09-13 18:00:31 +00001011 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1012 // Insert the load in the corresponding predecessor, not right before the
1013 // PHI.
Gabor Greif261734d2009-01-23 19:40:15 +00001014 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner27ef89e2008-12-15 21:44:34 +00001015 } else if (isa<BitCastInst>(U)) {
1016 // Must be bitcast between the malloc and store to initialize the global.
1017 ReplaceUsesOfMallocWithGlobal(U, GV);
1018 U->eraseFromParent();
1019 continue;
1020 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1021 // If this is a "GEP bitcast" and the user is a store to the global, then
1022 // just process it as a bitcast.
1023 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1024 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1025 if (SI->getOperand(1) == GV) {
1026 // Must be bitcast GEP between the malloc and store to initialize
1027 // the global.
1028 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1029 GEPI->eraseFromParent();
1030 continue;
1031 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 }
Chris Lattner27ef89e2008-12-15 21:44:34 +00001033
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 // Insert a load from the global, and use it instead of the malloc.
Chris Lattner20eef0f2007-09-13 18:00:31 +00001035 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 U->replaceUsesOfWith(Alloc, NL);
1037 }
1038}
1039
Chris Lattner7f252db2008-12-16 21:24:51 +00001040/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1041/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1042/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001043static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Chengb00d9282009-06-02 00:56:07 +00001044 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1045 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner7f252db2008-12-16 21:24:51 +00001046 // We permit two users of the load: setcc comparing against the null
1047 // pointer, and a getelementptr of a specific form.
1048 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1049 Instruction *User = cast<Instruction>(*UI);
1050
1051 // Comparison against null is ok.
1052 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1053 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1054 return false;
1055 continue;
1056 }
1057
1058 // getelementptr is also ok, but only a simple form.
1059 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1060 // Must index into the array and into the struct.
1061 if (GEPI->getNumOperands() < 3)
1062 return false;
1063
1064 // Otherwise the GEP is ok.
1065 continue;
1066 }
1067
1068 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Chengb00d9282009-06-02 00:56:07 +00001069 if (!LoadUsingPHIsPerLoad.insert(PN))
1070 // This means some phi nodes are dependent on each other.
1071 // Avoid infinite looping!
1072 return false;
1073 if (!LoadUsingPHIs.insert(PN))
1074 // If we have already analyzed this PHI, then it is safe.
Chris Lattner7f252db2008-12-16 21:24:51 +00001075 continue;
1076
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001077 // Make sure all uses of the PHI are simple enough to transform.
Evan Chengb00d9282009-06-02 00:56:07 +00001078 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1079 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001080 return false;
1081
1082 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 }
Chris Lattner7f252db2008-12-16 21:24:51 +00001084
1085 // Otherwise we don't know what this is, not ok.
1086 return false;
1087 }
1088
1089 return true;
1090}
1091
1092
1093/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1094/// GV are simple enough to perform HeapSRA, return true.
1095static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
Victor Hernandez48c3c542009-09-18 22:35:49 +00001096 Instruction *StoredVal) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001097 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Chengb00d9282009-06-02 00:56:07 +00001098 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner7f252db2008-12-16 21:24:51 +00001099 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1100 ++UI)
Evan Chengb00d9282009-06-02 00:56:07 +00001101 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1102 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1103 LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001104 return false;
Evan Chengb00d9282009-06-02 00:56:07 +00001105 LoadUsingPHIsPerLoad.clear();
1106 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001107
1108 // If we reach here, we know that all uses of the loads and transitive uses
1109 // (through PHI nodes) are simple enough to transform. However, we don't know
1110 // that all inputs the to the PHI nodes are in the same equivalence sets.
1111 // Check to verify that all operands of the PHIs are either PHIS that can be
1112 // transformed, loads from GV, or MI itself.
1113 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1114 E = LoadUsingPHIs.end(); I != E; ++I) {
1115 PHINode *PN = *I;
1116 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1117 Value *InVal = PN->getIncomingValue(op);
1118
1119 // PHI of the stored value itself is ok.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001120 if (InVal == StoredVal) continue;
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001121
1122 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1123 // One of the PHIs in our set is (optimistically) ok.
1124 if (LoadUsingPHIs.count(InPN))
1125 continue;
1126 return false;
1127 }
1128
1129 // Load from GV is ok.
1130 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1131 if (LI->getOperand(0) == GV)
1132 continue;
1133
1134 // UNDEF? NULL?
1135
1136 // Anything else is rejected.
1137 return false;
1138 }
1139 }
1140
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 return true;
1142}
1143
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001144static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1145 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001146 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson175b6542009-07-22 00:24:57 +00001147 LLVMContext &Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001148 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1149
1150 if (FieldNo >= FieldVals.size())
1151 FieldVals.resize(FieldNo+1);
1152
1153 // If we already have this value, just reuse the previously scalarized
1154 // version.
1155 if (Value *FieldVal = FieldVals[FieldNo])
1156 return FieldVal;
1157
1158 // Depending on what instruction this is, we have several cases.
1159 Value *Result;
1160 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1161 // This is a scalarized version of the load from the global. Just create
1162 // a new Load of the scalarized global.
1163 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1164 InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001165 PHIsToRewrite, Context),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001166 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001167 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1168 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1169 // field.
1170 const StructType *ST =
1171 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1172
Owen Anderson086ea052009-07-06 01:34:54 +00001173 Result =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001174 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001175 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001176 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1177 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001178 llvm_unreachable("Unknown usable value");
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001179 Result = 0;
1180 }
1181
1182 return FieldVals[FieldNo] = Result;
Chris Lattner20eef0f2007-09-13 18:00:31 +00001183}
1184
Chris Lattneraf82fb82007-09-13 17:29:05 +00001185/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1186/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001187static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1188 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001189 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson175b6542009-07-22 00:24:57 +00001190 LLVMContext &Context) {
Chris Lattneraf82fb82007-09-13 17:29:05 +00001191 // If this is a comparison against null, handle it.
1192 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1193 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1194 // If we have a setcc of the loaded pointer, we can use a setcc of any
1195 // field.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001196 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson086ea052009-07-06 01:34:54 +00001197 InsertedScalarizedValues, PHIsToRewrite,
1198 Context);
Chris Lattneraf82fb82007-09-13 17:29:05 +00001199
Owen Anderson6601fcd2009-07-09 23:48:35 +00001200 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersonaac28372009-07-31 20:28:14 +00001201 Constant::getNullValue(NPtr->getType()),
Owen Anderson6601fcd2009-07-09 23:48:35 +00001202 SCI->getName());
Chris Lattneraf82fb82007-09-13 17:29:05 +00001203 SCI->replaceAllUsesWith(New);
1204 SCI->eraseFromParent();
1205 return;
1206 }
1207
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001208 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattner20eef0f2007-09-13 18:00:31 +00001209 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1210 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1211 && "Unexpected GEPI!");
Chris Lattneraf82fb82007-09-13 17:29:05 +00001212
Chris Lattner20eef0f2007-09-13 18:00:31 +00001213 // Load the pointer for this field.
1214 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001215 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson086ea052009-07-06 01:34:54 +00001216 InsertedScalarizedValues, PHIsToRewrite,
1217 Context);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001218
1219 // Create the new GEP idx vector.
1220 SmallVector<Value*, 8> GEPIdx;
1221 GEPIdx.push_back(GEPI->getOperand(1));
1222 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1223
Gabor Greifb91ea9d2008-05-15 10:04:30 +00001224 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1225 GEPIdx.begin(), GEPIdx.end(),
Gabor Greifd6da1d02008-04-06 20:25:17 +00001226 GEPI->getName(), GEPI);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001227 GEPI->replaceAllUsesWith(NGEPI);
1228 GEPI->eraseFromParent();
1229 return;
1230 }
Chris Lattnereefff982007-09-13 21:31:36 +00001231
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001232 // Recursively transform the users of PHI nodes. This will lazily create the
1233 // PHIs that are needed for individual elements. Keep track of what PHIs we
1234 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1235 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1236 // already been seen first by another load, so its uses have already been
1237 // processed.
1238 PHINode *PN = cast<PHINode>(LoadUser);
1239 bool Inserted;
1240 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1241 tie(InsertPos, Inserted) =
1242 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1243 if (!Inserted) return;
Chris Lattnereefff982007-09-13 21:31:36 +00001244
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001245 // If this is the first time we've seen this PHI, recursively process all
1246 // users.
Chris Lattnera5e124b2008-12-17 05:42:08 +00001247 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1248 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001249 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1250 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001251 }
Chris Lattneraf82fb82007-09-13 17:29:05 +00001252}
1253
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1255/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1256/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner7f252db2008-12-16 21:24:51 +00001257/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattneraf82fb82007-09-13 17:29:05 +00001258static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001259 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001260 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson175b6542009-07-22 00:24:57 +00001261 LLVMContext &Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001262 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnera5e124b2008-12-17 05:42:08 +00001263 UI != E; ) {
1264 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001265 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1266 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001267 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001268
1269 if (Load->use_empty()) {
1270 Load->eraseFromParent();
1271 InsertedScalarizedValues.erase(Load);
1272 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273}
1274
Victor Hernandez48c3c542009-09-18 22:35:49 +00001275/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1276/// it up into multiple allocations of arrays of the fields.
1277static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV,
1278 CallInst *CI, BitCastInst* BCI,
1279 LLVMContext &Context,
1280 TargetData *TD){
1281 DEBUG(errs() << "SROA HEAP ALLOC: " << *GV << " MALLOC CALL = " << *CI
1282 << " BITCAST = " << *BCI << '\n');
1283 const Type* MAT = getMallocAllocatedType(CI);
1284 const StructType *STy = cast<StructType>(MAT);
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001285 Value* ArraySize = getMallocArraySize(CI, Context, TD);
1286 assert(ArraySize && "not a malloc whose array size can be determined");
Victor Hernandez48c3c542009-09-18 22:35:49 +00001287
1288 // There is guaranteed to be at least one use of the malloc (storing
1289 // it into GV). If there are other uses, change them to be uses of
1290 // the global to simplify later code. This also deletes the store
1291 // into GV.
1292 ReplaceUsesOfMallocWithGlobal(BCI, GV);
1293
1294 // Okay, at this point, there are no users of the malloc. Insert N
1295 // new mallocs at the same place as CI, and N globals.
1296 std::vector<Value*> FieldGlobals;
1297 std::vector<Value*> FieldMallocs;
1298
1299 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1300 const Type *FieldTy = STy->getElementType(FieldNo);
1301 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1302
1303 GlobalVariable *NGV =
1304 new GlobalVariable(*GV->getParent(),
1305 PFieldTy, false, GlobalValue::InternalLinkage,
1306 Constant::getNullValue(PFieldTy),
1307 GV->getName() + ".f" + Twine(FieldNo), GV,
1308 GV->isThreadLocal());
1309 FieldGlobals.push_back(NGV);
1310
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001311 Value *NMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context),
1312 FieldTy, ArraySize,
Victor Hernandez48c3c542009-09-18 22:35:49 +00001313 BCI->getName() + ".f" + Twine(FieldNo));
1314 FieldMallocs.push_back(NMI);
1315 new StoreInst(NMI, NGV, BCI);
1316 }
1317
1318 // The tricky aspect of this transformation is handling the case when malloc
1319 // fails. In the original code, malloc failing would set the result pointer
1320 // of malloc to null. In this case, some mallocs could succeed and others
1321 // could fail. As such, we emit code that looks like this:
1322 // F0 = malloc(field0)
1323 // F1 = malloc(field1)
1324 // F2 = malloc(field2)
1325 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1326 // if (F0) { free(F0); F0 = 0; }
1327 // if (F1) { free(F1); F1 = 0; }
1328 // if (F2) { free(F2); F2 = 0; }
1329 // }
1330 Value *RunningOr = 0;
1331 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1332 Value *Cond = new ICmpInst(BCI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1333 Constant::getNullValue(FieldMallocs[i]->getType()),
1334 "isnull");
1335 if (!RunningOr)
1336 RunningOr = Cond; // First seteq
1337 else
1338 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", BCI);
1339 }
1340
1341 // Split the basic block at the old malloc.
1342 BasicBlock *OrigBB = BCI->getParent();
1343 BasicBlock *ContBB = OrigBB->splitBasicBlock(BCI, "malloc_cont");
1344
1345 // Create the block to check the first condition. Put all these blocks at the
1346 // end of the function as they are unlikely to be executed.
1347 BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
1348 OrigBB->getParent());
1349
1350 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1351 // branch on RunningOr.
1352 OrigBB->getTerminator()->eraseFromParent();
1353 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1354
1355 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1356 // pointer, because some may be null while others are not.
1357 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1358 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1359 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1360 Constant::getNullValue(GVVal->getType()),
1361 "tmp");
1362 BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1363 OrigBB->getParent());
1364 BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1365 OrigBB->getParent());
Victor Hernandez93946082009-10-24 04:23:03 +00001366 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1367 Cmp, NullPtrBlock);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001368
1369 // Fill in FreeBlock.
Victor Hernandez93946082009-10-24 04:23:03 +00001370 CallInst::CreateFree(GVVal, BI);
Victor Hernandez48c3c542009-09-18 22:35:49 +00001371 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1372 FreeBlock);
1373 BranchInst::Create(NextBlock, FreeBlock);
1374
1375 NullPtrBlock = NextBlock;
1376 }
1377
1378 BranchInst::Create(ContBB, NullPtrBlock);
1379
1380 // CI and BCI are no longer needed, remove them.
1381 BCI->eraseFromParent();
1382 CI->eraseFromParent();
1383
1384 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1385 /// update all uses of the load, keep track of what scalarized loads are
1386 /// inserted for a given load.
1387 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1388 InsertedScalarizedValues[GV] = FieldGlobals;
1389
1390 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1391
1392 // Okay, the malloc site is completely handled. All of the uses of GV are now
1393 // loads, and all uses of those loads are simple. Rewrite them to use loads
1394 // of the per-field globals instead.
1395 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1396 Instruction *User = cast<Instruction>(*UI++);
1397
1398 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1399 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1400 Context);
1401 continue;
1402 }
1403
1404 // Must be a store of null.
1405 StoreInst *SI = cast<StoreInst>(User);
1406 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1407 "Unexpected heap-sra user!");
1408
1409 // Insert a store of null into each global.
1410 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1411 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1412 Constant *Null = Constant::getNullValue(PT->getElementType());
1413 new StoreInst(Null, FieldGlobals[i], SI);
1414 }
1415 // Erase the original store.
1416 SI->eraseFromParent();
1417 }
1418
1419 // While we have PHIs that are interesting to rewrite, do it.
1420 while (!PHIsToRewrite.empty()) {
1421 PHINode *PN = PHIsToRewrite.back().first;
1422 unsigned FieldNo = PHIsToRewrite.back().second;
1423 PHIsToRewrite.pop_back();
1424 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1425 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1426
1427 // Add all the incoming values. This can materialize more phis.
1428 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1429 Value *InVal = PN->getIncomingValue(i);
1430 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1431 PHIsToRewrite, Context);
1432 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1433 }
1434 }
1435
1436 // Drop all inter-phi links and any loads that made it this far.
1437 for (DenseMap<Value*, std::vector<Value*> >::iterator
1438 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1439 I != E; ++I) {
1440 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1441 PN->dropAllReferences();
1442 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1443 LI->dropAllReferences();
1444 }
1445
1446 // Delete all the phis and loads now that inter-references are dead.
1447 for (DenseMap<Value*, std::vector<Value*> >::iterator
1448 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1449 I != E; ++I) {
1450 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1451 PN->eraseFromParent();
1452 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1453 LI->eraseFromParent();
1454 }
1455
1456 // The old global is now dead, remove it.
1457 GV->eraseFromParent();
1458
1459 ++NumHeapSRA;
1460 return cast<GlobalVariable>(FieldGlobals[0]);
1461}
1462
Chris Lattner78e568b2008-12-15 21:02:25 +00001463/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1464/// pointer global variable with a single value stored it that is a malloc or
1465/// cast of malloc.
1466static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
Victor Hernandez48c3c542009-09-18 22:35:49 +00001467 CallInst *CI,
1468 BitCastInst *BCI,
1469 Module::global_iterator &GVI,
1470 TargetData *TD,
1471 LLVMContext &Context) {
1472 // If we can't figure out the type being malloced, then we can't optimize.
1473 const Type *AllocTy = getMallocAllocatedType(CI);
1474 assert(AllocTy);
1475
1476 // If this is a malloc of an abstract type, don't touch it.
1477 if (!AllocTy->isSized())
1478 return false;
1479
1480 // We can't optimize this global unless all uses of it are *known* to be
1481 // of the malloc value, not of the null initializer value (consider a use
1482 // that compares the global's value against zero to see if the malloc has
1483 // been reached). To do this, we check to see if all uses of the global
1484 // would trap if the global were null: this proves that they must all
1485 // happen after the malloc.
1486 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1487 return false;
1488
1489 // We can't optimize this if the malloc itself is used in a complex way,
1490 // for example, being stored into multiple globals. This allows the
1491 // malloc to be stored into the specified global, loaded setcc'd, and
1492 // GEP'd. These are all things we could transform to using the global
1493 // for.
1494 {
1495 SmallPtrSet<PHINode*, 8> PHIs;
1496 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1497 return false;
1498 }
1499
1500 // If we have a global that is only initialized with a fixed size malloc,
1501 // transform the program to use global memory instead of malloc'd memory.
1502 // This eliminates dynamic allocation, avoids an indirection accessing the
1503 // data, and exposes the resultant global to further GlobalOpt.
Victor Hernandez89058912009-10-15 20:14:52 +00001504 Value *NElems = getMallocArraySize(CI, Context, TD);
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001505 // We cannot optimize the malloc if we cannot determine malloc array size.
Victor Hernandez89058912009-10-15 20:14:52 +00001506 if (NElems) {
1507 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1508 // Restrict this transformation to only working on small allocations
1509 // (2048 bytes currently), as we don't want to introduce a 16M global or
1510 // something.
1511 if (TD &&
1512 NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1513 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, BCI, Context, TD);
1514 return true;
1515 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00001516
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001517 // If the allocation is an array of structures, consider transforming this
1518 // into multiple malloc'd arrays, one for each field. This is basically
1519 // SRoA for malloc'd memory.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001520
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001521 // If this is an allocation of a fixed size array of structs, analyze as a
1522 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1523 if (!isArrayMalloc(CI, Context, TD))
1524 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1525 AllocTy = AT->getElementType();
Victor Hernandez48c3c542009-09-18 22:35:49 +00001526
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001527 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1528 // This the structure has an unreasonable number of fields, leave it
1529 // alone.
1530 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1531 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, BCI)) {
Victor Hernandez48c3c542009-09-18 22:35:49 +00001532
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001533 // If this is a fixed size array, transform the Malloc to be an alloc of
1534 // structs. malloc [100 x struct],1 -> malloc struct, 100
1535 if (const ArrayType *AT =
1536 dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1537 Value* NumElements = ConstantInt::get(Type::getInt32Ty(Context),
1538 AT->getNumElements());
1539 Value* NewMI = CallInst::CreateMalloc(CI, TD->getIntPtrType(Context),
1540 AllocSTy, NumElements,
1541 BCI->getName());
1542 Value *Cast = new BitCastInst(NewMI, getMallocType(CI), "tmp", CI);
1543 BCI->replaceAllUsesWith(Cast);
1544 BCI->eraseFromParent();
1545 CI->eraseFromParent();
1546 BCI = cast<BitCastInst>(NewMI);
1547 CI = extractMallocCallFromBitCast(NewMI);
1548 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00001549
Victor Hernandez2d1e0842009-10-16 23:12:25 +00001550 GVI = PerformHeapAllocSRoA(GV, CI, BCI, Context, TD);
1551 return true;
1552 }
Victor Hernandez48c3c542009-09-18 22:35:49 +00001553 }
1554 }
1555
1556 return false;
1557}
1558
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001559// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1560// that only one value (besides its initializer) is ever stored to the global.
1561static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1562 Module::global_iterator &GVI,
Dan Gohmanf657fcd2009-08-14 00:11:03 +00001563 TargetData *TD, LLVMContext &Context) {
Chris Lattner2e729112008-12-15 21:20:32 +00001564 // Ignore no-op GEPs and bitcasts.
1565 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566
1567 // 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.
1571 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1572 GV->getInitializer()->isNullValue()) {
1573 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1574 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson086ea052009-07-06 01:34:54 +00001575 SOVC =
Owen Anderson02b48c32009-07-29 18:55:55 +00001576 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577
1578 // Optimize away any trapping uses of the loaded value.
Owen Anderson086ea052009-07-06 01:34:54 +00001579 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 return true;
Victor Hernandez48c3c542009-09-18 22:35:49 +00001581 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1582 if (getMallocAllocatedType(CI)) {
1583 BitCastInst* BCI = NULL;
1584 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
1585 UI != E; )
1586 BCI = dyn_cast<BitCastInst>(cast<Instruction>(*UI++));
1587 if (BCI &&
1588 TryToOptimizeStoreOfMallocToGlobal(GV, CI, BCI, GVI, TD, Context))
1589 return true;
1590 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 }
1592 }
1593
1594 return false;
1595}
1596
Chris Lattnerece46db2008-01-14 01:17:44 +00001597/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1598/// two values ever stored into GV are its initializer and OtherVal. See if we
1599/// can shrink the global into a boolean and select between the two values
1600/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson086ea052009-07-06 01:34:54 +00001601static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
Owen Anderson175b6542009-07-22 00:24:57 +00001602 LLVMContext &Context) {
Chris Lattnerece46db2008-01-14 01:17:44 +00001603 const Type *GVElType = GV->getType()->getElementType();
1604
1605 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001606 // an FP value, pointer or vector, don't do this optimization because a select
1607 // between them is very expensive and unlikely to lead to later
1608 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1609 // where v1 and v2 both require constant pool loads, a big loss.
Owen Anderson35b47072009-08-13 21:58:54 +00001610 if (GVElType == Type::getInt1Ty(Context) || GVElType->isFloatingPoint() ||
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001611 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattnerece46db2008-01-14 01:17:44 +00001612 return false;
1613
1614 // Walk the use list of the global seeing if all the uses are load or store.
1615 // If there is anything else, bail out.
1616 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel9b951552009-03-06 01:39:36 +00001617 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattnerece46db2008-01-14 01:17:44 +00001618 return false;
1619
Chris Lattner8a6411c2009-08-23 04:37:46 +00001620 DEBUG(errs() << " *** SHRINKING TO BOOL: " << *GV);
Chris Lattnerece46db2008-01-14 01:17:44 +00001621
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622 // Create the new global, initializing it to false.
Owen Anderson35b47072009-08-13 21:58:54 +00001623 GlobalVariable *NewGV = new GlobalVariable(Context,
1624 Type::getInt1Ty(Context), false,
Owen Anderson4f720fa2009-07-31 17:39:07 +00001625 GlobalValue::InternalLinkage, ConstantInt::getFalse(Context),
Nick Lewycky74e96b72009-05-03 03:49:08 +00001626 GV->getName()+".b",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627 GV->isThreadLocal());
1628 GV->getParent()->getGlobalList().insert(GV, NewGV);
1629
1630 Constant *InitVal = GV->getInitializer();
Owen Anderson35b47072009-08-13 21:58:54 +00001631 assert(InitVal->getType() != Type::getInt1Ty(Context) &&
1632 "No reason to shrink to bool!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633
1634 // If initialized to zero and storing one into the global, we can use a cast
1635 // instead of a select to synthesize the desired value.
1636 bool IsOneZero = false;
1637 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1638 IsOneZero = InitVal->isNullValue() && CI->isOne();
1639
1640 while (!GV->use_empty()) {
Devang Patel9b951552009-03-06 01:39:36 +00001641 Instruction *UI = cast<Instruction>(GV->use_back());
1642 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643 // Change the store into a boolean store.
1644 bool StoringOther = SI->getOperand(0) == OtherVal;
1645 // Only do this if we weren't storing a loaded value.
1646 Value *StoreVal;
1647 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson35b47072009-08-13 21:58:54 +00001648 StoreVal = ConstantInt::get(Type::getInt1Ty(Context), StoringOther);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 else {
1650 // Otherwise, we are storing a previously loaded copy. To do this,
1651 // change the copy from copying the original value to just copying the
1652 // bool.
1653 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1654
1655 // If we're already replaced the input, StoredVal will be a cast or
1656 // select instruction. If not, it will be a load of the original
1657 // global.
1658 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1659 assert(LI->getOperand(0) == GV && "Not a copy!");
1660 // Insert a new load, to preserve the saved value.
1661 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1662 } else {
1663 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1664 "This is not a form that we understand!");
1665 StoreVal = StoredVal->getOperand(0);
1666 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1667 }
1668 }
1669 new StoreInst(StoreVal, NewGV, SI);
Devang Patel9b951552009-03-06 01:39:36 +00001670 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671 // Change the load into a load of bool then a select.
Devang Patel9b951552009-03-06 01:39:36 +00001672 LoadInst *LI = cast<LoadInst>(UI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1674 Value *NSI;
1675 if (IsOneZero)
1676 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1677 else
Gabor Greifd6da1d02008-04-06 20:25:17 +00001678 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 NSI->takeName(LI);
1680 LI->replaceAllUsesWith(NSI);
Devang Patel9b951552009-03-06 01:39:36 +00001681 }
1682 UI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683 }
1684
1685 GV->eraseFromParent();
Chris Lattnerece46db2008-01-14 01:17:44 +00001686 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687}
1688
1689
1690/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1691/// it if possible. If we make a change, return true.
1692bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1693 Module::global_iterator &GVI) {
Chris Lattner4cd08c22008-12-16 07:34:30 +00001694 SmallPtrSet<PHINode*, 16> PHIUsers;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001695 GlobalStatus GS;
1696 GV->removeDeadConstantUsers();
1697
1698 if (GV->use_empty()) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001699 DEBUG(errs() << "GLOBAL DEAD: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001700 GV->eraseFromParent();
1701 ++NumDeleted;
1702 return true;
1703 }
1704
1705 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1706#if 0
1707 cerr << "Global: " << *GV;
1708 cerr << " isLoaded = " << GS.isLoaded << "\n";
1709 cerr << " StoredType = ";
1710 switch (GS.StoredType) {
1711 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1712 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1713 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1714 case GlobalStatus::isStored: cerr << "stored\n"; break;
1715 }
1716 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1717 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1718 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1719 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1720 << "\n";
1721 cerr << " HasMultipleAccessingFunctions = "
1722 << GS.HasMultipleAccessingFunctions << "\n";
1723 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001724 cerr << "\n";
1725#endif
1726
1727 // If this is a first class global and has only one accessing function
1728 // and this function is main (which we know is not recursive we can make
1729 // this global a local variable) we replace the global with a local alloca
1730 // in this function.
1731 //
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001732 // NOTE: It doesn't make sense to promote non single-value types since we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 // are just replacing static memory to stack memory.
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001734 //
1735 // If the global is in different address space, don't bring it to stack.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001736 if (!GS.HasMultipleAccessingFunctions &&
1737 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001738 GV->getType()->getElementType()->isSingleValueType() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001740 GS.AccessingFunction->hasExternalLinkage() &&
1741 GV->getType()->getAddressSpace() == 0) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001742 DEBUG(errs() << "LOCALIZING GLOBAL: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001743 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1744 const Type* ElemTy = GV->getType()->getElementType();
1745 // FIXME: Pass Global's alignment when globals have alignment
Owen Anderson140166d2009-07-15 23:53:25 +00001746 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747 if (!isa<UndefValue>(GV->getInitializer()))
1748 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1749
1750 GV->replaceAllUsesWith(Alloca);
1751 GV->eraseFromParent();
1752 ++NumLocalized;
1753 return true;
1754 }
1755
1756 // If the global is never loaded (but may be stored to), it is dead.
1757 // Delete it now.
1758 if (!GS.isLoaded) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001759 DEBUG(errs() << "GLOBAL NEVER LOADED: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760
1761 // Delete any stores we can find to the global. We may not be able to
1762 // make it completely dead though.
Owen Andersond4d90a02009-07-06 18:42:36 +00001763 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
Owen Anderson175b6542009-07-22 00:24:57 +00001764 GV->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765
1766 // If the global is dead now, delete it.
1767 if (GV->use_empty()) {
1768 GV->eraseFromParent();
1769 ++NumDeleted;
1770 Changed = true;
1771 }
1772 return Changed;
1773
1774 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001775 DEBUG(errs() << "MARKING CONSTANT: " << *GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776 GV->setConstant(true);
1777
1778 // Clean up any obviously simplifiable users now.
Owen Anderson175b6542009-07-22 00:24:57 +00001779 CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001780
1781 // If the global is dead now, just nuke it.
1782 if (GV->use_empty()) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001783 DEBUG(errs() << " *** Marking constant allowed us to simplify "
1784 << "all users and delete global!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 GV->eraseFromParent();
1786 ++NumDeleted;
1787 }
1788
1789 ++NumMarked;
1790 return true;
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001791 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Dan Gohmanf657fcd2009-08-14 00:11:03 +00001792 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1793 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD,
1794 GV->getContext())) {
1795 GVI = FirstNewGV; // Don't skip the newly produced globals!
1796 return true;
1797 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1799 // If the initial value for the global was an undef value, and if only
1800 // one other value was stored into it, we can just change the
Duncan Sands25464152009-01-13 13:48:44 +00001801 // initializer to be the stored value, then delete all stores to the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802 // global. This allows us to mark it constant.
1803 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1804 if (isa<UndefValue>(GV->getInitializer())) {
1805 // Change the initial value here.
1806 GV->setInitializer(SOVConstant);
1807
1808 // Clean up any obviously simplifiable users now.
Owen Anderson175b6542009-07-22 00:24:57 +00001809 CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1810 GV->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811
1812 if (GV->use_empty()) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001813 DEBUG(errs() << " *** Substituting initializer allowed us to "
1814 << "simplify all users and delete global!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001815 GV->eraseFromParent();
1816 ++NumDeleted;
1817 } else {
1818 GVI = GV;
1819 }
1820 ++NumSubstitute;
1821 return true;
1822 }
1823
1824 // Try to optimize globals based on the knowledge that only one value
1825 // (besides its initializer) is ever stored to the global.
1826 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Dan Gohmanf657fcd2009-08-14 00:11:03 +00001827 getAnalysisIfAvailable<TargetData>(),
1828 GV->getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829 return true;
1830
1831 // Otherwise, if the global was not a boolean, we can shrink it to be a
1832 // boolean.
1833 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Anderson175b6542009-07-22 00:24:57 +00001834 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 ++NumShrunkToBool;
1836 return true;
1837 }
1838 }
1839 }
1840 return false;
1841}
1842
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001843/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1844/// function, changing them to FastCC.
1845static void ChangeCalleesToFastCall(Function *F) {
1846 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001847 CallSite User(cast<Instruction>(*UI));
1848 User.setCallingConv(CallingConv::Fast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849 }
1850}
1851
Devang Pateld222f862008-09-25 21:00:45 +00001852static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner1c8733e2008-03-12 17:45:29 +00001853 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Pateld222f862008-09-25 21:00:45 +00001854 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands551ec902008-02-18 17:32:13 +00001855 continue;
1856
Duncan Sands551ec902008-02-18 17:32:13 +00001857 // There can be only one.
Devang Pateld222f862008-09-25 21:00:45 +00001858 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001859 }
1860
1861 return Attrs;
1862}
1863
1864static void RemoveNestAttribute(Function *F) {
Devang Pateld222f862008-09-25 21:00:45 +00001865 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001866 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001867 CallSite User(cast<Instruction>(*UI));
Devang Pateld222f862008-09-25 21:00:45 +00001868 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001869 }
1870}
1871
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872bool GlobalOpt::OptimizeFunctions(Module &M) {
1873 bool Changed = false;
1874 // Optimize functions.
1875 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1876 Function *F = FI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001877 // Functions without names cannot be referenced outside this module.
1878 if (!F->hasName() && !F->isDeclaration())
1879 F->setLinkage(GlobalValue::InternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880 F->removeDeadConstantUsers();
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001881 if (F->use_empty() && (F->hasLocalLinkage() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 F->hasLinkOnceLinkage())) {
1883 M.getFunctionList().erase(F);
1884 Changed = true;
1885 ++NumFnDeleted;
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001886 } else if (F->hasLocalLinkage()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001887 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad1379d592009-06-10 08:41:11 +00001888 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001889 // If this function has C calling conventions, is not a varargs
1890 // function, and is only called directly, promote it to use the Fast
1891 // calling convention.
1892 F->setCallingConv(CallingConv::Fast);
1893 ChangeCalleesToFastCall(F);
1894 ++NumFastCallFns;
1895 Changed = true;
1896 }
1897
Devang Pateld222f862008-09-25 21:00:45 +00001898 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad1379d592009-06-10 08:41:11 +00001899 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001900 // The function is not used by a trampoline intrinsic, so it is safe
1901 // to remove the 'nest' attribute.
1902 RemoveNestAttribute(F);
1903 ++NumNestRemoved;
1904 Changed = true;
1905 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906 }
1907 }
1908 return Changed;
1909}
1910
1911bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1912 bool Changed = false;
1913 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1914 GVI != E; ) {
1915 GlobalVariable *GV = GVI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001916 // Global variables without names cannot be referenced outside this module.
1917 if (!GV->hasName() && !GV->isDeclaration())
1918 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001919 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920 GV->hasInitializer())
1921 Changed |= ProcessInternalGlobal(GV, GVI);
1922 }
1923 return Changed;
1924}
1925
1926/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1927/// initializers have an init priority of 65535.
1928GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1929 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1930 I != E; ++I)
1931 if (I->getName() == "llvm.global_ctors") {
1932 // Found it, verify it's an array of { int, void()* }.
1933 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1934 if (!ATy) return 0;
1935 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1936 if (!STy || STy->getNumElements() != 2 ||
Owen Anderson35b47072009-08-13 21:58:54 +00001937 STy->getElementType(0) != Type::getInt32Ty(M.getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001938 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1939 if (!PFTy) return 0;
1940 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Owen Anderson35b47072009-08-13 21:58:54 +00001941 if (!FTy || FTy->getReturnType() != Type::getVoidTy(M.getContext()) ||
1942 FTy->isVarArg() || FTy->getNumParams() != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943 return 0;
1944
1945 // Verify that the initializer is simple enough for us to handle.
Dan Gohman5e423ed2009-08-19 18:20:44 +00001946 if (!I->hasDefinitiveInitializer()) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001947 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1948 if (!CA) return 0;
Gabor Greif20f03f52008-05-29 01:59:18 +00001949 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1950 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001951 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1952 continue;
1953
1954 // Must have a function or null ptr.
1955 if (!isa<Function>(CS->getOperand(1)))
1956 return 0;
1957
1958 // Init priority must be standard.
1959 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1960 if (!CI || CI->getZExtValue() != 65535)
1961 return 0;
1962 } else {
1963 return 0;
1964 }
1965
1966 return I;
1967 }
1968 return 0;
1969}
1970
1971/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1972/// return a list of the functions and null terminator as a vector.
1973static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1974 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1975 std::vector<Function*> Result;
1976 Result.reserve(CA->getNumOperands());
Gabor Greif20f03f52008-05-29 01:59:18 +00001977 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1978 ConstantStruct *CS = cast<ConstantStruct>(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001979 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1980 }
1981 return Result;
1982}
1983
1984/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1985/// specified array, returning the new global to use.
1986static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson086ea052009-07-06 01:34:54 +00001987 const std::vector<Function*> &Ctors,
Owen Anderson175b6542009-07-22 00:24:57 +00001988 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 // If we made a change, reassemble the initializer list.
1990 std::vector<Constant*> CSVals;
Owen Anderson35b47072009-08-13 21:58:54 +00001991 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(Context), 65535));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 CSVals.push_back(0);
1993
1994 // Create the new init list.
1995 std::vector<Constant*> CAList;
1996 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1997 if (Ctors[i]) {
1998 CSVals[1] = Ctors[i];
1999 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00002000 const Type *FTy = FunctionType::get(Type::getVoidTy(Context), false);
Owen Anderson6b6e2d92009-07-29 22:17:13 +00002001 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersonaac28372009-07-31 20:28:14 +00002002 CSVals[1] = Constant::getNullValue(PFTy);
Owen Anderson35b47072009-08-13 21:58:54 +00002003 CSVals[0] = ConstantInt::get(Type::getInt32Ty(Context), 2147483647);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004 }
Nick Lewycky9229fdb2009-09-19 20:30:26 +00002005 CAList.push_back(ConstantStruct::get(Context, CSVals, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002006 }
2007
2008 // Create the array initializer.
2009 const Type *StructTy =
Nick Lewycky9229fdb2009-09-19 20:30:26 +00002010 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson7b4f9f82009-07-28 18:32:17 +00002011 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Nick Lewycky9229fdb2009-09-19 20:30:26 +00002012 CAList.size()), CAList);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013
2014 // If we didn't change the number of elements, don't create a new GV.
2015 if (CA->getType() == GCL->getInitializer()->getType()) {
2016 GCL->setInitializer(CA);
2017 return GCL;
2018 }
2019
2020 // Create the new global and insert it next to the existing list.
Owen Anderson175b6542009-07-22 00:24:57 +00002021 GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(),
Owen Andersone0f136d2009-07-08 01:26:06 +00002022 GCL->isConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002023 GCL->getLinkage(), CA, "",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002024 GCL->isThreadLocal());
2025 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2026 NGV->takeName(GCL);
2027
2028 // Nuke the old list, replacing any uses with the new one.
2029 if (!GCL->use_empty()) {
2030 Constant *V = NGV;
2031 if (V->getType() != GCL->getType())
Owen Anderson02b48c32009-07-29 18:55:55 +00002032 V = ConstantExpr::getBitCast(V, GCL->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002033 GCL->replaceAllUsesWith(V);
2034 }
2035 GCL->eraseFromParent();
2036
2037 if (Ctors.size())
2038 return NGV;
2039 else
2040 return 0;
2041}
2042
2043
Chris Lattner4cd08c22008-12-16 07:34:30 +00002044static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002045 Value *V) {
2046 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2047 Constant *R = ComputedValues[V];
2048 assert(R && "Reference to an uncomputed value!");
2049 return R;
2050}
2051
2052/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2053/// enough for us to understand. In particular, if it is a cast of something,
2054/// we punt. We basically just support direct accesses to globals and GEP's of
2055/// globals. This should be kept up to date with CommitValueTo.
Owen Anderson175b6542009-07-22 00:24:57 +00002056static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
Dan Gohman9524ee62009-09-07 22:42:05 +00002057 // Conservatively, avoid aggregate types. This is because we don't
2058 // want to worry about them partially overlapping other stores.
2059 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2060 return false;
2061
Dan Gohman278fbe62009-09-07 22:31:26 +00002062 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2063 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2064 // external globals.
2065 return GV->hasDefinitiveInitializer();
2066
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002067 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2068 // Handle a constantexpr gep.
2069 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohman0c834c02009-09-07 22:40:13 +00002070 isa<GlobalVariable>(CE->getOperand(0)) &&
2071 cast<GEPOperator>(CE)->isInBounds()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002072 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman278fbe62009-09-07 22:31:26 +00002073 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2074 // external globals.
2075 if (!GV->hasDefinitiveInitializer())
2076 return false;
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002077
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002078 // The first index must be zero.
Dan Gohmandb050e92009-09-10 23:37:55 +00002079 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002080 if (!CI || !CI->isZero()) return false;
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002081
2082 // The remaining indices must be compile-time known integers within the
Dan Gohmandb050e92009-09-10 23:37:55 +00002083 // notional bounds of the corresponding static array types.
2084 if (!CE->isGEPWithNoNotionalOverIndexing())
2085 return false;
Dan Gohmanc2723ad2009-09-07 22:44:55 +00002086
Dan Gohmanf49f7b02009-10-05 16:36:26 +00002087 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088 }
2089 return false;
2090}
2091
2092/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2093/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2094/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2095static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson086ea052009-07-06 01:34:54 +00002096 ConstantExpr *Addr, unsigned OpNo,
Owen Anderson175b6542009-07-22 00:24:57 +00002097 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098 // Base case of the recursion.
2099 if (OpNo == Addr->getNumOperands()) {
2100 assert(Val->getType() == Init->getType() && "Type mismatch!");
2101 return Val;
2102 }
2103
2104 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2105 std::vector<Constant*> Elts;
2106
2107 // Break up the constant into its elements.
2108 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002109 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2110 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002111 } else if (isa<ConstantAggregateZero>(Init)) {
2112 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersonaac28372009-07-31 20:28:14 +00002113 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002114 } else if (isa<UndefValue>(Init)) {
2115 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersonb99ecca2009-07-30 23:03:37 +00002116 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002117 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002118 llvm_unreachable("This code is out of sync with "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119 " ConstantFoldLoadThroughGEPConstantExpr");
2120 }
2121
2122 // Replace the element that we are supposed to.
2123 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2124 unsigned Idx = CU->getZExtValue();
2125 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson086ea052009-07-06 01:34:54 +00002126 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127
2128 // Return the modified struct.
Owen Andersond2ed7452009-08-05 23:16:16 +00002129 return ConstantStruct::get(Context, &Elts[0], Elts.size(), STy->isPacked());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130 } else {
2131 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2132 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2133
2134 // Break up the array into elements.
2135 std::vector<Constant*> Elts;
2136 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002137 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2138 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002139 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Andersonaac28372009-07-31 20:28:14 +00002140 Constant *Elt = Constant::getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141 Elts.assign(ATy->getNumElements(), Elt);
2142 } else if (isa<UndefValue>(Init)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +00002143 Constant *Elt = UndefValue::get(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002144 Elts.assign(ATy->getNumElements(), Elt);
2145 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002146 llvm_unreachable("This code is out of sync with "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002147 " ConstantFoldLoadThroughGEPConstantExpr");
2148 }
2149
2150 assert(CI->getZExtValue() < ATy->getNumElements());
2151 Elts[CI->getZExtValue()] =
Owen Anderson086ea052009-07-06 01:34:54 +00002152 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
Owen Anderson7b4f9f82009-07-28 18:32:17 +00002153 return ConstantArray::get(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154 }
2155}
2156
2157/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2158/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson086ea052009-07-06 01:34:54 +00002159static void CommitValueTo(Constant *Val, Constant *Addr,
Owen Anderson175b6542009-07-22 00:24:57 +00002160 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2162 assert(GV->hasInitializer());
2163 GV->setInitializer(Val);
2164 return;
2165 }
2166
2167 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2168 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2169
2170 Constant *Init = GV->getInitializer();
Owen Anderson086ea052009-07-06 01:34:54 +00002171 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172 GV->setInitializer(Init);
2173}
2174
2175/// ComputeLoadResult - Return the value that would be computed by a load from
2176/// P after the stores reflected by 'memory' have been performed. If we can't
2177/// decide, return null.
2178static Constant *ComputeLoadResult(Constant *P,
Owen Andersond4d90a02009-07-06 18:42:36 +00002179 const DenseMap<Constant*, Constant*> &Memory,
Owen Anderson175b6542009-07-22 00:24:57 +00002180 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181 // If this memory location has been recently stored, use the stored value: it
2182 // is the most up-to-date.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002183 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002184 if (I != Memory.end()) return I->second;
2185
2186 // Access it.
2187 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
Dan Gohman5e423ed2009-08-19 18:20:44 +00002188 if (GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 return GV->getInitializer();
2190 return 0;
2191 }
2192
2193 // Handle a constantexpr getelementptr.
2194 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2195 if (CE->getOpcode() == Instruction::GetElementPtr &&
2196 isa<GlobalVariable>(CE->getOperand(0))) {
2197 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Dan Gohman5e423ed2009-08-19 18:20:44 +00002198 if (GV->hasDefinitiveInitializer())
Dan Gohmanf49f7b02009-10-05 16:36:26 +00002199 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200 }
2201
2202 return 0; // don't know how to evaluate.
2203}
2204
2205/// EvaluateFunction - Evaluate a call to function F, returning true if
2206/// successful, false if we can't evaluate it. ActualArgs contains the formal
2207/// arguments for the function.
2208static bool EvaluateFunction(Function *F, Constant *&RetVal,
Duncan Sands408bbf32009-08-17 14:33:27 +00002209 const SmallVectorImpl<Constant*> &ActualArgs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 std::vector<Function*> &CallStack,
Chris Lattner4cd08c22008-12-16 07:34:30 +00002211 DenseMap<Constant*, Constant*> &MutatedMemory,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002212 std::vector<GlobalVariable*> &AllocaTmps) {
2213 // Check to see if this function is already executing (recursion). If so,
2214 // bail out. TODO: we might want to accept limited recursion.
2215 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2216 return false;
2217
Owen Anderson175b6542009-07-22 00:24:57 +00002218 LLVMContext &Context = F->getContext();
Owen Anderson086ea052009-07-06 01:34:54 +00002219
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002220 CallStack.push_back(F);
2221
2222 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002223 DenseMap<Value*, Constant*> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002224
2225 // Initialize arguments to the incoming values specified.
2226 unsigned ArgNo = 0;
2227 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2228 ++AI, ++ArgNo)
2229 Values[AI] = ActualArgs[ArgNo];
2230
2231 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2232 /// we can only evaluate any one basic block at most once. This set keeps
2233 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002234 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235
2236 // CurInst - The current instruction we're evaluating.
2237 BasicBlock::iterator CurInst = F->begin()->begin();
2238
2239 // This is the main evaluation loop.
2240 while (1) {
2241 Constant *InstResult = 0;
2242
2243 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2244 if (SI->isVolatile()) return false; // no volatile accesses.
2245 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Andersond4d90a02009-07-06 18:42:36 +00002246 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247 // If this is too complex for us to commit, reject it.
2248 return false;
2249 Constant *Val = getVal(Values, SI->getOperand(0));
2250 MutatedMemory[Ptr] = Val;
2251 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002252 InstResult = ConstantExpr::get(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253 getVal(Values, BO->getOperand(0)),
2254 getVal(Values, BO->getOperand(1)));
2255 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002256 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002257 getVal(Values, CI->getOperand(0)),
2258 getVal(Values, CI->getOperand(1)));
2259 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002260 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002261 getVal(Values, CI->getOperand(0)),
2262 CI->getType());
2263 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002264 InstResult =
Owen Anderson02b48c32009-07-29 18:55:55 +00002265 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002266 getVal(Values, SI->getOperand(1)),
2267 getVal(Values, SI->getOperand(2)));
2268 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2269 Constant *P = getVal(Values, GEP->getOperand(0));
2270 SmallVector<Constant*, 8> GEPOps;
Gabor Greif20f03f52008-05-29 01:59:18 +00002271 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2272 i != e; ++i)
2273 GEPOps.push_back(getVal(Values, *i));
Dan Gohman6d907d02009-09-07 22:34:43 +00002274 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2275 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2276 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2278 if (LI->isVolatile()) return false; // no volatile accesses.
2279 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Andersond4d90a02009-07-06 18:42:36 +00002280 MutatedMemory, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 if (InstResult == 0) return false; // Could not evaluate load.
2282 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2283 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2284 const Type *Ty = AI->getType()->getElementType();
Owen Anderson175b6542009-07-22 00:24:57 +00002285 AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286 GlobalValue::InternalLinkage,
Owen Andersonb99ecca2009-07-30 23:03:37 +00002287 UndefValue::get(Ty),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288 AI->getName()));
2289 InstResult = AllocaTmps.back();
2290 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel5b1082b2009-03-09 23:04:12 +00002291
2292 // Debug info can safely be ignored here.
2293 if (isa<DbgInfoIntrinsic>(CI)) {
2294 ++CurInst;
2295 continue;
2296 }
2297
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002298 // Cannot handle inline asm.
2299 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2300
2301 // Resolve function pointers.
2302 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2303 if (!Callee) return false; // Cannot resolve.
2304
Duncan Sands408bbf32009-08-17 14:33:27 +00002305 SmallVector<Constant*, 8> Formals;
Gabor Greif20f03f52008-05-29 01:59:18 +00002306 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2307 i != e; ++i)
2308 Formals.push_back(getVal(Values, *i));
Duncan Sands408bbf32009-08-17 14:33:27 +00002309
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310 if (Callee->isDeclaration()) {
2311 // If this is a function we can constant fold, do it.
Duncan Sands408bbf32009-08-17 14:33:27 +00002312 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 Formals.size())) {
2314 InstResult = C;
2315 } else {
2316 return false;
2317 }
2318 } else {
2319 if (Callee->getFunctionType()->isVarArg())
2320 return false;
2321
2322 Constant *RetVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002323 // Execute the call, if successful, use the return value.
2324 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2325 MutatedMemory, AllocaTmps))
2326 return false;
2327 InstResult = RetVal;
2328 }
2329 } else if (isa<TerminatorInst>(CurInst)) {
2330 BasicBlock *NewBB = 0;
2331 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2332 if (BI->isUnconditional()) {
2333 NewBB = BI->getSuccessor(0);
2334 } else {
2335 ConstantInt *Cond =
2336 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2337 if (!Cond) return false; // Cannot determine.
2338
2339 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2340 }
2341 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2342 ConstantInt *Val =
2343 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2344 if (!Val) return false; // Cannot determine.
2345 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2346 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2347 if (RI->getNumOperands())
2348 RetVal = getVal(Values, RI->getOperand(0));
2349
2350 CallStack.pop_back(); // return from fn.
2351 return true; // We succeeded at evaluating this ctor!
2352 } else {
2353 // invoke, unwind, unreachable.
2354 return false; // Cannot handle this terminator.
2355 }
2356
2357 // Okay, we succeeded in evaluating this control flow. See if we have
2358 // executed the new block before. If so, we have a looping function,
2359 // which we cannot evaluate in reasonable time.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002360 if (!ExecutedBlocks.insert(NewBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002361 return false; // looped!
2362
2363 // Okay, we have never been in this block before. Check to see if there
2364 // are any PHI nodes. If so, evaluate them with information about where
2365 // we came from.
2366 BasicBlock *OldBB = CurInst->getParent();
2367 CurInst = NewBB->begin();
2368 PHINode *PN;
2369 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2370 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2371
2372 // Do NOT increment CurInst. We know that the terminator had no value.
2373 continue;
2374 } else {
2375 // Did not know how to evaluate this!
2376 return false;
2377 }
2378
2379 if (!CurInst->use_empty())
2380 Values[CurInst] = InstResult;
2381
2382 // Advance program counter.
2383 ++CurInst;
2384 }
2385}
2386
2387/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2388/// we can. Return true if we can, false otherwise.
2389static bool EvaluateStaticConstructor(Function *F) {
2390 /// MutatedMemory - For each store we execute, we update this map. Loads
2391 /// check this to get the most up-to-date value. If evaluation is successful,
2392 /// this state is committed to the process.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002393 DenseMap<Constant*, Constant*> MutatedMemory;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002394
2395 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2396 /// to represent its body. This vector is needed so we can delete the
2397 /// temporary globals when we are done.
2398 std::vector<GlobalVariable*> AllocaTmps;
2399
2400 /// CallStack - This is used to detect recursion. In pathological situations
2401 /// we could hit exponential behavior, but at least there is nothing
2402 /// unbounded.
2403 std::vector<Function*> CallStack;
2404
2405 // Call the function.
2406 Constant *RetValDummy;
Duncan Sands408bbf32009-08-17 14:33:27 +00002407 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2408 SmallVector<Constant*, 0>(), CallStack,
2409 MutatedMemory, AllocaTmps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002410 if (EvalSuccess) {
2411 // We succeeded at evaluation: commit the result.
Daniel Dunbar005975c2009-07-25 00:23:56 +00002412 DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2413 << F->getName() << "' to " << MutatedMemory.size()
2414 << " stores.\n");
Chris Lattner4cd08c22008-12-16 07:34:30 +00002415 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002416 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson086ea052009-07-06 01:34:54 +00002417 CommitValueTo(I->second, I->first, F->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002418 }
2419
2420 // At this point, we are done interpreting. If we created any 'alloca'
2421 // temporaries, release them now.
2422 while (!AllocaTmps.empty()) {
2423 GlobalVariable *Tmp = AllocaTmps.back();
2424 AllocaTmps.pop_back();
2425
2426 // If there are still users of the alloca, the program is doing something
2427 // silly, e.g. storing the address of the alloca somewhere and using it
2428 // later. Since this is undefined, we'll just make it be null.
2429 if (!Tmp->use_empty())
Owen Andersonaac28372009-07-31 20:28:14 +00002430 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002431 delete Tmp;
2432 }
2433
2434 return EvalSuccess;
2435}
2436
2437
2438
2439/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2440/// Return true if anything changed.
2441bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2442 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2443 bool MadeChange = false;
2444 if (Ctors.empty()) return false;
2445
2446 // Loop over global ctors, optimizing them when we can.
2447 for (unsigned i = 0; i != Ctors.size(); ++i) {
2448 Function *F = Ctors[i];
2449 // Found a null terminator in the middle of the list, prune off the rest of
2450 // the list.
2451 if (F == 0) {
2452 if (i != Ctors.size()-1) {
2453 Ctors.resize(i+1);
2454 MadeChange = true;
2455 }
2456 break;
2457 }
2458
2459 // We cannot simplify external ctor functions.
2460 if (F->empty()) continue;
2461
2462 // If we can evaluate the ctor at compile time, do.
2463 if (EvaluateStaticConstructor(F)) {
2464 Ctors.erase(Ctors.begin()+i);
2465 MadeChange = true;
2466 --i;
2467 ++NumCtorsEvaluated;
2468 continue;
2469 }
2470 }
2471
2472 if (!MadeChange) return false;
2473
Owen Anderson175b6542009-07-22 00:24:57 +00002474 GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002475 return true;
2476}
2477
Duncan Sands0c7b6332009-03-06 10:21:56 +00002478bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002479 bool Changed = false;
2480
Duncan Sands0f064b92009-01-07 20:01:06 +00002481 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002482 I != E;) {
2483 Module::alias_iterator J = I++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00002484 // Aliases without names cannot be referenced outside this module.
2485 if (!J->hasName() && !J->isDeclaration())
2486 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002487 // If the aliasee may change at link time, nothing can be done - bail out.
2488 if (J->mayBeOverridden())
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002489 continue;
2490
Duncan Sandse7f431f2009-02-15 09:56:08 +00002491 Constant *Aliasee = J->getAliasee();
2492 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7531ad62009-02-18 17:55:38 +00002493 Target->removeDeadConstantUsers();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002494 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2495
2496 // Make all users of the alias use the aliasee instead.
2497 if (!J->use_empty()) {
2498 J->replaceAllUsesWith(Aliasee);
2499 ++NumAliasesResolved;
2500 Changed = true;
2501 }
2502
2503 // If the aliasee has internal linkage, give it the name and linkage
2504 // of the alias, and delete the alias. This turns:
2505 // define internal ... @f(...)
2506 // @a = alias ... @f
2507 // into:
2508 // define ... @a(...)
Duncan Sands8f723612009-02-17 17:50:04 +00002509 if (!Target->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002510 continue;
2511
2512 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands8f723612009-02-17 17:50:04 +00002513 if (J->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002514 continue;
2515
Duncan Sandse10858a2009-02-15 11:54:49 +00002516 // Do not perform the transform if multiple aliases potentially target the
2517 // aliasee. This check also ensures that it is safe to replace the section
2518 // and other attributes of the aliasee with those of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002519 if (!hasOneUse)
2520 continue;
2521
Duncan Sandse10858a2009-02-15 11:54:49 +00002522 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002523 Target->takeName(J);
2524 Target->setLinkage(J->getLinkage());
Duncan Sandse10858a2009-02-15 11:54:49 +00002525 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002526
2527 // Delete the alias.
2528 M.getAliasList().erase(J);
2529 ++NumAliasesRemoved;
2530 Changed = true;
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002531 }
2532
2533 return Changed;
2534}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535
2536bool GlobalOpt::runOnModule(Module &M) {
2537 bool Changed = false;
2538
2539 // Try to find the llvm.globalctors list.
2540 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2541
2542 bool LocalChange = true;
2543 while (LocalChange) {
2544 LocalChange = false;
2545
2546 // Delete functions that are trivially dead, ccc -> fastcc
2547 LocalChange |= OptimizeFunctions(M);
2548
2549 // Optimize global_ctors list.
2550 if (GlobalCtors)
2551 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2552
2553 // Optimize non-address-taken globals.
2554 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002555
2556 // Resolve aliases, when possible.
Duncan Sands0c7b6332009-03-06 10:21:56 +00002557 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002558 Changed |= LocalChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002559 }
2560
2561 // TODO: Move all global ctors functions to the end of the module for code
2562 // layout.
2563
2564 return Changed;
2565}