blob: ae3acad96ff9c71fef6cdccfcdf584dc5c390568 [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"
27#include "llvm/Target/TargetData.h"
Duncan Sands551ec902008-02-18 17:32:13 +000028#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Support/Compiler.h"
30#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 {
59 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<TargetData>();
62 }
63 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000064 GlobalOpt() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065
66 bool runOnModule(Module &M);
67
68 private:
69 GlobalVariable *FindGlobalCtors(Module &M);
70 bool OptimizeFunctions(Module &M);
71 bool OptimizeGlobalVars(Module &M);
Duncan Sands0c7b6332009-03-06 10:21:56 +000072 bool OptimizeGlobalAliases(Module &M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
74 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
75 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076}
77
Dan Gohman089efff2008-05-13 00:00:25 +000078char GlobalOpt::ID = 0;
79static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
80
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
82
Dan Gohman089efff2008-05-13 00:00:25 +000083namespace {
84
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085/// GlobalStatus - As we analyze each global, keep track of some information
86/// about it. If we find out that the address of the global is taken, none of
87/// this info will be accurate.
88struct VISIBILITY_HIDDEN GlobalStatus {
89 /// isLoaded - True if the global is ever loaded. If the global isn't ever
90 /// loaded it can be deleted.
91 bool isLoaded;
92
93 /// StoredType - Keep track of what stores to the global look like.
94 ///
95 enum StoredType {
96 /// NotStored - There is no store to this global. It can thus be marked
97 /// constant.
98 NotStored,
99
100 /// isInitializerStored - This global is stored to, but the only thing
101 /// stored is the constant it was initialized with. This is only tracked
102 /// for scalar globals.
103 isInitializerStored,
104
105 /// isStoredOnce - This global is stored to, but only its initializer and
106 /// one other value is ever stored to it. If this global isStoredOnce, we
107 /// track the value stored to it in StoredOnceValue below. This is only
108 /// tracked for scalar globals.
109 isStoredOnce,
110
111 /// isStored - This global is stored to by multiple values or something else
112 /// that we cannot track.
113 isStored
114 } StoredType;
115
116 /// StoredOnceValue - If only one value (besides the initializer constant) is
117 /// ever stored to this global, keep track of what value it is.
118 Value *StoredOnceValue;
119
120 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
121 /// null/false. When the first accessing function is noticed, it is recorded.
122 /// When a second different accessing function is noticed,
123 /// HasMultipleAccessingFunctions is set to true.
124 Function *AccessingFunction;
125 bool HasMultipleAccessingFunctions;
126
127 /// HasNonInstructionUser - Set to true if this global has a user that is not
128 /// an instruction (e.g. a constant expr or GV initializer).
129 bool HasNonInstructionUser;
130
131 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
132 bool HasPHIUser;
133
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
135 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattnercad76212008-01-14 01:32:52 +0000136 HasNonInstructionUser(false), HasPHIUser(false) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137};
138
Dan Gohman089efff2008-05-13 00:00:25 +0000139}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140
Jay Foade4914352009-06-09 21:37:11 +0000141// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
142// by constants itself. Note that constants cannot be cyclic, so this test is
143// pretty easy to implement recursively.
144//
145static bool SafeToDestroyConstant(Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 if (isa<GlobalValue>(C)) return false;
147
Devang Patel3b6b19e2009-03-06 01:37:41 +0000148 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
149 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade4914352009-06-09 21:37:11 +0000150 if (!SafeToDestroyConstant(CU)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 } else
152 return false;
153 return true;
154}
155
156
157/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
158/// structure. If the global has its address taken, return true to indicate we
159/// can't do anything with it.
160///
161static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner4cd08c22008-12-16 07:34:30 +0000162 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
165 GS.HasNonInstructionUser = true;
166
167 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168
169 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
170 if (!GS.HasMultipleAccessingFunctions) {
171 Function *F = I->getParent()->getParent();
172 if (GS.AccessingFunction == 0)
173 GS.AccessingFunction = F;
174 else if (GS.AccessingFunction != F)
175 GS.HasMultipleAccessingFunctions = true;
176 }
Chris Lattner75a2db82008-01-29 19:01:37 +0000177 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 GS.isLoaded = true;
Chris Lattner75a2db82008-01-29 19:01:37 +0000179 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
181 // Don't allow a store OF the address, only stores TO the address.
182 if (SI->getOperand(0) == V) return true;
183
Chris Lattner75a2db82008-01-29 19:01:37 +0000184 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
185
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186 // If this is a direct store to the global (i.e., the global is a scalar
187 // value, not an aggregate), keep more specific information about
188 // stores.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000189 if (GS.StoredType != GlobalStatus::isStored) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
191 Value *StoredVal = SI->getOperand(0);
192 if (StoredVal == GV->getInitializer()) {
193 if (GS.StoredType < GlobalStatus::isInitializerStored)
194 GS.StoredType = GlobalStatus::isInitializerStored;
195 } else if (isa<LoadInst>(StoredVal) &&
196 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
197 // G = G
198 if (GS.StoredType < GlobalStatus::isInitializerStored)
199 GS.StoredType = GlobalStatus::isInitializerStored;
200 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
201 GS.StoredType = GlobalStatus::isStoredOnce;
202 GS.StoredOnceValue = StoredVal;
203 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
204 GS.StoredOnceValue == StoredVal) {
205 // noop.
206 } else {
207 GS.StoredType = GlobalStatus::isStored;
208 }
209 } else {
210 GS.StoredType = GlobalStatus::isStored;
211 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000212 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 } else if (isa<GetElementPtrInst>(I)) {
214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 } else if (isa<SelectInst>(I)) {
216 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
218 // PHI nodes we can check just like select or GEP instructions, but we
219 // have to be careful about infinite recursion.
Chris Lattner4cd08c22008-12-16 07:34:30 +0000220 if (PHIUsers.insert(PN)) // Not already visited.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 GS.HasPHIUser = true;
223 } else if (isa<CmpInst>(I)) {
Chris Lattnerb914b952009-03-08 03:37:35 +0000224 } else if (isa<MemTransferInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 if (I->getOperand(1) == V)
226 GS.StoredType = GlobalStatus::isStored;
227 if (I->getOperand(2) == V)
228 GS.isLoaded = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 } else if (isa<MemSetInst>(I)) {
230 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
231 GS.StoredType = GlobalStatus::isStored;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 } else {
233 return true; // Any other non-load instruction might take address!
234 }
235 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
236 GS.HasNonInstructionUser = true;
237 // We might have a dead and dangling constant hanging off of here.
Jay Foade4914352009-06-09 21:37:11 +0000238 if (!SafeToDestroyConstant(C))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 return true;
240 } else {
241 GS.HasNonInstructionUser = true;
242 // Otherwise must be some other user.
243 return true;
244 }
245
246 return false;
247}
248
Owen Anderson086ea052009-07-06 01:34:54 +0000249static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
Owen Anderson175b6542009-07-22 00:24:57 +0000250 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
252 if (!CI) return 0;
253 unsigned IdxV = CI->getZExtValue();
254
255 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
256 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
257 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
258 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
259 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
260 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
261 } else if (isa<ConstantAggregateZero>(Agg)) {
262 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
263 if (IdxV < STy->getNumElements())
Owen Andersonaac28372009-07-31 20:28:14 +0000264 return Constant::getNullValue(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 } else if (const SequentialType *STy =
266 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersonaac28372009-07-31 20:28:14 +0000267 return Constant::getNullValue(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 }
269 } else if (isa<UndefValue>(Agg)) {
270 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
271 if (IdxV < STy->getNumElements())
Owen Andersonb99ecca2009-07-30 23:03:37 +0000272 return UndefValue::get(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 } else if (const SequentialType *STy =
274 dyn_cast<SequentialType>(Agg->getType())) {
Owen Andersonb99ecca2009-07-30 23:03:37 +0000275 return UndefValue::get(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 }
277 }
278 return 0;
279}
280
281
282/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
283/// users of the global, cleaning up the obvious ones. This is largely just a
284/// quick scan over the use list to clean up the easy and obvious cruft. This
285/// returns true if it made a change.
Owen Andersond4d90a02009-07-06 18:42:36 +0000286static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Owen Anderson175b6542009-07-22 00:24:57 +0000287 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 bool Changed = false;
289 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
290 User *U = *UI++;
291
292 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
293 if (Init) {
294 // Replace the load with the initializer.
295 LI->replaceAllUsesWith(Init);
296 LI->eraseFromParent();
297 Changed = true;
298 }
299 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
300 // Store must be unreachable or storing Init into the global.
301 SI->eraseFromParent();
302 Changed = true;
303 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
304 if (CE->getOpcode() == Instruction::GetElementPtr) {
305 Constant *SubInit = 0;
306 if (Init)
Owen Andersond4d90a02009-07-06 18:42:36 +0000307 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
308 Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 } else if (CE->getOpcode() == Instruction::BitCast &&
310 isa<PointerType>(CE->getType())) {
311 // Pointer cast, delete any stores and memsets to the global.
Owen Andersond4d90a02009-07-06 18:42:36 +0000312 Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 }
314
315 if (CE->use_empty()) {
316 CE->destroyConstant();
317 Changed = true;
318 }
319 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7ebafca2007-11-09 17:33:02 +0000320 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
321 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
322 // and will invalidate our notion of what Init is.
Chris Lattner2dd9c042007-11-13 21:46:23 +0000323 Constant *SubInit = 0;
Chris Lattner7ebafca2007-11-09 17:33:02 +0000324 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
325 ConstantExpr *CE =
Owen Andersond4d90a02009-07-06 18:42:36 +0000326 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
Chris Lattner7ebafca2007-11-09 17:33:02 +0000327 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Owen Andersond4d90a02009-07-06 18:42:36 +0000328 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
Chris Lattner7ebafca2007-11-09 17:33:02 +0000329 }
Owen Andersond4d90a02009-07-06 18:42:36 +0000330 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331
332 if (GEP->use_empty()) {
333 GEP->eraseFromParent();
334 Changed = true;
335 }
336 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
337 if (MI->getRawDest() == V) {
338 MI->eraseFromParent();
339 Changed = true;
340 }
341
342 } else if (Constant *C = dyn_cast<Constant>(U)) {
343 // If we have a chain of dead constantexprs or other things dangling from
344 // us, and if they are all dead, nuke them without remorse.
Jay Foade4914352009-06-09 21:37:11 +0000345 if (SafeToDestroyConstant(C)) {
Devang Patel3b6b19e2009-03-06 01:37:41 +0000346 C->destroyConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 // This could have invalidated UI, start over from scratch.
Owen Andersond4d90a02009-07-06 18:42:36 +0000348 CleanupConstantGlobalUsers(V, Init, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 return true;
350 }
351 }
352 }
353 return Changed;
354}
355
Chris Lattner7bd79da2008-01-14 02:09:12 +0000356/// isSafeSROAElementUse - Return true if the specified instruction is a safe
357/// user of a derived expression from a global that we want to SROA.
358static bool isSafeSROAElementUse(Value *V) {
359 // We might have a dead and dangling constant hanging off of here.
360 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade4914352009-06-09 21:37:11 +0000361 return SafeToDestroyConstant(C);
Chris Lattner7329c662008-01-14 01:31:05 +0000362
Chris Lattner7bd79da2008-01-14 02:09:12 +0000363 Instruction *I = dyn_cast<Instruction>(V);
364 if (!I) return false;
365
366 // Loads are ok.
367 if (isa<LoadInst>(I)) return true;
368
369 // Stores *to* the pointer are ok.
370 if (StoreInst *SI = dyn_cast<StoreInst>(I))
371 return SI->getOperand(0) != V;
372
373 // Otherwise, it must be a GEP.
374 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
375 if (GEPI == 0) return false;
376
377 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
378 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
379 return false;
380
381 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
382 I != E; ++I)
383 if (!isSafeSROAElementUse(*I))
384 return false;
Chris Lattner7329c662008-01-14 01:31:05 +0000385 return true;
386}
387
Chris Lattner7bd79da2008-01-14 02:09:12 +0000388
389/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
390/// Look at it and its uses and decide whether it is safe to SROA this global.
391///
392static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
393 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
394 if (!isa<GetElementPtrInst>(U) &&
395 (!isa<ConstantExpr>(U) ||
396 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
397 return false;
398
399 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
400 // don't like < 3 operand CE's, and we don't like non-constant integer
401 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
402 // value of C.
403 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
404 !cast<Constant>(U->getOperand(1))->isNullValue() ||
405 !isa<ConstantInt>(U->getOperand(2)))
406 return false;
407
408 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
409 ++GEPI; // Skip over the pointer index.
410
411 // If this is a use of an array allocation, do a bit more checking for sanity.
412 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
413 uint64_t NumElements = AT->getNumElements();
414 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
415
416 // Check to make sure that index falls within the array. If not,
417 // something funny is going on, so we won't do the optimization.
418 //
419 if (Idx->getZExtValue() >= NumElements)
420 return false;
421
422 // We cannot scalar repl this level of the array unless any array
423 // sub-indices are in-range constants. In particular, consider:
424 // A[0][i]. We cannot know that the user isn't doing invalid things like
425 // allowing i to index an out-of-range subscript that accesses A[1].
426 //
427 // Scalar replacing *just* the outer index of the array is probably not
428 // going to be a win anyway, so just give up.
429 for (++GEPI; // Skip array index.
430 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
431 ++GEPI) {
432 uint64_t NumElements;
433 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
434 NumElements = SubArrayTy->getNumElements();
435 else
436 NumElements = cast<VectorType>(*GEPI)->getNumElements();
437
438 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
439 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
440 return false;
441 }
442 }
443
444 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
445 if (!isSafeSROAElementUse(*I))
446 return false;
447 return true;
448}
449
450/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
451/// is safe for us to perform this transformation.
452///
453static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
454 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
455 UI != E; ++UI) {
456 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
457 return false;
458 }
459 return true;
460}
461
462
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000463/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
464/// variable. This opens the door for other optimizations by exposing the
465/// behavior of the program in a more fine-grained way. We have determined that
466/// this transformation is safe already. We return the first global variable we
467/// insert so that the caller can reprocess it.
Owen Anderson086ea052009-07-06 01:34:54 +0000468static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
Owen Anderson175b6542009-07-22 00:24:57 +0000469 LLVMContext &Context) {
Chris Lattner7329c662008-01-14 01:31:05 +0000470 // Make sure this global only has simple uses that we can SRA.
Chris Lattner7bd79da2008-01-14 02:09:12 +0000471 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner7329c662008-01-14 01:31:05 +0000472 return 0;
473
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000474 assert(GV->hasLocalLinkage() && !GV->isConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 Constant *Init = GV->getInitializer();
476 const Type *Ty = Init->getType();
477
478 std::vector<GlobalVariable*> NewGlobals;
479 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
480
Chris Lattner20846272008-04-26 07:40:11 +0000481 // Get the alignment of the global, either explicit or target-specific.
482 unsigned StartAlignment = GV->getAlignment();
483 if (StartAlignment == 0)
484 StartAlignment = TD.getABITypeAlignment(GV->getType());
485
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
487 NewGlobals.reserve(STy->getNumElements());
Chris Lattner20846272008-04-26 07:40:11 +0000488 const StructLayout &Layout = *TD.getStructLayout(STy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
490 Constant *In = getAggregateConstantElement(Init,
Owen Anderson35b47072009-08-13 21:58:54 +0000491 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson086ea052009-07-06 01:34:54 +0000492 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 assert(In && "Couldn't get element of initializer?");
Owen Anderson175b6542009-07-22 00:24:57 +0000494 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000495 STy->getElementType(i), false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 GlobalVariable::InternalLinkage,
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000497 In, GV->getName()+"."+Twine(i),
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000498 GV->isThreadLocal(),
Owen Andersone0f136d2009-07-08 01:26:06 +0000499 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 Globals.insert(GV, NGV);
501 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000502
503 // Calculate the known alignment of the field. If the original aggregate
504 // had 256 byte alignment for example, something might depend on that:
505 // propagate info to each field.
506 uint64_t FieldOffset = Layout.getElementOffset(i);
507 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
508 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
509 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510 }
511 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
512 unsigned NumElements = 0;
513 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
514 NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 else
Chris Lattner20846272008-04-26 07:40:11 +0000516 NumElements = cast<VectorType>(STy)->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517
518 if (NumElements > 16 && GV->hasNUsesOrMore(16))
519 return 0; // It's not worth it.
520 NewGlobals.reserve(NumElements);
Chris Lattner20846272008-04-26 07:40:11 +0000521
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000522 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner20846272008-04-26 07:40:11 +0000523 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524 for (unsigned i = 0, e = NumElements; i != e; ++i) {
525 Constant *In = getAggregateConstantElement(Init,
Owen Anderson35b47072009-08-13 21:58:54 +0000526 ConstantInt::get(Type::getInt32Ty(Context), i),
Owen Anderson086ea052009-07-06 01:34:54 +0000527 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 assert(In && "Couldn't get element of initializer?");
529
Owen Anderson175b6542009-07-22 00:24:57 +0000530 GlobalVariable *NGV = new GlobalVariable(Context,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000531 STy->getElementType(), false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 GlobalVariable::InternalLinkage,
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000533 In, GV->getName()+"."+Twine(i),
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000534 GV->isThreadLocal(),
Owen Andersone17fc1d2009-07-08 19:03:57 +0000535 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 Globals.insert(GV, NGV);
537 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000538
539 // Calculate the known alignment of the field. If the original aggregate
540 // had 256 byte alignment for example, something might depend on that:
541 // propagate info to each field.
542 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
543 if (NewAlign > EltAlign)
544 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 }
546 }
547
548 if (NewGlobals.empty())
549 return 0;
550
551 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
552
Owen Anderson35b47072009-08-13 21:58:54 +0000553 Constant *NullInt = Constant::getNullValue(Type::getInt32Ty(Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554
555 // Loop over all of the uses of the global, replacing the constantexpr geps,
556 // with smaller constantexpr geps or direct references.
557 while (!GV->use_empty()) {
558 User *GEP = GV->use_back();
559 assert(((isa<ConstantExpr>(GEP) &&
560 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
561 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
562
563 // Ignore the 1th operand, which has to be zero or else the program is quite
564 // broken (undefined). Get the 2nd operand, which is the structure or array
565 // index.
566 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
567 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
568
569 Value *NewPtr = NewGlobals[Val];
570
571 // Form a shorter GEP if needed.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000572 if (GEP->getNumOperands() > 3) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
574 SmallVector<Constant*, 8> Idxs;
575 Idxs.push_back(NullInt);
576 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
577 Idxs.push_back(CE->getOperand(i));
Owen Anderson02b48c32009-07-29 18:55:55 +0000578 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 &Idxs[0], Idxs.size());
580 } else {
581 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
582 SmallVector<Value*, 8> Idxs;
583 Idxs.push_back(NullInt);
584 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
585 Idxs.push_back(GEPI->getOperand(i));
Gabor Greifd6da1d02008-04-06 20:25:17 +0000586 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
Daniel Dunbar15676ac2009-07-30 17:37:43 +0000587 GEPI->getName()+"."+Twine(Val),GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000589 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 GEP->replaceAllUsesWith(NewPtr);
591
592 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
593 GEPI->eraseFromParent();
594 else
595 cast<ConstantExpr>(GEP)->destroyConstant();
596 }
597
598 // Delete the old global, now that it is dead.
599 Globals.erase(GV);
600 ++NumSRA;
601
602 // Loop over the new globals array deleting any globals that are obviously
603 // dead. This can arise due to scalarization of a structure or an array that
604 // has elements that are dead.
605 unsigned FirstGlobal = 0;
606 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
607 if (NewGlobals[i]->use_empty()) {
608 Globals.erase(NewGlobals[i]);
609 if (FirstGlobal == i) ++FirstGlobal;
610 }
611
612 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
613}
614
615/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattnerbdf77462007-09-13 16:30:19 +0000616/// value will trap if the value is dynamically null. PHIs keeps track of any
617/// phi nodes we've seen to avoid reprocessing them.
618static bool AllUsesOfValueWillTrapIfNull(Value *V,
619 SmallPtrSet<PHINode*, 8> &PHIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
621 if (isa<LoadInst>(*UI)) {
622 // Will trap.
623 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
624 if (SI->getOperand(0) == V) {
625 //cerr << "NONTRAPPING USE: " << **UI;
626 return false; // Storing the value.
627 }
628 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
629 if (CI->getOperand(0) != V) {
630 //cerr << "NONTRAPPING USE: " << **UI;
631 return false; // Not calling the ptr
632 }
633 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
634 if (II->getOperand(0) != V) {
635 //cerr << "NONTRAPPING USE: " << **UI;
636 return false; // Not calling the ptr
637 }
Chris Lattnerbdf77462007-09-13 16:30:19 +0000638 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
639 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000641 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
642 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
643 // If we've already seen this phi node, ignore it, it has already been
644 // checked.
645 if (PHIs.insert(PN))
646 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 } else if (isa<ICmpInst>(*UI) &&
648 isa<ConstantPointerNull>(UI->getOperand(1))) {
649 // Ignore setcc X, null
650 } else {
651 //cerr << "NONTRAPPING USE: " << **UI;
652 return false;
653 }
654 return true;
655}
656
657/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
658/// from GV will trap if the loaded value is null. Note that this also permits
659/// comparisons of the loaded value against null, as a special case.
660static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
661 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
662 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000663 SmallPtrSet<PHINode*, 8> PHIs;
664 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 return false;
666 } else if (isa<StoreInst>(*UI)) {
667 // Ignore stores to the global.
668 } else {
669 // We don't know or understand this user, bail out.
670 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
671 return false;
672 }
673
674 return true;
675}
676
Owen Anderson086ea052009-07-06 01:34:54 +0000677static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
Owen Anderson175b6542009-07-22 00:24:57 +0000678 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 bool Changed = false;
680 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
681 Instruction *I = cast<Instruction>(*UI++);
682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
683 LI->setOperand(0, NewV);
684 Changed = true;
685 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
686 if (SI->getOperand(1) == V) {
687 SI->setOperand(1, NewV);
688 Changed = true;
689 }
690 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
691 if (I->getOperand(0) == V) {
692 // Calling through the pointer! Turn into a direct call, but be careful
693 // that the pointer is not also being passed as an argument.
694 I->setOperand(0, NewV);
695 Changed = true;
696 bool PassedAsArg = false;
697 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
698 if (I->getOperand(i) == V) {
699 PassedAsArg = true;
700 I->setOperand(i, NewV);
701 }
702
703 if (PassedAsArg) {
704 // Being passed as an argument also. Be careful to not invalidate UI!
705 UI = V->use_begin();
706 }
707 }
708 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
709 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson02b48c32009-07-29 18:55:55 +0000710 ConstantExpr::getCast(CI->getOpcode(),
Owen Anderson086ea052009-07-06 01:34:54 +0000711 NewV, CI->getType()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712 if (CI->use_empty()) {
713 Changed = true;
714 CI->eraseFromParent();
715 }
716 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
717 // Should handle GEP here.
718 SmallVector<Constant*, 8> Idxs;
719 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif20f03f52008-05-29 01:59:18 +0000720 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
721 i != e; ++i)
722 if (Constant *C = dyn_cast<Constant>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 Idxs.push_back(C);
724 else
725 break;
726 if (Idxs.size() == GEPI->getNumOperands()-1)
727 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Anderson02b48c32009-07-29 18:55:55 +0000728 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Owen Anderson086ea052009-07-06 01:34:54 +0000729 Idxs.size()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 if (GEPI->use_empty()) {
731 Changed = true;
732 GEPI->eraseFromParent();
733 }
734 }
735 }
736
737 return Changed;
738}
739
740
741/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
742/// value stored into it. If there are uses of the loaded value that would trap
743/// if the loaded value is dynamically null, then we know that they cannot be
744/// reachable with a null optimize away the load.
Owen Anderson086ea052009-07-06 01:34:54 +0000745static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Owen Anderson175b6542009-07-22 00:24:57 +0000746 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 bool Changed = false;
748
Chris Lattner9806cc12009-01-14 00:12:58 +0000749 // Keep track of whether we are able to remove all the uses of the global
750 // other than the store that defines it.
751 bool AllNonStoreUsesGone = true;
752
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner9806cc12009-01-14 00:12:58 +0000754 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
755 User *GlobalUser = *GUI++;
756 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson086ea052009-07-06 01:34:54 +0000757 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner9806cc12009-01-14 00:12:58 +0000758 // If we were able to delete all uses of the loads
759 if (LI->use_empty()) {
760 LI->eraseFromParent();
761 Changed = true;
762 } else {
763 AllNonStoreUsesGone = false;
764 }
765 } else if (isa<StoreInst>(GlobalUser)) {
766 // Ignore the store that stores "LV" to the global.
767 assert(GlobalUser->getOperand(1) == GV &&
768 "Must be storing *to* the global");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 } else {
Chris Lattner9806cc12009-01-14 00:12:58 +0000770 AllNonStoreUsesGone = false;
771
772 // If we get here we could have other crazy uses that are transitively
773 // loaded.
774 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
775 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776 }
Chris Lattner9806cc12009-01-14 00:12:58 +0000777 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778
779 if (Changed) {
780 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
781 ++NumGlobUses;
782 }
783
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 // If we nuked all of the loads, then none of the stores are needed either,
785 // nor is the global.
Chris Lattner9806cc12009-01-14 00:12:58 +0000786 if (AllNonStoreUsesGone) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 DOUT << " *** GLOBAL NOW DEAD!\n";
Owen Andersond4d90a02009-07-06 18:42:36 +0000788 CleanupConstantGlobalUsers(GV, 0, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 if (GV->use_empty()) {
790 GV->eraseFromParent();
791 ++NumDeleted;
792 }
793 Changed = true;
794 }
795 return Changed;
796}
797
798/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
799/// instructions that are foldable.
Owen Anderson175b6542009-07-22 00:24:57 +0000800static void ConstantPropUsersOf(Value *V, LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000801 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
802 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Andersond4d90a02009-07-06 18:42:36 +0000803 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 I->replaceAllUsesWith(NewC);
805
806 // Advance UI to the next non-I use to avoid invalidating it!
807 // Instructions could multiply use V.
808 while (UI != E && *UI == I)
809 ++UI;
810 I->eraseFromParent();
811 }
812}
813
814/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
815/// variable, and transforms the program as if it always contained the result of
816/// the specified malloc. Because it is always the result of the specified
817/// malloc, there is no reason to actually DO the malloc. Instead, turn the
818/// malloc into a global, and any loads of GV as uses of the new global.
819static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson086ea052009-07-06 01:34:54 +0000820 MallocInst *MI,
Owen Anderson175b6542009-07-22 00:24:57 +0000821 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
823 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
824
825 if (NElements->getZExtValue() != 1) {
826 // If we have an array allocation, transform it to a single element
827 // allocation to make the code below simpler.
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000828 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 NElements->getZExtValue());
830 MallocInst *NewMI =
Owen Anderson35b47072009-08-13 21:58:54 +0000831 new MallocInst(NewTy, Constant::getNullValue(Type::getInt32Ty(Context)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 MI->getAlignment(), MI->getName(), MI);
833 Value* Indices[2];
Owen Anderson35b47072009-08-13 21:58:54 +0000834 Indices[0] = Indices[1] = Constant::getNullValue(Type::getInt32Ty(Context));
Gabor Greifd6da1d02008-04-06 20:25:17 +0000835 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
836 NewMI->getName()+".el0", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 MI->replaceAllUsesWith(NewGEP);
838 MI->eraseFromParent();
839 MI = NewMI;
840 }
841
842 // Create the new global variable. The contents of the malloc'd memory is
843 // undefined, so initialize with an undef value.
Chris Lattner20846272008-04-26 07:40:11 +0000844 // FIXME: This new global should have the alignment returned by malloc. Code
845 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
846 // this would only guarantee some lower alignment.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000847 Constant *Init = UndefValue::get(MI->getAllocatedType());
Owen Andersone17fc1d2009-07-08 19:03:57 +0000848 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
849 MI->getAllocatedType(), false,
850 GlobalValue::InternalLinkage, Init,
851 GV->getName()+".body",
852 GV,
853 GV->isThreadLocal());
854
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 // Anything that used the malloc now uses the global directly.
856 MI->replaceAllUsesWith(NewGV);
857
858 Constant *RepValue = NewGV;
859 if (NewGV->getType() != GV->getType()->getElementType())
Owen Anderson02b48c32009-07-29 18:55:55 +0000860 RepValue = ConstantExpr::getBitCast(RepValue,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000861 GV->getType()->getElementType());
862
863 // If there is a comparison against null, we will insert a global bool to
864 // keep track of whether the global was initialized yet or not.
865 GlobalVariable *InitBool =
Owen Anderson35b47072009-08-13 21:58:54 +0000866 new GlobalVariable(Context, Type::getInt1Ty(Context), false,
Owen Andersone0f136d2009-07-08 01:26:06 +0000867 GlobalValue::InternalLinkage,
Owen Anderson4f720fa2009-07-31 17:39:07 +0000868 ConstantInt::getFalse(Context), GV->getName()+".init",
Owen Andersone17fc1d2009-07-08 19:03:57 +0000869 GV->isThreadLocal());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 bool InitBoolUsed = false;
871
872 // Loop over all uses of GV, processing them in turn.
873 std::vector<StoreInst*> Stores;
874 while (!GV->use_empty())
875 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
876 while (!LI->use_empty()) {
877 Use &LoadUse = LI->use_begin().getUse();
878 if (!isa<ICmpInst>(LoadUse.getUser()))
879 LoadUse = RepValue;
880 else {
881 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
882 // Replace the cmp X, 0 with a use of the bool value.
883 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
884 InitBoolUsed = true;
885 switch (CI->getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000886 default: llvm_unreachable("Unknown ICmp Predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 case ICmpInst::ICMP_ULT:
888 case ICmpInst::ICMP_SLT:
Owen Anderson4f720fa2009-07-31 17:39:07 +0000889 LV = ConstantInt::getFalse(Context); // X < null -> always false
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 break;
891 case ICmpInst::ICMP_ULE:
892 case ICmpInst::ICMP_SLE:
893 case ICmpInst::ICMP_EQ:
Dan Gohmancdff2122009-08-12 16:23:25 +0000894 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000895 break;
896 case ICmpInst::ICMP_NE:
897 case ICmpInst::ICMP_UGE:
898 case ICmpInst::ICMP_SGE:
899 case ICmpInst::ICMP_UGT:
900 case ICmpInst::ICMP_SGT:
901 break; // no change.
902 }
903 CI->replaceAllUsesWith(LV);
904 CI->eraseFromParent();
905 }
906 }
907 LI->eraseFromParent();
908 } else {
909 StoreInst *SI = cast<StoreInst>(GV->use_back());
910 // The global is initialized when the store to it occurs.
Owen Anderson4f720fa2009-07-31 17:39:07 +0000911 new StoreInst(ConstantInt::getTrue(Context), InitBool, SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 SI->eraseFromParent();
913 }
914
915 // If the initialization boolean was used, insert it, otherwise delete it.
916 if (!InitBoolUsed) {
917 while (!InitBool->use_empty()) // Delete initializations
918 cast<Instruction>(InitBool->use_back())->eraseFromParent();
919 delete InitBool;
920 } else
921 GV->getParent()->getGlobalList().insert(GV, InitBool);
922
923
924 // Now the GV is dead, nuke it and the malloc.
925 GV->eraseFromParent();
926 MI->eraseFromParent();
927
928 // To further other optimizations, loop over all users of NewGV and try to
929 // constant prop them. This will promote GEP instructions with constant
930 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Owen Andersond4d90a02009-07-06 18:42:36 +0000931 ConstantPropUsersOf(NewGV, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 if (RepValue != NewGV)
Owen Andersond4d90a02009-07-06 18:42:36 +0000933 ConstantPropUsersOf(RepValue, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 return NewGV;
936}
937
938/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
939/// to make sure that there are no complex uses of V. We permit simple things
940/// like dereferencing the pointer, but not storing through the address, unless
941/// it is to the specified global.
942static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnere7606f42007-09-13 16:37:20 +0000943 GlobalVariable *GV,
944 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner183b0cf2008-12-15 21:08:54 +0000945 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foadd1d6a142009-06-06 17:49:35 +0000946 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner183b0cf2008-12-15 21:08:54 +0000947
948 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
949 continue; // Fine, ignore.
950 }
951
952 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
954 return false; // Storing the pointer itself... bad.
Chris Lattner183b0cf2008-12-15 21:08:54 +0000955 continue; // Otherwise, storing through it, or storing into GV... fine.
956 }
957
958 if (isa<GetElementPtrInst>(Inst)) {
959 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000961 continue;
962 }
963
964 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnere7606f42007-09-13 16:37:20 +0000965 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
966 // cycles.
967 if (PHIs.insert(PN))
Chris Lattner4bde3c42007-09-14 03:41:21 +0000968 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
969 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000970 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 }
Chris Lattner183b0cf2008-12-15 21:08:54 +0000972
973 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
974 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
975 return false;
976 continue;
977 }
978
979 return false;
980 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 return true;
982}
983
984/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
985/// somewhere. Transform all uses of the allocation into loads from the
986/// global and uses of the resultant pointer. Further, delete the store into
987/// GV. This assumes that these value pass the
988/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
989static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
990 GlobalVariable *GV) {
991 while (!Alloc->use_empty()) {
Chris Lattner20eef0f2007-09-13 18:00:31 +0000992 Instruction *U = cast<Instruction>(*Alloc->use_begin());
993 Instruction *InsertPt = U;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
995 // If this is the store of the allocation into the global, remove it.
996 if (SI->getOperand(1) == GV) {
997 SI->eraseFromParent();
998 continue;
999 }
Chris Lattner20eef0f2007-09-13 18:00:31 +00001000 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1001 // Insert the load in the corresponding predecessor, not right before the
1002 // PHI.
Gabor Greif261734d2009-01-23 19:40:15 +00001003 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner27ef89e2008-12-15 21:44:34 +00001004 } else if (isa<BitCastInst>(U)) {
1005 // Must be bitcast between the malloc and store to initialize the global.
1006 ReplaceUsesOfMallocWithGlobal(U, GV);
1007 U->eraseFromParent();
1008 continue;
1009 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1010 // If this is a "GEP bitcast" and the user is a store to the global, then
1011 // just process it as a bitcast.
1012 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1013 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1014 if (SI->getOperand(1) == GV) {
1015 // Must be bitcast GEP between the malloc and store to initialize
1016 // the global.
1017 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1018 GEPI->eraseFromParent();
1019 continue;
1020 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 }
Chris Lattner27ef89e2008-12-15 21:44:34 +00001022
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 // Insert a load from the global, and use it instead of the malloc.
Chris Lattner20eef0f2007-09-13 18:00:31 +00001024 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 U->replaceUsesOfWith(Alloc, NL);
1026 }
1027}
1028
Chris Lattner7f252db2008-12-16 21:24:51 +00001029/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1030/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1031/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001032static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Chengb00d9282009-06-02 00:56:07 +00001033 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1034 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner7f252db2008-12-16 21:24:51 +00001035 // We permit two users of the load: setcc comparing against the null
1036 // pointer, and a getelementptr of a specific form.
1037 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1038 Instruction *User = cast<Instruction>(*UI);
1039
1040 // Comparison against null is ok.
1041 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1042 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1043 return false;
1044 continue;
1045 }
1046
1047 // getelementptr is also ok, but only a simple form.
1048 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1049 // Must index into the array and into the struct.
1050 if (GEPI->getNumOperands() < 3)
1051 return false;
1052
1053 // Otherwise the GEP is ok.
1054 continue;
1055 }
1056
1057 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Chengb00d9282009-06-02 00:56:07 +00001058 if (!LoadUsingPHIsPerLoad.insert(PN))
1059 // This means some phi nodes are dependent on each other.
1060 // Avoid infinite looping!
1061 return false;
1062 if (!LoadUsingPHIs.insert(PN))
1063 // If we have already analyzed this PHI, then it is safe.
Chris Lattner7f252db2008-12-16 21:24:51 +00001064 continue;
1065
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001066 // Make sure all uses of the PHI are simple enough to transform.
Evan Chengb00d9282009-06-02 00:56:07 +00001067 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1068 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001069 return false;
1070
1071 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 }
Chris Lattner7f252db2008-12-16 21:24:51 +00001073
1074 // Otherwise we don't know what this is, not ok.
1075 return false;
1076 }
1077
1078 return true;
1079}
1080
1081
1082/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1083/// GV are simple enough to perform HeapSRA, return true.
1084static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1085 MallocInst *MI) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001086 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Chengb00d9282009-06-02 00:56:07 +00001087 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner7f252db2008-12-16 21:24:51 +00001088 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1089 ++UI)
Evan Chengb00d9282009-06-02 00:56:07 +00001090 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1091 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1092 LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001093 return false;
Evan Chengb00d9282009-06-02 00:56:07 +00001094 LoadUsingPHIsPerLoad.clear();
1095 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001096
1097 // If we reach here, we know that all uses of the loads and transitive uses
1098 // (through PHI nodes) are simple enough to transform. However, we don't know
1099 // that all inputs the to the PHI nodes are in the same equivalence sets.
1100 // Check to verify that all operands of the PHIs are either PHIS that can be
1101 // transformed, loads from GV, or MI itself.
1102 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1103 E = LoadUsingPHIs.end(); I != E; ++I) {
1104 PHINode *PN = *I;
1105 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1106 Value *InVal = PN->getIncomingValue(op);
1107
1108 // PHI of the stored value itself is ok.
1109 if (InVal == MI) continue;
1110
1111 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1112 // One of the PHIs in our set is (optimistically) ok.
1113 if (LoadUsingPHIs.count(InPN))
1114 continue;
1115 return false;
1116 }
1117
1118 // Load from GV is ok.
1119 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1120 if (LI->getOperand(0) == GV)
1121 continue;
1122
1123 // UNDEF? NULL?
1124
1125 // Anything else is rejected.
1126 return false;
1127 }
1128 }
1129
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 return true;
1131}
1132
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001133static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1134 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001135 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson175b6542009-07-22 00:24:57 +00001136 LLVMContext &Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001137 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1138
1139 if (FieldNo >= FieldVals.size())
1140 FieldVals.resize(FieldNo+1);
1141
1142 // If we already have this value, just reuse the previously scalarized
1143 // version.
1144 if (Value *FieldVal = FieldVals[FieldNo])
1145 return FieldVal;
1146
1147 // Depending on what instruction this is, we have several cases.
1148 Value *Result;
1149 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1150 // This is a scalarized version of the load from the global. Just create
1151 // a new Load of the scalarized global.
1152 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1153 InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001154 PHIsToRewrite, Context),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001155 LI->getName()+".f"+Twine(FieldNo), LI);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001156 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1157 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1158 // field.
1159 const StructType *ST =
1160 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1161
Owen Anderson086ea052009-07-06 01:34:54 +00001162 Result =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001163 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001164 PN->getName()+".f"+Twine(FieldNo), PN);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001165 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1166 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001167 llvm_unreachable("Unknown usable value");
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001168 Result = 0;
1169 }
1170
1171 return FieldVals[FieldNo] = Result;
Chris Lattner20eef0f2007-09-13 18:00:31 +00001172}
1173
Chris Lattneraf82fb82007-09-13 17:29:05 +00001174/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1175/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001176static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1177 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001178 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson175b6542009-07-22 00:24:57 +00001179 LLVMContext &Context) {
Chris Lattneraf82fb82007-09-13 17:29:05 +00001180 // If this is a comparison against null, handle it.
1181 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1182 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1183 // If we have a setcc of the loaded pointer, we can use a setcc of any
1184 // field.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001185 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson086ea052009-07-06 01:34:54 +00001186 InsertedScalarizedValues, PHIsToRewrite,
1187 Context);
Chris Lattneraf82fb82007-09-13 17:29:05 +00001188
Owen Anderson6601fcd2009-07-09 23:48:35 +00001189 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
Owen Andersonaac28372009-07-31 20:28:14 +00001190 Constant::getNullValue(NPtr->getType()),
Owen Anderson6601fcd2009-07-09 23:48:35 +00001191 SCI->getName());
Chris Lattneraf82fb82007-09-13 17:29:05 +00001192 SCI->replaceAllUsesWith(New);
1193 SCI->eraseFromParent();
1194 return;
1195 }
1196
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001197 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattner20eef0f2007-09-13 18:00:31 +00001198 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1199 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1200 && "Unexpected GEPI!");
Chris Lattneraf82fb82007-09-13 17:29:05 +00001201
Chris Lattner20eef0f2007-09-13 18:00:31 +00001202 // Load the pointer for this field.
1203 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001204 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson086ea052009-07-06 01:34:54 +00001205 InsertedScalarizedValues, PHIsToRewrite,
1206 Context);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001207
1208 // Create the new GEP idx vector.
1209 SmallVector<Value*, 8> GEPIdx;
1210 GEPIdx.push_back(GEPI->getOperand(1));
1211 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1212
Gabor Greifb91ea9d2008-05-15 10:04:30 +00001213 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1214 GEPIdx.begin(), GEPIdx.end(),
Gabor Greifd6da1d02008-04-06 20:25:17 +00001215 GEPI->getName(), GEPI);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001216 GEPI->replaceAllUsesWith(NGEPI);
1217 GEPI->eraseFromParent();
1218 return;
1219 }
Chris Lattnereefff982007-09-13 21:31:36 +00001220
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001221 // Recursively transform the users of PHI nodes. This will lazily create the
1222 // PHIs that are needed for individual elements. Keep track of what PHIs we
1223 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1224 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1225 // already been seen first by another load, so its uses have already been
1226 // processed.
1227 PHINode *PN = cast<PHINode>(LoadUser);
1228 bool Inserted;
1229 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1230 tie(InsertPos, Inserted) =
1231 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1232 if (!Inserted) return;
Chris Lattnereefff982007-09-13 21:31:36 +00001233
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001234 // If this is the first time we've seen this PHI, recursively process all
1235 // users.
Chris Lattnera5e124b2008-12-17 05:42:08 +00001236 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1237 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001238 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1239 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001240 }
Chris Lattneraf82fb82007-09-13 17:29:05 +00001241}
1242
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1244/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1245/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner7f252db2008-12-16 21:24:51 +00001246/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattneraf82fb82007-09-13 17:29:05 +00001247static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001248 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001249 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson175b6542009-07-22 00:24:57 +00001250 LLVMContext &Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001251 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnera5e124b2008-12-17 05:42:08 +00001252 UI != E; ) {
1253 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001254 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1255 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001256 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001257
1258 if (Load->use_empty()) {
1259 Load->eraseFromParent();
1260 InsertedScalarizedValues.erase(Load);
1261 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262}
1263
1264/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1265/// it up into multiple allocations of arrays of the fields.
Owen Anderson086ea052009-07-06 01:34:54 +00001266static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
Owen Anderson175b6542009-07-22 00:24:57 +00001267 LLVMContext &Context){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
1269 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1270
1271 // There is guaranteed to be at least one use of the malloc (storing
1272 // it into GV). If there are other uses, change them to be uses of
1273 // the global to simplify later code. This also deletes the store
1274 // into GV.
1275 ReplaceUsesOfMallocWithGlobal(MI, GV);
1276
1277 // Okay, at this point, there are no users of the malloc. Insert N
1278 // new mallocs at the same place as MI, and N globals.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001279 std::vector<Value*> FieldGlobals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 std::vector<MallocInst*> FieldMallocs;
1281
1282 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1283 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001284 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285
1286 GlobalVariable *NGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +00001287 new GlobalVariable(*GV->getParent(),
1288 PFieldTy, false, GlobalValue::InternalLinkage,
Owen Andersonaac28372009-07-31 20:28:14 +00001289 Constant::getNullValue(PFieldTy),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001290 GV->getName() + ".f" + Twine(FieldNo), GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 GV->isThreadLocal());
1292 FieldGlobals.push_back(NGV);
1293
Owen Anderson140166d2009-07-15 23:53:25 +00001294 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
Daniel Dunbar15676ac2009-07-30 17:37:43 +00001295 MI->getName() + ".f" + Twine(FieldNo), MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 FieldMallocs.push_back(NMI);
1297 new StoreInst(NMI, NGV, MI);
1298 }
1299
1300 // The tricky aspect of this transformation is handling the case when malloc
1301 // fails. In the original code, malloc failing would set the result pointer
1302 // of malloc to null. In this case, some mallocs could succeed and others
1303 // could fail. As such, we emit code that looks like this:
1304 // F0 = malloc(field0)
1305 // F1 = malloc(field1)
1306 // F2 = malloc(field2)
1307 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1308 // if (F0) { free(F0); F0 = 0; }
1309 // if (F1) { free(F1); F1 = 0; }
1310 // if (F2) { free(F2); F2 = 0; }
1311 // }
1312 Value *RunningOr = 0;
1313 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00001314 Value *Cond = new ICmpInst(MI, ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Andersonaac28372009-07-31 20:28:14 +00001315 Constant::getNullValue(FieldMallocs[i]->getType()),
Owen Anderson6601fcd2009-07-09 23:48:35 +00001316 "isnull");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 if (!RunningOr)
1318 RunningOr = Cond; // First seteq
1319 else
Gabor Greifa645dd32008-05-16 19:29:10 +00001320 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 }
1322
1323 // Split the basic block at the old malloc.
1324 BasicBlock *OrigBB = MI->getParent();
1325 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1326
1327 // Create the block to check the first condition. Put all these blocks at the
1328 // end of the function as they are unlikely to be executed.
Owen Anderson35b47072009-08-13 21:58:54 +00001329 BasicBlock *NullPtrBlock = BasicBlock::Create(Context, "malloc_ret_null",
Gabor Greifd6da1d02008-04-06 20:25:17 +00001330 OrigBB->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331
1332 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1333 // branch on RunningOr.
1334 OrigBB->getTerminator()->eraseFromParent();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001335 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336
1337 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1338 // pointer, because some may be null while others are not.
1339 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1340 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Owen Anderson6601fcd2009-07-09 23:48:35 +00001341 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
Owen Andersonaac28372009-07-31 20:28:14 +00001342 Constant::getNullValue(GVVal->getType()),
Owen Anderson6601fcd2009-07-09 23:48:35 +00001343 "tmp");
Owen Anderson35b47072009-08-13 21:58:54 +00001344 BasicBlock *FreeBlock = BasicBlock::Create(Context, "free_it",
1345 OrigBB->getParent());
1346 BasicBlock *NextBlock = BasicBlock::Create(Context, "next",
1347 OrigBB->getParent());
Gabor Greifd6da1d02008-04-06 20:25:17 +00001348 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
1350 // Fill in FreeBlock.
1351 new FreeInst(GVVal, FreeBlock);
Owen Andersonaac28372009-07-31 20:28:14 +00001352 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 FreeBlock);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001354 BranchInst::Create(NextBlock, FreeBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355
1356 NullPtrBlock = NextBlock;
1357 }
1358
Gabor Greifd6da1d02008-04-06 20:25:17 +00001359 BranchInst::Create(ContBB, NullPtrBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360
1361 // MI is no longer needed, remove it.
1362 MI->eraseFromParent();
1363
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001364 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1365 /// update all uses of the load, keep track of what scalarized loads are
1366 /// inserted for a given load.
1367 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1368 InsertedScalarizedValues[GV] = FieldGlobals;
1369
1370 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371
1372 // Okay, the malloc site is completely handled. All of the uses of GV are now
1373 // loads, and all uses of those loads are simple. Rewrite them to use loads
1374 // of the per-field globals instead.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001375 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1376 Instruction *User = cast<Instruction>(*UI++);
1377
1378 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson086ea052009-07-06 01:34:54 +00001379 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1380 Context);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001381 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001383
1384 // Must be a store of null.
1385 StoreInst *SI = cast<StoreInst>(User);
1386 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1387 "Unexpected heap-sra user!");
1388
1389 // Insert a store of null into each global.
1390 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1391 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Owen Andersonaac28372009-07-31 20:28:14 +00001392 Constant *Null = Constant::getNullValue(PT->getElementType());
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001393 new StoreInst(Null, FieldGlobals[i], SI);
1394 }
1395 // Erase the original store.
1396 SI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 }
1398
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001399 // While we have PHIs that are interesting to rewrite, do it.
1400 while (!PHIsToRewrite.empty()) {
1401 PHINode *PN = PHIsToRewrite.back().first;
1402 unsigned FieldNo = PHIsToRewrite.back().second;
1403 PHIsToRewrite.pop_back();
1404 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1405 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1406
1407 // Add all the incoming values. This can materialize more phis.
1408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1409 Value *InVal = PN->getIncomingValue(i);
1410 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001411 PHIsToRewrite, Context);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001412 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1413 }
1414 }
1415
1416 // Drop all inter-phi links and any loads that made it this far.
1417 for (DenseMap<Value*, std::vector<Value*> >::iterator
1418 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1419 I != E; ++I) {
1420 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1421 PN->dropAllReferences();
1422 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1423 LI->dropAllReferences();
1424 }
1425
1426 // Delete all the phis and loads now that inter-references are dead.
1427 for (DenseMap<Value*, std::vector<Value*> >::iterator
1428 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1429 I != E; ++I) {
1430 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1431 PN->eraseFromParent();
1432 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1433 LI->eraseFromParent();
1434 }
1435
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 // The old global is now dead, remove it.
1437 GV->eraseFromParent();
1438
1439 ++NumHeapSRA;
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001440 return cast<GlobalVariable>(FieldGlobals[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441}
1442
Chris Lattner78e568b2008-12-15 21:02:25 +00001443/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1444/// pointer global variable with a single value stored it that is a malloc or
1445/// cast of malloc.
1446static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1447 MallocInst *MI,
1448 Module::global_iterator &GVI,
Owen Anderson086ea052009-07-06 01:34:54 +00001449 TargetData &TD,
Owen Anderson175b6542009-07-22 00:24:57 +00001450 LLVMContext &Context) {
Chris Lattner78e568b2008-12-15 21:02:25 +00001451 // If this is a malloc of an abstract type, don't touch it.
1452 if (!MI->getAllocatedType()->isSized())
1453 return false;
1454
1455 // We can't optimize this global unless all uses of it are *known* to be
1456 // of the malloc value, not of the null initializer value (consider a use
1457 // that compares the global's value against zero to see if the malloc has
1458 // been reached). To do this, we check to see if all uses of the global
1459 // would trap if the global were null: this proves that they must all
1460 // happen after the malloc.
1461 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1462 return false;
1463
1464 // We can't optimize this if the malloc itself is used in a complex way,
1465 // for example, being stored into multiple globals. This allows the
1466 // malloc to be stored into the specified global, loaded setcc'd, and
1467 // GEP'd. These are all things we could transform to using the global
1468 // for.
1469 {
1470 SmallPtrSet<PHINode*, 8> PHIs;
1471 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1472 return false;
1473 }
1474
1475
1476 // If we have a global that is only initialized with a fixed size malloc,
1477 // transform the program to use global memory instead of malloc'd memory.
1478 // This eliminates dynamic allocation, avoids an indirection accessing the
1479 // data, and exposes the resultant global to further GlobalOpt.
1480 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1481 // Restrict this transformation to only working on small allocations
1482 // (2048 bytes currently), as we don't want to introduce a 16M global or
1483 // something.
1484 if (NElements->getZExtValue()*
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001485 TD.getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Owen Anderson086ea052009-07-06 01:34:54 +00001486 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
Chris Lattner78e568b2008-12-15 21:02:25 +00001487 return true;
1488 }
1489 }
1490
1491 // If the allocation is an array of structures, consider transforming this
1492 // into multiple malloc'd arrays, one for each field. This is basically
1493 // SRoA for malloc'd memory.
Chris Lattner27ef89e2008-12-15 21:44:34 +00001494 const Type *AllocTy = MI->getAllocatedType();
1495
1496 // If this is an allocation of a fixed size array of structs, analyze as a
1497 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1498 if (!MI->isArrayAllocation())
1499 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1500 AllocTy = AT->getElementType();
1501
1502 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattner78e568b2008-12-15 21:02:25 +00001503 // This the structure has an unreasonable number of fields, leave it
1504 // alone.
Chris Lattner27ef89e2008-12-15 21:44:34 +00001505 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner7f252db2008-12-16 21:24:51 +00001506 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner27ef89e2008-12-15 21:44:34 +00001507
1508 // If this is a fixed size array, transform the Malloc to be an alloc of
1509 // structs. malloc [100 x struct],1 -> malloc struct, 100
1510 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1511 MallocInst *NewMI =
Owen Anderson140166d2009-07-15 23:53:25 +00001512 new MallocInst(AllocSTy,
Owen Anderson35b47072009-08-13 21:58:54 +00001513 ConstantInt::get(Type::getInt32Ty(Context),
1514 AT->getNumElements()),
Chris Lattner27ef89e2008-12-15 21:44:34 +00001515 "", MI);
1516 NewMI->takeName(MI);
1517 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1518 MI->replaceAllUsesWith(Cast);
1519 MI->eraseFromParent();
1520 MI = NewMI;
1521 }
1522
Owen Anderson086ea052009-07-06 01:34:54 +00001523 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattner78e568b2008-12-15 21:02:25 +00001524 return true;
1525 }
1526 }
1527
1528 return false;
1529}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530
1531// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1532// that only one value (besides its initializer) is ever stored to the global.
1533static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1534 Module::global_iterator &GVI,
Owen Anderson175b6542009-07-22 00:24:57 +00001535 TargetData &TD, LLVMContext &Context) {
Chris Lattner2e729112008-12-15 21:20:32 +00001536 // Ignore no-op GEPs and bitcasts.
1537 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538
1539 // If we are dealing with a pointer global that is initialized to null and
1540 // only has one (non-null) value stored into it, then we can optimize any
1541 // users of the loaded value (often calls and loads) that would trap if the
1542 // value was null.
1543 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1544 GV->getInitializer()->isNullValue()) {
1545 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1546 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson086ea052009-07-06 01:34:54 +00001547 SOVC =
Owen Anderson02b48c32009-07-29 18:55:55 +00001548 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549
1550 // Optimize away any trapping uses of the loaded value.
Owen Anderson086ea052009-07-06 01:34:54 +00001551 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001552 return true;
1553 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson086ea052009-07-06 01:34:54 +00001554 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattner78e568b2008-12-15 21:02:25 +00001555 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556 }
1557 }
1558
1559 return false;
1560}
1561
Chris Lattnerece46db2008-01-14 01:17:44 +00001562/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1563/// two values ever stored into GV are its initializer and OtherVal. See if we
1564/// can shrink the global into a boolean and select between the two values
1565/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson086ea052009-07-06 01:34:54 +00001566static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
Owen Anderson175b6542009-07-22 00:24:57 +00001567 LLVMContext &Context) {
Chris Lattnerece46db2008-01-14 01:17:44 +00001568 const Type *GVElType = GV->getType()->getElementType();
1569
1570 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001571 // an FP value, pointer or vector, don't do this optimization because a select
1572 // between them is very expensive and unlikely to lead to later
1573 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1574 // where v1 and v2 both require constant pool loads, a big loss.
Owen Anderson35b47072009-08-13 21:58:54 +00001575 if (GVElType == Type::getInt1Ty(Context) || GVElType->isFloatingPoint() ||
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001576 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattnerece46db2008-01-14 01:17:44 +00001577 return false;
1578
1579 // Walk the use list of the global seeing if all the uses are load or store.
1580 // If there is anything else, bail out.
1581 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel9b951552009-03-06 01:39:36 +00001582 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattnerece46db2008-01-14 01:17:44 +00001583 return false;
1584
1585 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1586
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001587 // Create the new global, initializing it to false.
Owen Anderson35b47072009-08-13 21:58:54 +00001588 GlobalVariable *NewGV = new GlobalVariable(Context,
1589 Type::getInt1Ty(Context), false,
Owen Anderson4f720fa2009-07-31 17:39:07 +00001590 GlobalValue::InternalLinkage, ConstantInt::getFalse(Context),
Nick Lewycky74e96b72009-05-03 03:49:08 +00001591 GV->getName()+".b",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592 GV->isThreadLocal());
1593 GV->getParent()->getGlobalList().insert(GV, NewGV);
1594
1595 Constant *InitVal = GV->getInitializer();
Owen Anderson35b47072009-08-13 21:58:54 +00001596 assert(InitVal->getType() != Type::getInt1Ty(Context) &&
1597 "No reason to shrink to bool!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598
1599 // If initialized to zero and storing one into the global, we can use a cast
1600 // instead of a select to synthesize the desired value.
1601 bool IsOneZero = false;
1602 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1603 IsOneZero = InitVal->isNullValue() && CI->isOne();
1604
1605 while (!GV->use_empty()) {
Devang Patel9b951552009-03-06 01:39:36 +00001606 Instruction *UI = cast<Instruction>(GV->use_back());
1607 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 // Change the store into a boolean store.
1609 bool StoringOther = SI->getOperand(0) == OtherVal;
1610 // Only do this if we weren't storing a loaded value.
1611 Value *StoreVal;
1612 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson35b47072009-08-13 21:58:54 +00001613 StoreVal = ConstantInt::get(Type::getInt1Ty(Context), StoringOther);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614 else {
1615 // Otherwise, we are storing a previously loaded copy. To do this,
1616 // change the copy from copying the original value to just copying the
1617 // bool.
1618 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1619
1620 // If we're already replaced the input, StoredVal will be a cast or
1621 // select instruction. If not, it will be a load of the original
1622 // global.
1623 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1624 assert(LI->getOperand(0) == GV && "Not a copy!");
1625 // Insert a new load, to preserve the saved value.
1626 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1627 } else {
1628 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1629 "This is not a form that we understand!");
1630 StoreVal = StoredVal->getOperand(0);
1631 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1632 }
1633 }
1634 new StoreInst(StoreVal, NewGV, SI);
Devang Patel9b951552009-03-06 01:39:36 +00001635 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 // Change the load into a load of bool then a select.
Devang Patel9b951552009-03-06 01:39:36 +00001637 LoadInst *LI = cast<LoadInst>(UI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001638 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1639 Value *NSI;
1640 if (IsOneZero)
1641 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1642 else
Gabor Greifd6da1d02008-04-06 20:25:17 +00001643 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001644 NSI->takeName(LI);
1645 LI->replaceAllUsesWith(NSI);
Devang Patel9b951552009-03-06 01:39:36 +00001646 }
1647 UI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 }
1649
1650 GV->eraseFromParent();
Chris Lattnerece46db2008-01-14 01:17:44 +00001651 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652}
1653
1654
1655/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1656/// it if possible. If we make a change, return true.
1657bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1658 Module::global_iterator &GVI) {
Chris Lattner4cd08c22008-12-16 07:34:30 +00001659 SmallPtrSet<PHINode*, 16> PHIUsers;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 GlobalStatus GS;
1661 GV->removeDeadConstantUsers();
1662
1663 if (GV->use_empty()) {
1664 DOUT << "GLOBAL DEAD: " << *GV;
1665 GV->eraseFromParent();
1666 ++NumDeleted;
1667 return true;
1668 }
1669
1670 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1671#if 0
1672 cerr << "Global: " << *GV;
1673 cerr << " isLoaded = " << GS.isLoaded << "\n";
1674 cerr << " StoredType = ";
1675 switch (GS.StoredType) {
1676 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1677 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1678 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1679 case GlobalStatus::isStored: cerr << "stored\n"; break;
1680 }
1681 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1682 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1683 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1684 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1685 << "\n";
1686 cerr << " HasMultipleAccessingFunctions = "
1687 << GS.HasMultipleAccessingFunctions << "\n";
1688 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689 cerr << "\n";
1690#endif
1691
1692 // If this is a first class global and has only one accessing function
1693 // and this function is main (which we know is not recursive we can make
1694 // this global a local variable) we replace the global with a local alloca
1695 // in this function.
1696 //
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001697 // NOTE: It doesn't make sense to promote non single-value types since we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 // are just replacing static memory to stack memory.
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001699 //
1700 // If the global is in different address space, don't bring it to stack.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 if (!GS.HasMultipleAccessingFunctions &&
1702 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001703 GV->getType()->getElementType()->isSingleValueType() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001705 GS.AccessingFunction->hasExternalLinkage() &&
1706 GV->getType()->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001707 DOUT << "LOCALIZING GLOBAL: " << *GV;
1708 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1709 const Type* ElemTy = GV->getType()->getElementType();
1710 // FIXME: Pass Global's alignment when globals have alignment
Owen Anderson140166d2009-07-15 23:53:25 +00001711 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 if (!isa<UndefValue>(GV->getInitializer()))
1713 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1714
1715 GV->replaceAllUsesWith(Alloca);
1716 GV->eraseFromParent();
1717 ++NumLocalized;
1718 return true;
1719 }
1720
1721 // If the global is never loaded (but may be stored to), it is dead.
1722 // Delete it now.
1723 if (!GS.isLoaded) {
1724 DOUT << "GLOBAL NEVER LOADED: " << *GV;
1725
1726 // Delete any stores we can find to the global. We may not be able to
1727 // make it completely dead though.
Owen Andersond4d90a02009-07-06 18:42:36 +00001728 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
Owen Anderson175b6542009-07-22 00:24:57 +00001729 GV->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001730
1731 // If the global is dead now, delete it.
1732 if (GV->use_empty()) {
1733 GV->eraseFromParent();
1734 ++NumDeleted;
1735 Changed = true;
1736 }
1737 return Changed;
1738
1739 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1740 DOUT << "MARKING CONSTANT: " << *GV;
1741 GV->setConstant(true);
1742
1743 // Clean up any obviously simplifiable users now.
Owen Anderson175b6542009-07-22 00:24:57 +00001744 CleanupConstantGlobalUsers(GV, GV->getInitializer(), GV->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745
1746 // If the global is dead now, just nuke it.
1747 if (GV->use_empty()) {
1748 DOUT << " *** Marking constant allowed us to simplify "
1749 << "all users and delete global!\n";
1750 GV->eraseFromParent();
1751 ++NumDeleted;
1752 }
1753
1754 ++NumMarked;
1755 return true;
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001756 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner20846272008-04-26 07:40:11 +00001757 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
Owen Anderson086ea052009-07-06 01:34:54 +00001758 getAnalysis<TargetData>(),
Owen Anderson175b6542009-07-22 00:24:57 +00001759 GV->getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 GVI = FirstNewGV; // Don't skip the newly produced globals!
1761 return true;
1762 }
1763 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1764 // If the initial value for the global was an undef value, and if only
1765 // one other value was stored into it, we can just change the
Duncan Sands25464152009-01-13 13:48:44 +00001766 // initializer to be the stored value, then delete all stores to the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767 // global. This allows us to mark it constant.
1768 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1769 if (isa<UndefValue>(GV->getInitializer())) {
1770 // Change the initial value here.
1771 GV->setInitializer(SOVConstant);
1772
1773 // Clean up any obviously simplifiable users now.
Owen Anderson175b6542009-07-22 00:24:57 +00001774 CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1775 GV->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776
1777 if (GV->use_empty()) {
1778 DOUT << " *** Substituting initializer allowed us to "
1779 << "simplify all users and delete global!\n";
1780 GV->eraseFromParent();
1781 ++NumDeleted;
1782 } else {
1783 GVI = GV;
1784 }
1785 ++NumSubstitute;
1786 return true;
1787 }
1788
1789 // Try to optimize globals based on the knowledge that only one value
1790 // (besides its initializer) is ever stored to the global.
1791 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Owen Anderson175b6542009-07-22 00:24:57 +00001792 getAnalysis<TargetData>(), GV->getContext()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793 return true;
1794
1795 // Otherwise, if the global was not a boolean, we can shrink it to be a
1796 // boolean.
1797 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Anderson175b6542009-07-22 00:24:57 +00001798 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, GV->getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799 ++NumShrunkToBool;
1800 return true;
1801 }
1802 }
1803 }
1804 return false;
1805}
1806
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1808/// function, changing them to FastCC.
1809static void ChangeCalleesToFastCall(Function *F) {
1810 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001811 CallSite User(cast<Instruction>(*UI));
1812 User.setCallingConv(CallingConv::Fast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813 }
1814}
1815
Devang Pateld222f862008-09-25 21:00:45 +00001816static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner1c8733e2008-03-12 17:45:29 +00001817 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Pateld222f862008-09-25 21:00:45 +00001818 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands551ec902008-02-18 17:32:13 +00001819 continue;
1820
Duncan Sands551ec902008-02-18 17:32:13 +00001821 // There can be only one.
Devang Pateld222f862008-09-25 21:00:45 +00001822 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001823 }
1824
1825 return Attrs;
1826}
1827
1828static void RemoveNestAttribute(Function *F) {
Devang Pateld222f862008-09-25 21:00:45 +00001829 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001830 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001831 CallSite User(cast<Instruction>(*UI));
Devang Pateld222f862008-09-25 21:00:45 +00001832 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001833 }
1834}
1835
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001836bool GlobalOpt::OptimizeFunctions(Module &M) {
1837 bool Changed = false;
1838 // Optimize functions.
1839 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1840 Function *F = FI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001841 // Functions without names cannot be referenced outside this module.
1842 if (!F->hasName() && !F->isDeclaration())
1843 F->setLinkage(GlobalValue::InternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001844 F->removeDeadConstantUsers();
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001845 if (F->use_empty() && (F->hasLocalLinkage() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001846 F->hasLinkOnceLinkage())) {
1847 M.getFunctionList().erase(F);
1848 Changed = true;
1849 ++NumFnDeleted;
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001850 } else if (F->hasLocalLinkage()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001851 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad1379d592009-06-10 08:41:11 +00001852 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001853 // If this function has C calling conventions, is not a varargs
1854 // function, and is only called directly, promote it to use the Fast
1855 // calling convention.
1856 F->setCallingConv(CallingConv::Fast);
1857 ChangeCalleesToFastCall(F);
1858 ++NumFastCallFns;
1859 Changed = true;
1860 }
1861
Devang Pateld222f862008-09-25 21:00:45 +00001862 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad1379d592009-06-10 08:41:11 +00001863 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001864 // The function is not used by a trampoline intrinsic, so it is safe
1865 // to remove the 'nest' attribute.
1866 RemoveNestAttribute(F);
1867 ++NumNestRemoved;
1868 Changed = true;
1869 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870 }
1871 }
1872 return Changed;
1873}
1874
1875bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1876 bool Changed = false;
1877 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1878 GVI != E; ) {
1879 GlobalVariable *GV = GVI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001880 // Global variables without names cannot be referenced outside this module.
1881 if (!GV->hasName() && !GV->isDeclaration())
1882 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001883 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001884 GV->hasInitializer())
1885 Changed |= ProcessInternalGlobal(GV, GVI);
1886 }
1887 return Changed;
1888}
1889
1890/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1891/// initializers have an init priority of 65535.
1892GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1893 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1894 I != E; ++I)
1895 if (I->getName() == "llvm.global_ctors") {
1896 // Found it, verify it's an array of { int, void()* }.
1897 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1898 if (!ATy) return 0;
1899 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1900 if (!STy || STy->getNumElements() != 2 ||
Owen Anderson35b47072009-08-13 21:58:54 +00001901 STy->getElementType(0) != Type::getInt32Ty(M.getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1903 if (!PFTy) return 0;
1904 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
Owen Anderson35b47072009-08-13 21:58:54 +00001905 if (!FTy || FTy->getReturnType() != Type::getVoidTy(M.getContext()) ||
1906 FTy->isVarArg() || FTy->getNumParams() != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 return 0;
1908
1909 // Verify that the initializer is simple enough for us to handle.
1910 if (!I->hasInitializer()) return 0;
1911 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1912 if (!CA) return 0;
Gabor Greif20f03f52008-05-29 01:59:18 +00001913 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1914 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001915 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1916 continue;
1917
1918 // Must have a function or null ptr.
1919 if (!isa<Function>(CS->getOperand(1)))
1920 return 0;
1921
1922 // Init priority must be standard.
1923 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1924 if (!CI || CI->getZExtValue() != 65535)
1925 return 0;
1926 } else {
1927 return 0;
1928 }
1929
1930 return I;
1931 }
1932 return 0;
1933}
1934
1935/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1936/// return a list of the functions and null terminator as a vector.
1937static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1938 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1939 std::vector<Function*> Result;
1940 Result.reserve(CA->getNumOperands());
Gabor Greif20f03f52008-05-29 01:59:18 +00001941 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1942 ConstantStruct *CS = cast<ConstantStruct>(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1944 }
1945 return Result;
1946}
1947
1948/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1949/// specified array, returning the new global to use.
1950static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson086ea052009-07-06 01:34:54 +00001951 const std::vector<Function*> &Ctors,
Owen Anderson175b6542009-07-22 00:24:57 +00001952 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001953 // If we made a change, reassemble the initializer list.
1954 std::vector<Constant*> CSVals;
Owen Anderson35b47072009-08-13 21:58:54 +00001955 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(Context), 65535));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 CSVals.push_back(0);
1957
1958 // Create the new init list.
1959 std::vector<Constant*> CAList;
1960 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1961 if (Ctors[i]) {
1962 CSVals[1] = Ctors[i];
1963 } else {
Owen Anderson35b47072009-08-13 21:58:54 +00001964 const Type *FTy = FunctionType::get(Type::getVoidTy(Context), false);
Owen Anderson6b6e2d92009-07-29 22:17:13 +00001965 const PointerType *PFTy = PointerType::getUnqual(FTy);
Owen Andersonaac28372009-07-31 20:28:14 +00001966 CSVals[1] = Constant::getNullValue(PFTy);
Owen Anderson35b47072009-08-13 21:58:54 +00001967 CSVals[0] = ConstantInt::get(Type::getInt32Ty(Context), 2147483647);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001968 }
Owen Andersond2ed7452009-08-05 23:16:16 +00001969 CAList.push_back(ConstantStruct::get(Context, CSVals));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970 }
1971
1972 // Create the array initializer.
1973 const Type *StructTy =
1974 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson7b4f9f82009-07-28 18:32:17 +00001975 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
Owen Anderson086ea052009-07-06 01:34:54 +00001976 CAList.size()), CAList);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977
1978 // If we didn't change the number of elements, don't create a new GV.
1979 if (CA->getType() == GCL->getInitializer()->getType()) {
1980 GCL->setInitializer(CA);
1981 return GCL;
1982 }
1983
1984 // Create the new global and insert it next to the existing list.
Owen Anderson175b6542009-07-22 00:24:57 +00001985 GlobalVariable *NGV = new GlobalVariable(Context, CA->getType(),
Owen Andersone0f136d2009-07-08 01:26:06 +00001986 GCL->isConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001987 GCL->getLinkage(), CA, "",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 GCL->isThreadLocal());
1989 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1990 NGV->takeName(GCL);
1991
1992 // Nuke the old list, replacing any uses with the new one.
1993 if (!GCL->use_empty()) {
1994 Constant *V = NGV;
1995 if (V->getType() != GCL->getType())
Owen Anderson02b48c32009-07-29 18:55:55 +00001996 V = ConstantExpr::getBitCast(V, GCL->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001997 GCL->replaceAllUsesWith(V);
1998 }
1999 GCL->eraseFromParent();
2000
2001 if (Ctors.size())
2002 return NGV;
2003 else
2004 return 0;
2005}
2006
2007
Chris Lattner4cd08c22008-12-16 07:34:30 +00002008static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002009 Value *V) {
2010 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2011 Constant *R = ComputedValues[V];
2012 assert(R && "Reference to an uncomputed value!");
2013 return R;
2014}
2015
2016/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2017/// enough for us to understand. In particular, if it is a cast of something,
2018/// we punt. We basically just support direct accesses to globals and GEP's of
2019/// globals. This should be kept up to date with CommitValueTo.
Owen Anderson175b6542009-07-22 00:24:57 +00002020static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002022 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002023 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2024 return !GV->isDeclaration(); // reject external globals.
2025 }
2026 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2027 // Handle a constantexpr gep.
2028 if (CE->getOpcode() == Instruction::GetElementPtr &&
2029 isa<GlobalVariable>(CE->getOperand(0))) {
2030 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002031 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002032 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2033 return GV->hasInitializer() &&
Owen Andersond4d90a02009-07-06 18:42:36 +00002034 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2035 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002036 }
2037 return false;
2038}
2039
2040/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2041/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2042/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2043static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson086ea052009-07-06 01:34:54 +00002044 ConstantExpr *Addr, unsigned OpNo,
Owen Anderson175b6542009-07-22 00:24:57 +00002045 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002046 // Base case of the recursion.
2047 if (OpNo == Addr->getNumOperands()) {
2048 assert(Val->getType() == Init->getType() && "Type mismatch!");
2049 return Val;
2050 }
2051
2052 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2053 std::vector<Constant*> Elts;
2054
2055 // Break up the constant into its elements.
2056 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002057 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2058 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059 } else if (isa<ConstantAggregateZero>(Init)) {
2060 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersonaac28372009-07-31 20:28:14 +00002061 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002062 } else if (isa<UndefValue>(Init)) {
2063 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Andersonb99ecca2009-07-30 23:03:37 +00002064 Elts.push_back(UndefValue::get(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002065 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002066 llvm_unreachable("This code is out of sync with "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002067 " ConstantFoldLoadThroughGEPConstantExpr");
2068 }
2069
2070 // Replace the element that we are supposed to.
2071 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2072 unsigned Idx = CU->getZExtValue();
2073 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson086ea052009-07-06 01:34:54 +00002074 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002075
2076 // Return the modified struct.
Owen Andersond2ed7452009-08-05 23:16:16 +00002077 return ConstantStruct::get(Context, &Elts[0], Elts.size(), STy->isPacked());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078 } else {
2079 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2080 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2081
2082 // Break up the array into elements.
2083 std::vector<Constant*> Elts;
2084 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002085 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2086 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002087 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Andersonaac28372009-07-31 20:28:14 +00002088 Constant *Elt = Constant::getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002089 Elts.assign(ATy->getNumElements(), Elt);
2090 } else if (isa<UndefValue>(Init)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +00002091 Constant *Elt = UndefValue::get(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 Elts.assign(ATy->getNumElements(), Elt);
2093 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00002094 llvm_unreachable("This code is out of sync with "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095 " ConstantFoldLoadThroughGEPConstantExpr");
2096 }
2097
2098 assert(CI->getZExtValue() < ATy->getNumElements());
2099 Elts[CI->getZExtValue()] =
Owen Anderson086ea052009-07-06 01:34:54 +00002100 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
Owen Anderson7b4f9f82009-07-28 18:32:17 +00002101 return ConstantArray::get(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002102 }
2103}
2104
2105/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2106/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson086ea052009-07-06 01:34:54 +00002107static void CommitValueTo(Constant *Val, Constant *Addr,
Owen Anderson175b6542009-07-22 00:24:57 +00002108 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2110 assert(GV->hasInitializer());
2111 GV->setInitializer(Val);
2112 return;
2113 }
2114
2115 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2116 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2117
2118 Constant *Init = GV->getInitializer();
Owen Anderson086ea052009-07-06 01:34:54 +00002119 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002120 GV->setInitializer(Init);
2121}
2122
2123/// ComputeLoadResult - Return the value that would be computed by a load from
2124/// P after the stores reflected by 'memory' have been performed. If we can't
2125/// decide, return null.
2126static Constant *ComputeLoadResult(Constant *P,
Owen Andersond4d90a02009-07-06 18:42:36 +00002127 const DenseMap<Constant*, Constant*> &Memory,
Owen Anderson175b6542009-07-22 00:24:57 +00002128 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 // If this memory location has been recently stored, use the stored value: it
2130 // is the most up-to-date.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002131 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002132 if (I != Memory.end()) return I->second;
2133
2134 // Access it.
2135 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2136 if (GV->hasInitializer())
2137 return GV->getInitializer();
2138 return 0;
2139 }
2140
2141 // Handle a constantexpr getelementptr.
2142 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2143 if (CE->getOpcode() == Instruction::GetElementPtr &&
2144 isa<GlobalVariable>(CE->getOperand(0))) {
2145 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2146 if (GV->hasInitializer())
Owen Andersond4d90a02009-07-06 18:42:36 +00002147 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2148 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002149 }
2150
2151 return 0; // don't know how to evaluate.
2152}
2153
2154/// EvaluateFunction - Evaluate a call to function F, returning true if
2155/// successful, false if we can't evaluate it. ActualArgs contains the formal
2156/// arguments for the function.
2157static bool EvaluateFunction(Function *F, Constant *&RetVal,
2158 const std::vector<Constant*> &ActualArgs,
2159 std::vector<Function*> &CallStack,
Chris Lattner4cd08c22008-12-16 07:34:30 +00002160 DenseMap<Constant*, Constant*> &MutatedMemory,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161 std::vector<GlobalVariable*> &AllocaTmps) {
2162 // Check to see if this function is already executing (recursion). If so,
2163 // bail out. TODO: we might want to accept limited recursion.
2164 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2165 return false;
2166
Owen Anderson175b6542009-07-22 00:24:57 +00002167 LLVMContext &Context = F->getContext();
Owen Anderson086ea052009-07-06 01:34:54 +00002168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002169 CallStack.push_back(F);
2170
2171 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002172 DenseMap<Value*, Constant*> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002173
2174 // Initialize arguments to the incoming values specified.
2175 unsigned ArgNo = 0;
2176 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2177 ++AI, ++ArgNo)
2178 Values[AI] = ActualArgs[ArgNo];
2179
2180 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2181 /// we can only evaluate any one basic block at most once. This set keeps
2182 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002183 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002184
2185 // CurInst - The current instruction we're evaluating.
2186 BasicBlock::iterator CurInst = F->begin()->begin();
2187
2188 // This is the main evaluation loop.
2189 while (1) {
2190 Constant *InstResult = 0;
2191
2192 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2193 if (SI->isVolatile()) return false; // no volatile accesses.
2194 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Andersond4d90a02009-07-06 18:42:36 +00002195 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002196 // If this is too complex for us to commit, reject it.
2197 return false;
2198 Constant *Val = getVal(Values, SI->getOperand(0));
2199 MutatedMemory[Ptr] = Val;
2200 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002201 InstResult = ConstantExpr::get(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202 getVal(Values, BO->getOperand(0)),
2203 getVal(Values, BO->getOperand(1)));
2204 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002205 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002206 getVal(Values, CI->getOperand(0)),
2207 getVal(Values, CI->getOperand(1)));
2208 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002209 InstResult = ConstantExpr::getCast(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 getVal(Values, CI->getOperand(0)),
2211 CI->getType());
2212 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002213 InstResult =
Owen Anderson02b48c32009-07-29 18:55:55 +00002214 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002215 getVal(Values, SI->getOperand(1)),
2216 getVal(Values, SI->getOperand(2)));
2217 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2218 Constant *P = getVal(Values, GEP->getOperand(0));
2219 SmallVector<Constant*, 8> GEPOps;
Gabor Greif20f03f52008-05-29 01:59:18 +00002220 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2221 i != e; ++i)
2222 GEPOps.push_back(getVal(Values, *i));
Owen Anderson086ea052009-07-06 01:34:54 +00002223 InstResult =
Owen Anderson02b48c32009-07-29 18:55:55 +00002224 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002225 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2226 if (LI->isVolatile()) return false; // no volatile accesses.
2227 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Andersond4d90a02009-07-06 18:42:36 +00002228 MutatedMemory, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002229 if (InstResult == 0) return false; // Could not evaluate load.
2230 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2231 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2232 const Type *Ty = AI->getType()->getElementType();
Owen Anderson175b6542009-07-22 00:24:57 +00002233 AllocaTmps.push_back(new GlobalVariable(Context, Ty, false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002234 GlobalValue::InternalLinkage,
Owen Andersonb99ecca2009-07-30 23:03:37 +00002235 UndefValue::get(Ty),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002236 AI->getName()));
2237 InstResult = AllocaTmps.back();
2238 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel5b1082b2009-03-09 23:04:12 +00002239
2240 // Debug info can safely be ignored here.
2241 if (isa<DbgInfoIntrinsic>(CI)) {
2242 ++CurInst;
2243 continue;
2244 }
2245
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002246 // Cannot handle inline asm.
2247 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2248
2249 // Resolve function pointers.
2250 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2251 if (!Callee) return false; // Cannot resolve.
2252
2253 std::vector<Constant*> Formals;
Gabor Greif20f03f52008-05-29 01:59:18 +00002254 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2255 i != e; ++i)
2256 Formals.push_back(getVal(Values, *i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002257
2258 if (Callee->isDeclaration()) {
2259 // If this is a function we can constant fold, do it.
2260 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2261 Formals.size())) {
2262 InstResult = C;
2263 } else {
2264 return false;
2265 }
2266 } else {
2267 if (Callee->getFunctionType()->isVarArg())
2268 return false;
2269
2270 Constant *RetVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271 // Execute the call, if successful, use the return value.
2272 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2273 MutatedMemory, AllocaTmps))
2274 return false;
2275 InstResult = RetVal;
2276 }
2277 } else if (isa<TerminatorInst>(CurInst)) {
2278 BasicBlock *NewBB = 0;
2279 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2280 if (BI->isUnconditional()) {
2281 NewBB = BI->getSuccessor(0);
2282 } else {
2283 ConstantInt *Cond =
2284 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2285 if (!Cond) return false; // Cannot determine.
2286
2287 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2288 }
2289 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2290 ConstantInt *Val =
2291 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2292 if (!Val) return false; // Cannot determine.
2293 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2294 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2295 if (RI->getNumOperands())
2296 RetVal = getVal(Values, RI->getOperand(0));
2297
2298 CallStack.pop_back(); // return from fn.
2299 return true; // We succeeded at evaluating this ctor!
2300 } else {
2301 // invoke, unwind, unreachable.
2302 return false; // Cannot handle this terminator.
2303 }
2304
2305 // Okay, we succeeded in evaluating this control flow. See if we have
2306 // executed the new block before. If so, we have a looping function,
2307 // which we cannot evaluate in reasonable time.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002308 if (!ExecutedBlocks.insert(NewBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002309 return false; // looped!
2310
2311 // Okay, we have never been in this block before. Check to see if there
2312 // are any PHI nodes. If so, evaluate them with information about where
2313 // we came from.
2314 BasicBlock *OldBB = CurInst->getParent();
2315 CurInst = NewBB->begin();
2316 PHINode *PN;
2317 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2318 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2319
2320 // Do NOT increment CurInst. We know that the terminator had no value.
2321 continue;
2322 } else {
2323 // Did not know how to evaluate this!
2324 return false;
2325 }
2326
2327 if (!CurInst->use_empty())
2328 Values[CurInst] = InstResult;
2329
2330 // Advance program counter.
2331 ++CurInst;
2332 }
2333}
2334
2335/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2336/// we can. Return true if we can, false otherwise.
2337static bool EvaluateStaticConstructor(Function *F) {
2338 /// MutatedMemory - For each store we execute, we update this map. Loads
2339 /// check this to get the most up-to-date value. If evaluation is successful,
2340 /// this state is committed to the process.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002341 DenseMap<Constant*, Constant*> MutatedMemory;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002342
2343 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2344 /// to represent its body. This vector is needed so we can delete the
2345 /// temporary globals when we are done.
2346 std::vector<GlobalVariable*> AllocaTmps;
2347
2348 /// CallStack - This is used to detect recursion. In pathological situations
2349 /// we could hit exponential behavior, but at least there is nothing
2350 /// unbounded.
2351 std::vector<Function*> CallStack;
2352
2353 // Call the function.
2354 Constant *RetValDummy;
2355 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2356 CallStack, MutatedMemory, AllocaTmps);
2357 if (EvalSuccess) {
2358 // We succeeded at evaluation: commit the result.
Daniel Dunbar005975c2009-07-25 00:23:56 +00002359 DEBUG(errs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2360 << F->getName() << "' to " << MutatedMemory.size()
2361 << " stores.\n");
Chris Lattner4cd08c22008-12-16 07:34:30 +00002362 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002363 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson086ea052009-07-06 01:34:54 +00002364 CommitValueTo(I->second, I->first, F->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002365 }
2366
2367 // At this point, we are done interpreting. If we created any 'alloca'
2368 // temporaries, release them now.
2369 while (!AllocaTmps.empty()) {
2370 GlobalVariable *Tmp = AllocaTmps.back();
2371 AllocaTmps.pop_back();
2372
2373 // If there are still users of the alloca, the program is doing something
2374 // silly, e.g. storing the address of the alloca somewhere and using it
2375 // later. Since this is undefined, we'll just make it be null.
2376 if (!Tmp->use_empty())
Owen Andersonaac28372009-07-31 20:28:14 +00002377 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002378 delete Tmp;
2379 }
2380
2381 return EvalSuccess;
2382}
2383
2384
2385
2386/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2387/// Return true if anything changed.
2388bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2389 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2390 bool MadeChange = false;
2391 if (Ctors.empty()) return false;
2392
2393 // Loop over global ctors, optimizing them when we can.
2394 for (unsigned i = 0; i != Ctors.size(); ++i) {
2395 Function *F = Ctors[i];
2396 // Found a null terminator in the middle of the list, prune off the rest of
2397 // the list.
2398 if (F == 0) {
2399 if (i != Ctors.size()-1) {
2400 Ctors.resize(i+1);
2401 MadeChange = true;
2402 }
2403 break;
2404 }
2405
2406 // We cannot simplify external ctor functions.
2407 if (F->empty()) continue;
2408
2409 // If we can evaluate the ctor at compile time, do.
2410 if (EvaluateStaticConstructor(F)) {
2411 Ctors.erase(Ctors.begin()+i);
2412 MadeChange = true;
2413 --i;
2414 ++NumCtorsEvaluated;
2415 continue;
2416 }
2417 }
2418
2419 if (!MadeChange) return false;
2420
Owen Anderson175b6542009-07-22 00:24:57 +00002421 GCL = InstallGlobalCtors(GCL, Ctors, GCL->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002422 return true;
2423}
2424
Duncan Sands0c7b6332009-03-06 10:21:56 +00002425bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002426 bool Changed = false;
2427
Duncan Sands0f064b92009-01-07 20:01:06 +00002428 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002429 I != E;) {
2430 Module::alias_iterator J = I++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00002431 // Aliases without names cannot be referenced outside this module.
2432 if (!J->hasName() && !J->isDeclaration())
2433 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002434 // If the aliasee may change at link time, nothing can be done - bail out.
2435 if (J->mayBeOverridden())
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002436 continue;
2437
Duncan Sandse7f431f2009-02-15 09:56:08 +00002438 Constant *Aliasee = J->getAliasee();
2439 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7531ad62009-02-18 17:55:38 +00002440 Target->removeDeadConstantUsers();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002441 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2442
2443 // Make all users of the alias use the aliasee instead.
2444 if (!J->use_empty()) {
2445 J->replaceAllUsesWith(Aliasee);
2446 ++NumAliasesResolved;
2447 Changed = true;
2448 }
2449
2450 // If the aliasee has internal linkage, give it the name and linkage
2451 // of the alias, and delete the alias. This turns:
2452 // define internal ... @f(...)
2453 // @a = alias ... @f
2454 // into:
2455 // define ... @a(...)
Duncan Sands8f723612009-02-17 17:50:04 +00002456 if (!Target->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002457 continue;
2458
2459 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands8f723612009-02-17 17:50:04 +00002460 if (J->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002461 continue;
2462
Duncan Sandse10858a2009-02-15 11:54:49 +00002463 // Do not perform the transform if multiple aliases potentially target the
2464 // aliasee. This check also ensures that it is safe to replace the section
2465 // and other attributes of the aliasee with those of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002466 if (!hasOneUse)
2467 continue;
2468
Duncan Sandse10858a2009-02-15 11:54:49 +00002469 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002470 Target->takeName(J);
2471 Target->setLinkage(J->getLinkage());
Duncan Sandse10858a2009-02-15 11:54:49 +00002472 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002473
2474 // Delete the alias.
2475 M.getAliasList().erase(J);
2476 ++NumAliasesRemoved;
2477 Changed = true;
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002478 }
2479
2480 return Changed;
2481}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002482
2483bool GlobalOpt::runOnModule(Module &M) {
2484 bool Changed = false;
2485
2486 // Try to find the llvm.globalctors list.
2487 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2488
2489 bool LocalChange = true;
2490 while (LocalChange) {
2491 LocalChange = false;
2492
2493 // Delete functions that are trivially dead, ccc -> fastcc
2494 LocalChange |= OptimizeFunctions(M);
2495
2496 // Optimize global_ctors list.
2497 if (GlobalCtors)
2498 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2499
2500 // Optimize non-address-taken globals.
2501 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002502
2503 // Resolve aliases, when possible.
Duncan Sands0c7b6332009-03-06 10:21:56 +00002504 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002505 Changed |= LocalChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 }
2507
2508 // TODO: Move all global ctors functions to the end of the module for code
2509 // layout.
2510
2511 return Changed;
2512}