blob: eb13067ff0c8025bc3c770f595b537fb71803386 [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"
Chris Lattner7bd79da2008-01-14 02:09:12 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner20846272008-04-26 07:40:11 +000032#include "llvm/Support/MathExtras.h"
Chris Lattner4cd08c22008-12-16 07:34:30 +000033#include "llvm/ADT/DenseMap.h"
Chris Lattnerbdf77462007-09-13 16:30:19 +000034#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/StringExtras.h"
Chris Lattner8a2d32e2008-12-17 05:28:49 +000038#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040using namespace llvm;
41
42STATISTIC(NumMarked , "Number of globals marked constant");
43STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
44STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
45STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46STATISTIC(NumDeleted , "Number of globals deleted");
47STATISTIC(NumFnDeleted , "Number of functions deleted");
48STATISTIC(NumGlobUses , "Number of global uses devirtualized");
49STATISTIC(NumLocalized , "Number of globals localized");
50STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
51STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
52STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sandsafa10bf2008-02-16 20:56:04 +000053STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Duncan Sandse7f431f2009-02-15 09:56:08 +000054STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056
57namespace {
58 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addRequired<TargetData>();
61 }
62 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000063 GlobalOpt() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064
65 bool runOnModule(Module &M);
66
67 private:
68 GlobalVariable *FindGlobalCtors(Module &M);
69 bool OptimizeFunctions(Module &M);
70 bool OptimizeGlobalVars(Module &M);
Duncan Sands0c7b6332009-03-06 10:21:56 +000071 bool OptimizeGlobalAliases(Module &M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
73 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
74 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075}
76
Dan Gohman089efff2008-05-13 00:00:25 +000077char GlobalOpt::ID = 0;
78static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
79
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
81
Dan Gohman089efff2008-05-13 00:00:25 +000082namespace {
83
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084/// GlobalStatus - As we analyze each global, keep track of some information
85/// about it. If we find out that the address of the global is taken, none of
86/// this info will be accurate.
87struct VISIBILITY_HIDDEN GlobalStatus {
88 /// isLoaded - True if the global is ever loaded. If the global isn't ever
89 /// loaded it can be deleted.
90 bool isLoaded;
91
92 /// StoredType - Keep track of what stores to the global look like.
93 ///
94 enum StoredType {
95 /// NotStored - There is no store to this global. It can thus be marked
96 /// constant.
97 NotStored,
98
99 /// isInitializerStored - This global is stored to, but the only thing
100 /// stored is the constant it was initialized with. This is only tracked
101 /// for scalar globals.
102 isInitializerStored,
103
104 /// isStoredOnce - This global is stored to, but only its initializer and
105 /// one other value is ever stored to it. If this global isStoredOnce, we
106 /// track the value stored to it in StoredOnceValue below. This is only
107 /// tracked for scalar globals.
108 isStoredOnce,
109
110 /// isStored - This global is stored to by multiple values or something else
111 /// that we cannot track.
112 isStored
113 } StoredType;
114
115 /// StoredOnceValue - If only one value (besides the initializer constant) is
116 /// ever stored to this global, keep track of what value it is.
117 Value *StoredOnceValue;
118
119 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
120 /// null/false. When the first accessing function is noticed, it is recorded.
121 /// When a second different accessing function is noticed,
122 /// HasMultipleAccessingFunctions is set to true.
123 Function *AccessingFunction;
124 bool HasMultipleAccessingFunctions;
125
126 /// HasNonInstructionUser - Set to true if this global has a user that is not
127 /// an instruction (e.g. a constant expr or GV initializer).
128 bool HasNonInstructionUser;
129
130 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
131 bool HasPHIUser;
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
134 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattnercad76212008-01-14 01:32:52 +0000135 HasNonInstructionUser(false), HasPHIUser(false) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136};
137
Dan Gohman089efff2008-05-13 00:00:25 +0000138}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139
Jay Foade4914352009-06-09 21:37:11 +0000140// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
141// by constants itself. Note that constants cannot be cyclic, so this test is
142// pretty easy to implement recursively.
143//
144static bool SafeToDestroyConstant(Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 if (isa<GlobalValue>(C)) return false;
146
Devang Patel3b6b19e2009-03-06 01:37:41 +0000147 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
148 if (Constant *CU = dyn_cast<Constant>(*UI)) {
Jay Foade4914352009-06-09 21:37:11 +0000149 if (!SafeToDestroyConstant(CU)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 } else
151 return false;
152 return true;
153}
154
155
156/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157/// structure. If the global has its address taken, return true to indicate we
158/// can't do anything with it.
159///
160static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
Chris Lattner4cd08c22008-12-16 07:34:30 +0000161 SmallPtrSet<PHINode*, 16> &PHIUsers) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
164 GS.HasNonInstructionUser = true;
165
166 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
168 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
169 if (!GS.HasMultipleAccessingFunctions) {
170 Function *F = I->getParent()->getParent();
171 if (GS.AccessingFunction == 0)
172 GS.AccessingFunction = F;
173 else if (GS.AccessingFunction != F)
174 GS.HasMultipleAccessingFunctions = true;
175 }
Chris Lattner75a2db82008-01-29 19:01:37 +0000176 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 GS.isLoaded = true;
Chris Lattner75a2db82008-01-29 19:01:37 +0000178 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
180 // Don't allow a store OF the address, only stores TO the address.
181 if (SI->getOperand(0) == V) return true;
182
Chris Lattner75a2db82008-01-29 19:01:37 +0000183 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 // If this is a direct store to the global (i.e., the global is a scalar
186 // value, not an aggregate), keep more specific information about
187 // stores.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000188 if (GS.StoredType != GlobalStatus::isStored) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
190 Value *StoredVal = SI->getOperand(0);
191 if (StoredVal == GV->getInitializer()) {
192 if (GS.StoredType < GlobalStatus::isInitializerStored)
193 GS.StoredType = GlobalStatus::isInitializerStored;
194 } else if (isa<LoadInst>(StoredVal) &&
195 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
196 // G = G
197 if (GS.StoredType < GlobalStatus::isInitializerStored)
198 GS.StoredType = GlobalStatus::isInitializerStored;
199 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200 GS.StoredType = GlobalStatus::isStoredOnce;
201 GS.StoredOnceValue = StoredVal;
202 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
203 GS.StoredOnceValue == StoredVal) {
204 // noop.
205 } else {
206 GS.StoredType = GlobalStatus::isStored;
207 }
208 } else {
209 GS.StoredType = GlobalStatus::isStored;
210 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000211 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 } else if (isa<GetElementPtrInst>(I)) {
213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 } else if (isa<SelectInst>(I)) {
215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
217 // PHI nodes we can check just like select or GEP instructions, but we
218 // have to be careful about infinite recursion.
Chris Lattner4cd08c22008-12-16 07:34:30 +0000219 if (PHIUsers.insert(PN)) // Not already visited.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 GS.HasPHIUser = true;
222 } else if (isa<CmpInst>(I)) {
Chris Lattnerb914b952009-03-08 03:37:35 +0000223 } else if (isa<MemTransferInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 if (I->getOperand(1) == V)
225 GS.StoredType = GlobalStatus::isStored;
226 if (I->getOperand(2) == V)
227 GS.isLoaded = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 } else if (isa<MemSetInst>(I)) {
229 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
230 GS.StoredType = GlobalStatus::isStored;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 } else {
232 return true; // Any other non-load instruction might take address!
233 }
234 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
235 GS.HasNonInstructionUser = true;
236 // We might have a dead and dangling constant hanging off of here.
Jay Foade4914352009-06-09 21:37:11 +0000237 if (!SafeToDestroyConstant(C))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 return true;
239 } else {
240 GS.HasNonInstructionUser = true;
241 // Otherwise must be some other user.
242 return true;
243 }
244
245 return false;
246}
247
Owen Anderson086ea052009-07-06 01:34:54 +0000248static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +0000249 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
251 if (!CI) return 0;
252 unsigned IdxV = CI->getZExtValue();
253
254 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
255 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
256 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
257 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
258 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
259 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
260 } else if (isa<ConstantAggregateZero>(Agg)) {
261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
Owen Anderson086ea052009-07-06 01:34:54 +0000263 return Context->getNullValue(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson086ea052009-07-06 01:34:54 +0000266 return Context->getNullValue(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 }
268 } else if (isa<UndefValue>(Agg)) {
269 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
270 if (IdxV < STy->getNumElements())
Owen Anderson086ea052009-07-06 01:34:54 +0000271 return Context->getUndef(STy->getElementType(IdxV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 } else if (const SequentialType *STy =
273 dyn_cast<SequentialType>(Agg->getType())) {
Owen Anderson086ea052009-07-06 01:34:54 +0000274 return Context->getUndef(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 }
276 }
277 return 0;
278}
279
280
281/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
282/// users of the global, cleaning up the obvious ones. This is largely just a
283/// quick scan over the use list to clean up the easy and obvious cruft. This
284/// returns true if it made a change.
Owen Andersond4d90a02009-07-06 18:42:36 +0000285static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
Owen Anderson5349f052009-07-06 23:00:19 +0000286 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 bool Changed = false;
288 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
289 User *U = *UI++;
290
291 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
292 if (Init) {
293 // Replace the load with the initializer.
294 LI->replaceAllUsesWith(Init);
295 LI->eraseFromParent();
296 Changed = true;
297 }
298 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
299 // Store must be unreachable or storing Init into the global.
300 SI->eraseFromParent();
301 Changed = true;
302 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
303 if (CE->getOpcode() == Instruction::GetElementPtr) {
304 Constant *SubInit = 0;
305 if (Init)
Owen Andersond4d90a02009-07-06 18:42:36 +0000306 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
307 Changed |= CleanupConstantGlobalUsers(CE, SubInit, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 } else if (CE->getOpcode() == Instruction::BitCast &&
309 isa<PointerType>(CE->getType())) {
310 // Pointer cast, delete any stores and memsets to the global.
Owen Andersond4d90a02009-07-06 18:42:36 +0000311 Changed |= CleanupConstantGlobalUsers(CE, 0, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 }
313
314 if (CE->use_empty()) {
315 CE->destroyConstant();
316 Changed = true;
317 }
318 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7ebafca2007-11-09 17:33:02 +0000319 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
320 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
321 // and will invalidate our notion of what Init is.
Chris Lattner2dd9c042007-11-13 21:46:23 +0000322 Constant *SubInit = 0;
Chris Lattner7ebafca2007-11-09 17:33:02 +0000323 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
324 ConstantExpr *CE =
Owen Andersond4d90a02009-07-06 18:42:36 +0000325 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, Context));
Chris Lattner7ebafca2007-11-09 17:33:02 +0000326 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Owen Andersond4d90a02009-07-06 18:42:36 +0000327 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE, Context);
Chris Lattner7ebafca2007-11-09 17:33:02 +0000328 }
Owen Andersond4d90a02009-07-06 18:42:36 +0000329 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
331 if (GEP->use_empty()) {
332 GEP->eraseFromParent();
333 Changed = true;
334 }
335 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
336 if (MI->getRawDest() == V) {
337 MI->eraseFromParent();
338 Changed = true;
339 }
340
341 } else if (Constant *C = dyn_cast<Constant>(U)) {
342 // If we have a chain of dead constantexprs or other things dangling from
343 // us, and if they are all dead, nuke them without remorse.
Jay Foade4914352009-06-09 21:37:11 +0000344 if (SafeToDestroyConstant(C)) {
Devang Patel3b6b19e2009-03-06 01:37:41 +0000345 C->destroyConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 // This could have invalidated UI, start over from scratch.
Owen Andersond4d90a02009-07-06 18:42:36 +0000347 CleanupConstantGlobalUsers(V, Init, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348 return true;
349 }
350 }
351 }
352 return Changed;
353}
354
Chris Lattner7bd79da2008-01-14 02:09:12 +0000355/// isSafeSROAElementUse - Return true if the specified instruction is a safe
356/// user of a derived expression from a global that we want to SROA.
357static bool isSafeSROAElementUse(Value *V) {
358 // We might have a dead and dangling constant hanging off of here.
359 if (Constant *C = dyn_cast<Constant>(V))
Jay Foade4914352009-06-09 21:37:11 +0000360 return SafeToDestroyConstant(C);
Chris Lattner7329c662008-01-14 01:31:05 +0000361
Chris Lattner7bd79da2008-01-14 02:09:12 +0000362 Instruction *I = dyn_cast<Instruction>(V);
363 if (!I) return false;
364
365 // Loads are ok.
366 if (isa<LoadInst>(I)) return true;
367
368 // Stores *to* the pointer are ok.
369 if (StoreInst *SI = dyn_cast<StoreInst>(I))
370 return SI->getOperand(0) != V;
371
372 // Otherwise, it must be a GEP.
373 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
374 if (GEPI == 0) return false;
375
376 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
377 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
378 return false;
379
380 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
381 I != E; ++I)
382 if (!isSafeSROAElementUse(*I))
383 return false;
Chris Lattner7329c662008-01-14 01:31:05 +0000384 return true;
385}
386
Chris Lattner7bd79da2008-01-14 02:09:12 +0000387
388/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
389/// Look at it and its uses and decide whether it is safe to SROA this global.
390///
391static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
392 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
393 if (!isa<GetElementPtrInst>(U) &&
394 (!isa<ConstantExpr>(U) ||
395 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
396 return false;
397
398 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
399 // don't like < 3 operand CE's, and we don't like non-constant integer
400 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
401 // value of C.
402 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
403 !cast<Constant>(U->getOperand(1))->isNullValue() ||
404 !isa<ConstantInt>(U->getOperand(2)))
405 return false;
406
407 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
408 ++GEPI; // Skip over the pointer index.
409
410 // If this is a use of an array allocation, do a bit more checking for sanity.
411 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
412 uint64_t NumElements = AT->getNumElements();
413 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
414
415 // Check to make sure that index falls within the array. If not,
416 // something funny is going on, so we won't do the optimization.
417 //
418 if (Idx->getZExtValue() >= NumElements)
419 return false;
420
421 // We cannot scalar repl this level of the array unless any array
422 // sub-indices are in-range constants. In particular, consider:
423 // A[0][i]. We cannot know that the user isn't doing invalid things like
424 // allowing i to index an out-of-range subscript that accesses A[1].
425 //
426 // Scalar replacing *just* the outer index of the array is probably not
427 // going to be a win anyway, so just give up.
428 for (++GEPI; // Skip array index.
429 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
430 ++GEPI) {
431 uint64_t NumElements;
432 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
433 NumElements = SubArrayTy->getNumElements();
434 else
435 NumElements = cast<VectorType>(*GEPI)->getNumElements();
436
437 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
438 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
439 return false;
440 }
441 }
442
443 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
444 if (!isSafeSROAElementUse(*I))
445 return false;
446 return true;
447}
448
449/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
450/// is safe for us to perform this transformation.
451///
452static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
453 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
454 UI != E; ++UI) {
455 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
456 return false;
457 }
458 return true;
459}
460
461
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
463/// variable. This opens the door for other optimizations by exposing the
464/// behavior of the program in a more fine-grained way. We have determined that
465/// this transformation is safe already. We return the first global variable we
466/// insert so that the caller can reprocess it.
Owen Anderson086ea052009-07-06 01:34:54 +0000467static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD,
Owen Anderson5349f052009-07-06 23:00:19 +0000468 LLVMContext *Context) {
Chris Lattner7329c662008-01-14 01:31:05 +0000469 // Make sure this global only has simple uses that we can SRA.
Chris Lattner7bd79da2008-01-14 02:09:12 +0000470 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner7329c662008-01-14 01:31:05 +0000471 return 0;
472
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000473 assert(GV->hasLocalLinkage() && !GV->isConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 Constant *Init = GV->getInitializer();
475 const Type *Ty = Init->getType();
476
477 std::vector<GlobalVariable*> NewGlobals;
478 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
479
Chris Lattner20846272008-04-26 07:40:11 +0000480 // Get the alignment of the global, either explicit or target-specific.
481 unsigned StartAlignment = GV->getAlignment();
482 if (StartAlignment == 0)
483 StartAlignment = TD.getABITypeAlignment(GV->getType());
484
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
486 NewGlobals.reserve(STy->getNumElements());
Chris Lattner20846272008-04-26 07:40:11 +0000487 const StructLayout &Layout = *TD.getStructLayout(STy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489 Constant *In = getAggregateConstantElement(Init,
Owen Anderson086ea052009-07-06 01:34:54 +0000490 Context->getConstantInt(Type::Int32Ty, i),
491 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492 assert(In && "Couldn't get element of initializer?");
Owen Andersone0f136d2009-07-08 01:26:06 +0000493 GlobalVariable *NGV = new GlobalVariable(*Context, STy->getElementType(i),
494 false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 GlobalVariable::InternalLinkage,
496 In, GV->getName()+"."+utostr(i),
497 (Module *)NULL,
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 Anderson086ea052009-07-06 01:34:54 +0000526 Context->getConstantInt(Type::Int32Ty, i),
527 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 assert(In && "Couldn't get element of initializer?");
529
Owen Andersone0f136d2009-07-08 01:26:06 +0000530 GlobalVariable *NGV = new GlobalVariable(*Context, STy->getElementType(),
531 false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 GlobalVariable::InternalLinkage,
533 In, GV->getName()+"."+utostr(i),
534 (Module *)NULL,
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000535 GV->isThreadLocal(),
536 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 Globals.insert(GV, NGV);
538 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000539
540 // Calculate the known alignment of the field. If the original aggregate
541 // had 256 byte alignment for example, something might depend on that:
542 // propagate info to each field.
543 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
544 if (NewAlign > EltAlign)
545 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 }
547 }
548
549 if (NewGlobals.empty())
550 return 0;
551
552 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
553
Owen Anderson086ea052009-07-06 01:34:54 +0000554 Constant *NullInt = Context->getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555
556 // Loop over all of the uses of the global, replacing the constantexpr geps,
557 // with smaller constantexpr geps or direct references.
558 while (!GV->use_empty()) {
559 User *GEP = GV->use_back();
560 assert(((isa<ConstantExpr>(GEP) &&
561 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
562 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
563
564 // Ignore the 1th operand, which has to be zero or else the program is quite
565 // broken (undefined). Get the 2nd operand, which is the structure or array
566 // index.
567 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
568 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
569
570 Value *NewPtr = NewGlobals[Val];
571
572 // Form a shorter GEP if needed.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000573 if (GEP->getNumOperands() > 3) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000574 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
575 SmallVector<Constant*, 8> Idxs;
576 Idxs.push_back(NullInt);
577 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
578 Idxs.push_back(CE->getOperand(i));
Owen Anderson086ea052009-07-06 01:34:54 +0000579 NewPtr = Context->getConstantExprGetElementPtr(cast<Constant>(NewPtr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580 &Idxs[0], Idxs.size());
581 } else {
582 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
583 SmallVector<Value*, 8> Idxs;
584 Idxs.push_back(NullInt);
585 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
586 Idxs.push_back(GEPI->getOperand(i));
Gabor Greifd6da1d02008-04-06 20:25:17 +0000587 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
588 GEPI->getName()+"."+utostr(Val), GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000590 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 GEP->replaceAllUsesWith(NewPtr);
592
593 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
594 GEPI->eraseFromParent();
595 else
596 cast<ConstantExpr>(GEP)->destroyConstant();
597 }
598
599 // Delete the old global, now that it is dead.
600 Globals.erase(GV);
601 ++NumSRA;
602
603 // Loop over the new globals array deleting any globals that are obviously
604 // dead. This can arise due to scalarization of a structure or an array that
605 // has elements that are dead.
606 unsigned FirstGlobal = 0;
607 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
608 if (NewGlobals[i]->use_empty()) {
609 Globals.erase(NewGlobals[i]);
610 if (FirstGlobal == i) ++FirstGlobal;
611 }
612
613 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
614}
615
616/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattnerbdf77462007-09-13 16:30:19 +0000617/// value will trap if the value is dynamically null. PHIs keeps track of any
618/// phi nodes we've seen to avoid reprocessing them.
619static bool AllUsesOfValueWillTrapIfNull(Value *V,
620 SmallPtrSet<PHINode*, 8> &PHIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
622 if (isa<LoadInst>(*UI)) {
623 // Will trap.
624 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
625 if (SI->getOperand(0) == V) {
626 //cerr << "NONTRAPPING USE: " << **UI;
627 return false; // Storing the value.
628 }
629 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
630 if (CI->getOperand(0) != V) {
631 //cerr << "NONTRAPPING USE: " << **UI;
632 return false; // Not calling the ptr
633 }
634 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
635 if (II->getOperand(0) != V) {
636 //cerr << "NONTRAPPING USE: " << **UI;
637 return false; // Not calling the ptr
638 }
Chris Lattnerbdf77462007-09-13 16:30:19 +0000639 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
640 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000642 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
643 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
644 // If we've already seen this phi node, ignore it, it has already been
645 // checked.
646 if (PHIs.insert(PN))
647 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 } else if (isa<ICmpInst>(*UI) &&
649 isa<ConstantPointerNull>(UI->getOperand(1))) {
650 // Ignore setcc X, null
651 } else {
652 //cerr << "NONTRAPPING USE: " << **UI;
653 return false;
654 }
655 return true;
656}
657
658/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
659/// from GV will trap if the loaded value is null. Note that this also permits
660/// comparisons of the loaded value against null, as a special case.
661static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
662 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
663 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000664 SmallPtrSet<PHINode*, 8> PHIs;
665 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 return false;
667 } else if (isa<StoreInst>(*UI)) {
668 // Ignore stores to the global.
669 } else {
670 // We don't know or understand this user, bail out.
671 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
672 return false;
673 }
674
675 return true;
676}
677
Owen Anderson086ea052009-07-06 01:34:54 +0000678static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
Owen Anderson5349f052009-07-06 23:00:19 +0000679 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 bool Changed = false;
681 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
682 Instruction *I = cast<Instruction>(*UI++);
683 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
684 LI->setOperand(0, NewV);
685 Changed = true;
686 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
687 if (SI->getOperand(1) == V) {
688 SI->setOperand(1, NewV);
689 Changed = true;
690 }
691 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
692 if (I->getOperand(0) == V) {
693 // Calling through the pointer! Turn into a direct call, but be careful
694 // that the pointer is not also being passed as an argument.
695 I->setOperand(0, NewV);
696 Changed = true;
697 bool PassedAsArg = false;
698 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
699 if (I->getOperand(i) == V) {
700 PassedAsArg = true;
701 I->setOperand(i, NewV);
702 }
703
704 if (PassedAsArg) {
705 // Being passed as an argument also. Be careful to not invalidate UI!
706 UI = V->use_begin();
707 }
708 }
709 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
710 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson086ea052009-07-06 01:34:54 +0000711 Context->getConstantExprCast(CI->getOpcode(),
712 NewV, CI->getType()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 if (CI->use_empty()) {
714 Changed = true;
715 CI->eraseFromParent();
716 }
717 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
718 // Should handle GEP here.
719 SmallVector<Constant*, 8> Idxs;
720 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif20f03f52008-05-29 01:59:18 +0000721 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
722 i != e; ++i)
723 if (Constant *C = dyn_cast<Constant>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 Idxs.push_back(C);
725 else
726 break;
727 if (Idxs.size() == GEPI->getNumOperands()-1)
728 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Anderson086ea052009-07-06 01:34:54 +0000729 Context->getConstantExprGetElementPtr(NewV, &Idxs[0],
730 Idxs.size()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731 if (GEPI->use_empty()) {
732 Changed = true;
733 GEPI->eraseFromParent();
734 }
735 }
736 }
737
738 return Changed;
739}
740
741
742/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
743/// value stored into it. If there are uses of the loaded value that would trap
744/// if the loaded value is dynamically null, then we know that they cannot be
745/// reachable with a null optimize away the load.
Owen Anderson086ea052009-07-06 01:34:54 +0000746static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
Owen Anderson5349f052009-07-06 23:00:19 +0000747 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748 bool Changed = false;
749
Chris Lattner9806cc12009-01-14 00:12:58 +0000750 // Keep track of whether we are able to remove all the uses of the global
751 // other than the store that defines it.
752 bool AllNonStoreUsesGone = true;
753
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner9806cc12009-01-14 00:12:58 +0000755 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
756 User *GlobalUser = *GUI++;
757 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson086ea052009-07-06 01:34:54 +0000758 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner9806cc12009-01-14 00:12:58 +0000759 // If we were able to delete all uses of the loads
760 if (LI->use_empty()) {
761 LI->eraseFromParent();
762 Changed = true;
763 } else {
764 AllNonStoreUsesGone = false;
765 }
766 } else if (isa<StoreInst>(GlobalUser)) {
767 // Ignore the store that stores "LV" to the global.
768 assert(GlobalUser->getOperand(1) == GV &&
769 "Must be storing *to* the global");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 } else {
Chris Lattner9806cc12009-01-14 00:12:58 +0000771 AllNonStoreUsesGone = false;
772
773 // If we get here we could have other crazy uses that are transitively
774 // loaded.
775 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
776 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777 }
Chris Lattner9806cc12009-01-14 00:12:58 +0000778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779
780 if (Changed) {
781 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
782 ++NumGlobUses;
783 }
784
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 // If we nuked all of the loads, then none of the stores are needed either,
786 // nor is the global.
Chris Lattner9806cc12009-01-14 00:12:58 +0000787 if (AllNonStoreUsesGone) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 DOUT << " *** GLOBAL NOW DEAD!\n";
Owen Andersond4d90a02009-07-06 18:42:36 +0000789 CleanupConstantGlobalUsers(GV, 0, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000790 if (GV->use_empty()) {
791 GV->eraseFromParent();
792 ++NumDeleted;
793 }
794 Changed = true;
795 }
796 return Changed;
797}
798
799/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
800/// instructions that are foldable.
Owen Anderson5349f052009-07-06 23:00:19 +0000801static void ConstantPropUsersOf(Value *V, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
803 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Andersond4d90a02009-07-06 18:42:36 +0000804 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 I->replaceAllUsesWith(NewC);
806
807 // Advance UI to the next non-I use to avoid invalidating it!
808 // Instructions could multiply use V.
809 while (UI != E && *UI == I)
810 ++UI;
811 I->eraseFromParent();
812 }
813}
814
815/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
816/// variable, and transforms the program as if it always contained the result of
817/// the specified malloc. Because it is always the result of the specified
818/// malloc, there is no reason to actually DO the malloc. Instead, turn the
819/// malloc into a global, and any loads of GV as uses of the new global.
820static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson086ea052009-07-06 01:34:54 +0000821 MallocInst *MI,
Owen Anderson5349f052009-07-06 23:00:19 +0000822 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
824 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
825
826 if (NElements->getZExtValue() != 1) {
827 // If we have an array allocation, transform it to a single element
828 // allocation to make the code below simpler.
Owen Anderson086ea052009-07-06 01:34:54 +0000829 Type *NewTy = Context->getArrayType(MI->getAllocatedType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830 NElements->getZExtValue());
831 MallocInst *NewMI =
Owen Anderson086ea052009-07-06 01:34:54 +0000832 new MallocInst(NewTy, Context->getNullValue(Type::Int32Ty),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 MI->getAlignment(), MI->getName(), MI);
834 Value* Indices[2];
Owen Anderson086ea052009-07-06 01:34:54 +0000835 Indices[0] = Indices[1] = Context->getNullValue(Type::Int32Ty);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000836 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
837 NewMI->getName()+".el0", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 MI->replaceAllUsesWith(NewGEP);
839 MI->eraseFromParent();
840 MI = NewMI;
841 }
842
843 // Create the new global variable. The contents of the malloc'd memory is
844 // undefined, so initialize with an undef value.
Owen Anderson086ea052009-07-06 01:34:54 +0000845 Constant *Init = Context->getUndef(MI->getAllocatedType());
Owen Andersone0f136d2009-07-08 01:26:06 +0000846 GlobalVariable *NewGV = new GlobalVariable(*Context, MI->getAllocatedType(),
847 false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 GlobalValue::InternalLinkage, Init,
849 GV->getName()+".body",
850 (Module *)NULL,
851 GV->isThreadLocal());
Chris Lattner20846272008-04-26 07:40:11 +0000852 // FIXME: This new global should have the alignment returned by malloc. Code
853 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
854 // this would only guarantee some lower alignment.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 GV->getParent()->getGlobalList().insert(GV, NewGV);
856
857 // Anything that used the malloc now uses the global directly.
858 MI->replaceAllUsesWith(NewGV);
859
860 Constant *RepValue = NewGV;
861 if (NewGV->getType() != GV->getType()->getElementType())
Owen Anderson086ea052009-07-06 01:34:54 +0000862 RepValue = Context->getConstantExprBitCast(RepValue,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 GV->getType()->getElementType());
864
865 // If there is a comparison against null, we will insert a global bool to
866 // keep track of whether the global was initialized yet or not.
867 GlobalVariable *InitBool =
Owen Andersone0f136d2009-07-08 01:26:06 +0000868 new GlobalVariable(*Context, Type::Int1Ty, false,
869 GlobalValue::InternalLinkage,
Owen Anderson086ea052009-07-06 01:34:54 +0000870 Context->getConstantIntFalse(), GV->getName()+".init",
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 (Module *)NULL, GV->isThreadLocal());
872 bool InitBoolUsed = false;
873
874 // Loop over all uses of GV, processing them in turn.
875 std::vector<StoreInst*> Stores;
876 while (!GV->use_empty())
877 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
878 while (!LI->use_empty()) {
879 Use &LoadUse = LI->use_begin().getUse();
880 if (!isa<ICmpInst>(LoadUse.getUser()))
881 LoadUse = RepValue;
882 else {
883 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
884 // Replace the cmp X, 0 with a use of the bool value.
885 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
886 InitBoolUsed = true;
887 switch (CI->getPredicate()) {
888 default: assert(0 && "Unknown ICmp Predicate!");
889 case ICmpInst::ICMP_ULT:
890 case ICmpInst::ICMP_SLT:
Owen Anderson086ea052009-07-06 01:34:54 +0000891 LV = Context->getConstantIntFalse(); // X < null -> always false
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 break;
893 case ICmpInst::ICMP_ULE:
894 case ICmpInst::ICMP_SLE:
895 case ICmpInst::ICMP_EQ:
Gabor Greifa645dd32008-05-16 19:29:10 +0000896 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 break;
898 case ICmpInst::ICMP_NE:
899 case ICmpInst::ICMP_UGE:
900 case ICmpInst::ICMP_SGE:
901 case ICmpInst::ICMP_UGT:
902 case ICmpInst::ICMP_SGT:
903 break; // no change.
904 }
905 CI->replaceAllUsesWith(LV);
906 CI->eraseFromParent();
907 }
908 }
909 LI->eraseFromParent();
910 } else {
911 StoreInst *SI = cast<StoreInst>(GV->use_back());
912 // The global is initialized when the store to it occurs.
Owen Anderson086ea052009-07-06 01:34:54 +0000913 new StoreInst(Context->getConstantIntTrue(), InitBool, SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 SI->eraseFromParent();
915 }
916
917 // If the initialization boolean was used, insert it, otherwise delete it.
918 if (!InitBoolUsed) {
919 while (!InitBool->use_empty()) // Delete initializations
920 cast<Instruction>(InitBool->use_back())->eraseFromParent();
921 delete InitBool;
922 } else
923 GV->getParent()->getGlobalList().insert(GV, InitBool);
924
925
926 // Now the GV is dead, nuke it and the malloc.
927 GV->eraseFromParent();
928 MI->eraseFromParent();
929
930 // To further other optimizations, loop over all users of NewGV and try to
931 // constant prop them. This will promote GEP instructions with constant
932 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Owen Andersond4d90a02009-07-06 18:42:36 +0000933 ConstantPropUsersOf(NewGV, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 if (RepValue != NewGV)
Owen Andersond4d90a02009-07-06 18:42:36 +0000935 ConstantPropUsersOf(RepValue, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936
937 return NewGV;
938}
939
940/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
941/// to make sure that there are no complex uses of V. We permit simple things
942/// like dereferencing the pointer, but not storing through the address, unless
943/// it is to the specified global.
944static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnere7606f42007-09-13 16:37:20 +0000945 GlobalVariable *GV,
946 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner183b0cf2008-12-15 21:08:54 +0000947 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foadd1d6a142009-06-06 17:49:35 +0000948 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner183b0cf2008-12-15 21:08:54 +0000949
950 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
951 continue; // Fine, ignore.
952 }
953
954 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
956 return false; // Storing the pointer itself... bad.
Chris Lattner183b0cf2008-12-15 21:08:54 +0000957 continue; // Otherwise, storing through it, or storing into GV... fine.
958 }
959
960 if (isa<GetElementPtrInst>(Inst)) {
961 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000963 continue;
964 }
965
966 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnere7606f42007-09-13 16:37:20 +0000967 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
968 // cycles.
969 if (PHIs.insert(PN))
Chris Lattner4bde3c42007-09-14 03:41:21 +0000970 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
971 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000972 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 }
Chris Lattner183b0cf2008-12-15 21:08:54 +0000974
975 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
976 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
977 return false;
978 continue;
979 }
980
981 return false;
982 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 return true;
984}
985
986/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
987/// somewhere. Transform all uses of the allocation into loads from the
988/// global and uses of the resultant pointer. Further, delete the store into
989/// GV. This assumes that these value pass the
990/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
991static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
992 GlobalVariable *GV) {
993 while (!Alloc->use_empty()) {
Chris Lattner20eef0f2007-09-13 18:00:31 +0000994 Instruction *U = cast<Instruction>(*Alloc->use_begin());
995 Instruction *InsertPt = U;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
997 // If this is the store of the allocation into the global, remove it.
998 if (SI->getOperand(1) == GV) {
999 SI->eraseFromParent();
1000 continue;
1001 }
Chris Lattner20eef0f2007-09-13 18:00:31 +00001002 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1003 // Insert the load in the corresponding predecessor, not right before the
1004 // PHI.
Gabor Greif261734d2009-01-23 19:40:15 +00001005 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner27ef89e2008-12-15 21:44:34 +00001006 } else if (isa<BitCastInst>(U)) {
1007 // Must be bitcast between the malloc and store to initialize the global.
1008 ReplaceUsesOfMallocWithGlobal(U, GV);
1009 U->eraseFromParent();
1010 continue;
1011 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1012 // If this is a "GEP bitcast" and the user is a store to the global, then
1013 // just process it as a bitcast.
1014 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1015 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1016 if (SI->getOperand(1) == GV) {
1017 // Must be bitcast GEP between the malloc and store to initialize
1018 // the global.
1019 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1020 GEPI->eraseFromParent();
1021 continue;
1022 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 }
Chris Lattner27ef89e2008-12-15 21:44:34 +00001024
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 // Insert a load from the global, and use it instead of the malloc.
Chris Lattner20eef0f2007-09-13 18:00:31 +00001026 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027 U->replaceUsesOfWith(Alloc, NL);
1028 }
1029}
1030
Chris Lattner7f252db2008-12-16 21:24:51 +00001031/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1032/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1033/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001034static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Chengb00d9282009-06-02 00:56:07 +00001035 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1036 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner7f252db2008-12-16 21:24:51 +00001037 // We permit two users of the load: setcc comparing against the null
1038 // pointer, and a getelementptr of a specific form.
1039 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1040 Instruction *User = cast<Instruction>(*UI);
1041
1042 // Comparison against null is ok.
1043 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1044 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1045 return false;
1046 continue;
1047 }
1048
1049 // getelementptr is also ok, but only a simple form.
1050 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1051 // Must index into the array and into the struct.
1052 if (GEPI->getNumOperands() < 3)
1053 return false;
1054
1055 // Otherwise the GEP is ok.
1056 continue;
1057 }
1058
1059 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Chengb00d9282009-06-02 00:56:07 +00001060 if (!LoadUsingPHIsPerLoad.insert(PN))
1061 // This means some phi nodes are dependent on each other.
1062 // Avoid infinite looping!
1063 return false;
1064 if (!LoadUsingPHIs.insert(PN))
1065 // If we have already analyzed this PHI, then it is safe.
Chris Lattner7f252db2008-12-16 21:24:51 +00001066 continue;
1067
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001068 // Make sure all uses of the PHI are simple enough to transform.
Evan Chengb00d9282009-06-02 00:56:07 +00001069 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1070 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001071 return false;
1072
1073 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 }
Chris Lattner7f252db2008-12-16 21:24:51 +00001075
1076 // Otherwise we don't know what this is, not ok.
1077 return false;
1078 }
1079
1080 return true;
1081}
1082
1083
1084/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1085/// GV are simple enough to perform HeapSRA, return true.
1086static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1087 MallocInst *MI) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001088 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Chengb00d9282009-06-02 00:56:07 +00001089 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner7f252db2008-12-16 21:24:51 +00001090 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1091 ++UI)
Evan Chengb00d9282009-06-02 00:56:07 +00001092 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1093 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1094 LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001095 return false;
Evan Chengb00d9282009-06-02 00:56:07 +00001096 LoadUsingPHIsPerLoad.clear();
1097 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001098
1099 // If we reach here, we know that all uses of the loads and transitive uses
1100 // (through PHI nodes) are simple enough to transform. However, we don't know
1101 // that all inputs the to the PHI nodes are in the same equivalence sets.
1102 // Check to verify that all operands of the PHIs are either PHIS that can be
1103 // transformed, loads from GV, or MI itself.
1104 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1105 E = LoadUsingPHIs.end(); I != E; ++I) {
1106 PHINode *PN = *I;
1107 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1108 Value *InVal = PN->getIncomingValue(op);
1109
1110 // PHI of the stored value itself is ok.
1111 if (InVal == MI) continue;
1112
1113 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1114 // One of the PHIs in our set is (optimistically) ok.
1115 if (LoadUsingPHIs.count(InPN))
1116 continue;
1117 return false;
1118 }
1119
1120 // Load from GV is ok.
1121 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1122 if (LI->getOperand(0) == GV)
1123 continue;
1124
1125 // UNDEF? NULL?
1126
1127 // Anything else is rejected.
1128 return false;
1129 }
1130 }
1131
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 return true;
1133}
1134
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001135static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1136 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001137 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson5349f052009-07-06 23:00:19 +00001138 LLVMContext *Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001139 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1140
1141 if (FieldNo >= FieldVals.size())
1142 FieldVals.resize(FieldNo+1);
1143
1144 // If we already have this value, just reuse the previously scalarized
1145 // version.
1146 if (Value *FieldVal = FieldVals[FieldNo])
1147 return FieldVal;
1148
1149 // Depending on what instruction this is, we have several cases.
1150 Value *Result;
1151 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1152 // This is a scalarized version of the load from the global. Just create
1153 // a new Load of the scalarized global.
1154 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1155 InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001156 PHIsToRewrite, Context),
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001157 LI->getName()+".f" + utostr(FieldNo), LI);
1158 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1159 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1160 // field.
1161 const StructType *ST =
1162 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1163
Owen Anderson086ea052009-07-06 01:34:54 +00001164 Result =
1165 PHINode::Create(Context->getPointerTypeUnqual(ST->getElementType(FieldNo)),
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001166 PN->getName()+".f"+utostr(FieldNo), PN);
1167 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1168 } else {
1169 assert(0 && "Unknown usable value");
1170 Result = 0;
1171 }
1172
1173 return FieldVals[FieldNo] = Result;
Chris Lattner20eef0f2007-09-13 18:00:31 +00001174}
1175
Chris Lattneraf82fb82007-09-13 17:29:05 +00001176/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1177/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001178static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1179 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001180 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson5349f052009-07-06 23:00:19 +00001181 LLVMContext *Context) {
Chris Lattneraf82fb82007-09-13 17:29:05 +00001182 // If this is a comparison against null, handle it.
1183 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1184 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1185 // If we have a setcc of the loaded pointer, we can use a setcc of any
1186 // field.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001187 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson086ea052009-07-06 01:34:54 +00001188 InsertedScalarizedValues, PHIsToRewrite,
1189 Context);
Chris Lattneraf82fb82007-09-13 17:29:05 +00001190
1191 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
Owen Anderson086ea052009-07-06 01:34:54 +00001192 Context->getNullValue(NPtr->getType()),
Chris Lattneraf82fb82007-09-13 17:29:05 +00001193 SCI->getName(), SCI);
1194 SCI->replaceAllUsesWith(New);
1195 SCI->eraseFromParent();
1196 return;
1197 }
1198
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001199 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattner20eef0f2007-09-13 18:00:31 +00001200 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1201 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1202 && "Unexpected GEPI!");
Chris Lattneraf82fb82007-09-13 17:29:05 +00001203
Chris Lattner20eef0f2007-09-13 18:00:31 +00001204 // Load the pointer for this field.
1205 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001206 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson086ea052009-07-06 01:34:54 +00001207 InsertedScalarizedValues, PHIsToRewrite,
1208 Context);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001209
1210 // Create the new GEP idx vector.
1211 SmallVector<Value*, 8> GEPIdx;
1212 GEPIdx.push_back(GEPI->getOperand(1));
1213 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1214
Gabor Greifb91ea9d2008-05-15 10:04:30 +00001215 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1216 GEPIdx.begin(), GEPIdx.end(),
Gabor Greifd6da1d02008-04-06 20:25:17 +00001217 GEPI->getName(), GEPI);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001218 GEPI->replaceAllUsesWith(NGEPI);
1219 GEPI->eraseFromParent();
1220 return;
1221 }
Chris Lattnereefff982007-09-13 21:31:36 +00001222
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001223 // Recursively transform the users of PHI nodes. This will lazily create the
1224 // PHIs that are needed for individual elements. Keep track of what PHIs we
1225 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1226 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1227 // already been seen first by another load, so its uses have already been
1228 // processed.
1229 PHINode *PN = cast<PHINode>(LoadUser);
1230 bool Inserted;
1231 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1232 tie(InsertPos, Inserted) =
1233 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1234 if (!Inserted) return;
Chris Lattnereefff982007-09-13 21:31:36 +00001235
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001236 // If this is the first time we've seen this PHI, recursively process all
1237 // users.
Chris Lattnera5e124b2008-12-17 05:42:08 +00001238 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1239 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001240 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1241 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001242 }
Chris Lattneraf82fb82007-09-13 17:29:05 +00001243}
1244
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1246/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1247/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner7f252db2008-12-16 21:24:51 +00001248/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattneraf82fb82007-09-13 17:29:05 +00001249static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001250 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001251 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
Owen Anderson5349f052009-07-06 23:00:19 +00001252 LLVMContext *Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001253 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnera5e124b2008-12-17 05:42:08 +00001254 UI != E; ) {
1255 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001256 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1257 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001258 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001259
1260 if (Load->use_empty()) {
1261 Load->eraseFromParent();
1262 InsertedScalarizedValues.erase(Load);
1263 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264}
1265
1266/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1267/// it up into multiple allocations of arrays of the fields.
Owen Anderson086ea052009-07-06 01:34:54 +00001268static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
Owen Anderson5349f052009-07-06 23:00:19 +00001269 LLVMContext *Context){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
1271 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1272
1273 // There is guaranteed to be at least one use of the malloc (storing
1274 // it into GV). If there are other uses, change them to be uses of
1275 // the global to simplify later code. This also deletes the store
1276 // into GV.
1277 ReplaceUsesOfMallocWithGlobal(MI, GV);
1278
1279 // Okay, at this point, there are no users of the malloc. Insert N
1280 // new mallocs at the same place as MI, and N globals.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001281 std::vector<Value*> FieldGlobals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 std::vector<MallocInst*> FieldMallocs;
1283
1284 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1285 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Anderson086ea052009-07-06 01:34:54 +00001286 const Type *PFieldTy = Context->getPointerTypeUnqual(FieldTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287
1288 GlobalVariable *NGV =
Owen Andersone0f136d2009-07-08 01:26:06 +00001289 new GlobalVariable(*Context, PFieldTy, false,
1290 GlobalValue::InternalLinkage,
Owen Anderson086ea052009-07-06 01:34:54 +00001291 Context->getNullValue(PFieldTy),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 GV->getName() + ".f" + utostr(FieldNo), GV,
1293 GV->isThreadLocal());
1294 FieldGlobals.push_back(NGV);
1295
1296 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1297 MI->getName() + ".f" + utostr(FieldNo),MI);
1298 FieldMallocs.push_back(NMI);
1299 new StoreInst(NMI, NGV, MI);
1300 }
1301
1302 // The tricky aspect of this transformation is handling the case when malloc
1303 // fails. In the original code, malloc failing would set the result pointer
1304 // of malloc to null. In this case, some mallocs could succeed and others
1305 // could fail. As such, we emit code that looks like this:
1306 // F0 = malloc(field0)
1307 // F1 = malloc(field1)
1308 // F2 = malloc(field2)
1309 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1310 // if (F0) { free(F0); F0 = 0; }
1311 // if (F1) { free(F1); F1 = 0; }
1312 // if (F2) { free(F2); F2 = 0; }
1313 // }
1314 Value *RunningOr = 0;
1315 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1316 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Anderson086ea052009-07-06 01:34:54 +00001317 Context->getNullValue(FieldMallocs[i]->getType()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 "isnull", MI);
1319 if (!RunningOr)
1320 RunningOr = Cond; // First seteq
1321 else
Gabor Greifa645dd32008-05-16 19:29:10 +00001322 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 }
1324
1325 // Split the basic block at the old malloc.
1326 BasicBlock *OrigBB = MI->getParent();
1327 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1328
1329 // Create the block to check the first condition. Put all these blocks at the
1330 // end of the function as they are unlikely to be executed.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001331 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1332 OrigBB->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333
1334 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1335 // branch on RunningOr.
1336 OrigBB->getTerminator()->eraseFromParent();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001337 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338
1339 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1340 // pointer, because some may be null while others are not.
1341 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1342 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1343 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
Owen Anderson086ea052009-07-06 01:34:54 +00001344 Context->getNullValue(GVVal->getType()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 "tmp", NullPtrBlock);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001346 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1347 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1348 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
1350 // Fill in FreeBlock.
1351 new FreeInst(GVVal, FreeBlock);
Owen Anderson086ea052009-07-06 01:34:54 +00001352 new StoreInst(Context->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 Anderson086ea052009-07-06 01:34:54 +00001392 Constant *Null = Context->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 Anderson5349f052009-07-06 23:00:19 +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 =
1512 new MallocInst(AllocSTy,
Owen Anderson086ea052009-07-06 01:34:54 +00001513 Context->getConstantInt(Type::Int32Ty, AT->getNumElements()),
Chris Lattner27ef89e2008-12-15 21:44:34 +00001514 "", MI);
1515 NewMI->takeName(MI);
1516 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1517 MI->replaceAllUsesWith(Cast);
1518 MI->eraseFromParent();
1519 MI = NewMI;
1520 }
1521
Owen Anderson086ea052009-07-06 01:34:54 +00001522 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattner78e568b2008-12-15 21:02:25 +00001523 return true;
1524 }
1525 }
1526
1527 return false;
1528}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529
1530// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1531// that only one value (besides its initializer) is ever stored to the global.
1532static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1533 Module::global_iterator &GVI,
Owen Anderson5349f052009-07-06 23:00:19 +00001534 TargetData &TD, LLVMContext *Context) {
Chris Lattner2e729112008-12-15 21:20:32 +00001535 // Ignore no-op GEPs and bitcasts.
1536 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537
1538 // If we are dealing with a pointer global that is initialized to null and
1539 // only has one (non-null) value stored into it, then we can optimize any
1540 // users of the loaded value (often calls and loads) that would trap if the
1541 // value was null.
1542 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1543 GV->getInitializer()->isNullValue()) {
1544 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1545 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson086ea052009-07-06 01:34:54 +00001546 SOVC =
1547 Context->getConstantExprBitCast(SOVC, GV->getInitializer()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548
1549 // Optimize away any trapping uses of the loaded value.
Owen Anderson086ea052009-07-06 01:34:54 +00001550 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551 return true;
1552 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson086ea052009-07-06 01:34:54 +00001553 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattner78e568b2008-12-15 21:02:25 +00001554 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001555 }
1556 }
1557
1558 return false;
1559}
1560
Chris Lattnerece46db2008-01-14 01:17:44 +00001561/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1562/// two values ever stored into GV are its initializer and OtherVal. See if we
1563/// can shrink the global into a boolean and select between the two values
1564/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson086ea052009-07-06 01:34:54 +00001565static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
Owen Anderson5349f052009-07-06 23:00:19 +00001566 LLVMContext *Context) {
Chris Lattnerece46db2008-01-14 01:17:44 +00001567 const Type *GVElType = GV->getType()->getElementType();
1568
1569 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001570 // an FP value, pointer or vector, don't do this optimization because a select
1571 // between them is very expensive and unlikely to lead to later
1572 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1573 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattnerece46db2008-01-14 01:17:44 +00001574 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001575 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattnerece46db2008-01-14 01:17:44 +00001576 return false;
1577
1578 // Walk the use list of the global seeing if all the uses are load or store.
1579 // If there is anything else, bail out.
1580 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel9b951552009-03-06 01:39:36 +00001581 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattnerece46db2008-01-14 01:17:44 +00001582 return false;
1583
1584 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1585
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001586 // Create the new global, initializing it to false.
Owen Andersone0f136d2009-07-08 01:26:06 +00001587 GlobalVariable *NewGV = new GlobalVariable(*Context, Type::Int1Ty, false,
Owen Anderson086ea052009-07-06 01:34:54 +00001588 GlobalValue::InternalLinkage, Context->getConstantIntFalse(),
Nick Lewycky74e96b72009-05-03 03:49:08 +00001589 GV->getName()+".b",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001590 (Module *)NULL,
1591 GV->isThreadLocal());
1592 GV->getParent()->getGlobalList().insert(GV, NewGV);
1593
1594 Constant *InitVal = GV->getInitializer();
1595 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1596
1597 // If initialized to zero and storing one into the global, we can use a cast
1598 // instead of a select to synthesize the desired value.
1599 bool IsOneZero = false;
1600 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1601 IsOneZero = InitVal->isNullValue() && CI->isOne();
1602
1603 while (!GV->use_empty()) {
Devang Patel9b951552009-03-06 01:39:36 +00001604 Instruction *UI = cast<Instruction>(GV->use_back());
1605 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 // Change the store into a boolean store.
1607 bool StoringOther = SI->getOperand(0) == OtherVal;
1608 // Only do this if we weren't storing a loaded value.
1609 Value *StoreVal;
1610 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson086ea052009-07-06 01:34:54 +00001611 StoreVal = Context->getConstantInt(Type::Int1Ty, StoringOther);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612 else {
1613 // Otherwise, we are storing a previously loaded copy. To do this,
1614 // change the copy from copying the original value to just copying the
1615 // bool.
1616 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1617
1618 // If we're already replaced the input, StoredVal will be a cast or
1619 // select instruction. If not, it will be a load of the original
1620 // global.
1621 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1622 assert(LI->getOperand(0) == GV && "Not a copy!");
1623 // Insert a new load, to preserve the saved value.
1624 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1625 } else {
1626 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1627 "This is not a form that we understand!");
1628 StoreVal = StoredVal->getOperand(0);
1629 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1630 }
1631 }
1632 new StoreInst(StoreVal, NewGV, SI);
Devang Patel9b951552009-03-06 01:39:36 +00001633 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634 // Change the load into a load of bool then a select.
Devang Patel9b951552009-03-06 01:39:36 +00001635 LoadInst *LI = cast<LoadInst>(UI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1637 Value *NSI;
1638 if (IsOneZero)
1639 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1640 else
Gabor Greifd6da1d02008-04-06 20:25:17 +00001641 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642 NSI->takeName(LI);
1643 LI->replaceAllUsesWith(NSI);
Devang Patel9b951552009-03-06 01:39:36 +00001644 }
1645 UI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646 }
1647
1648 GV->eraseFromParent();
Chris Lattnerece46db2008-01-14 01:17:44 +00001649 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650}
1651
1652
1653/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1654/// it if possible. If we make a change, return true.
1655bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1656 Module::global_iterator &GVI) {
Chris Lattner4cd08c22008-12-16 07:34:30 +00001657 SmallPtrSet<PHINode*, 16> PHIUsers;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001658 GlobalStatus GS;
1659 GV->removeDeadConstantUsers();
1660
1661 if (GV->use_empty()) {
1662 DOUT << "GLOBAL DEAD: " << *GV;
1663 GV->eraseFromParent();
1664 ++NumDeleted;
1665 return true;
1666 }
1667
1668 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1669#if 0
1670 cerr << "Global: " << *GV;
1671 cerr << " isLoaded = " << GS.isLoaded << "\n";
1672 cerr << " StoredType = ";
1673 switch (GS.StoredType) {
1674 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1675 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1676 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1677 case GlobalStatus::isStored: cerr << "stored\n"; break;
1678 }
1679 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1680 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1681 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1682 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1683 << "\n";
1684 cerr << " HasMultipleAccessingFunctions = "
1685 << GS.HasMultipleAccessingFunctions << "\n";
1686 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 cerr << "\n";
1688#endif
1689
1690 // If this is a first class global and has only one accessing function
1691 // and this function is main (which we know is not recursive we can make
1692 // this global a local variable) we replace the global with a local alloca
1693 // in this function.
1694 //
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001695 // NOTE: It doesn't make sense to promote non single-value types since we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696 // are just replacing static memory to stack memory.
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001697 //
1698 // If the global is in different address space, don't bring it to stack.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001699 if (!GS.HasMultipleAccessingFunctions &&
1700 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001701 GV->getType()->getElementType()->isSingleValueType() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001703 GS.AccessingFunction->hasExternalLinkage() &&
1704 GV->getType()->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 DOUT << "LOCALIZING GLOBAL: " << *GV;
1706 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1707 const Type* ElemTy = GV->getType()->getElementType();
1708 // FIXME: Pass Global's alignment when globals have alignment
1709 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1710 if (!isa<UndefValue>(GV->getInitializer()))
1711 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1712
1713 GV->replaceAllUsesWith(Alloca);
1714 GV->eraseFromParent();
1715 ++NumLocalized;
1716 return true;
1717 }
1718
1719 // If the global is never loaded (but may be stored to), it is dead.
1720 // Delete it now.
1721 if (!GS.isLoaded) {
1722 DOUT << "GLOBAL NEVER LOADED: " << *GV;
1723
1724 // Delete any stores we can find to the global. We may not be able to
1725 // make it completely dead though.
Owen Andersond4d90a02009-07-06 18:42:36 +00001726 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1727 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728
1729 // If the global is dead now, delete it.
1730 if (GV->use_empty()) {
1731 GV->eraseFromParent();
1732 ++NumDeleted;
1733 Changed = true;
1734 }
1735 return Changed;
1736
1737 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1738 DOUT << "MARKING CONSTANT: " << *GV;
1739 GV->setConstant(true);
1740
1741 // Clean up any obviously simplifiable users now.
Owen Andersond4d90a02009-07-06 18:42:36 +00001742 CleanupConstantGlobalUsers(GV, GV->getInitializer(), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001743
1744 // If the global is dead now, just nuke it.
1745 if (GV->use_empty()) {
1746 DOUT << " *** Marking constant allowed us to simplify "
1747 << "all users and delete global!\n";
1748 GV->eraseFromParent();
1749 ++NumDeleted;
1750 }
1751
1752 ++NumMarked;
1753 return true;
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001754 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner20846272008-04-26 07:40:11 +00001755 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
Owen Anderson086ea052009-07-06 01:34:54 +00001756 getAnalysis<TargetData>(),
1757 Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758 GVI = FirstNewGV; // Don't skip the newly produced globals!
1759 return true;
1760 }
1761 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1762 // If the initial value for the global was an undef value, and if only
1763 // one other value was stored into it, we can just change the
Duncan Sands25464152009-01-13 13:48:44 +00001764 // initializer to be the stored value, then delete all stores to the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765 // global. This allows us to mark it constant.
1766 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1767 if (isa<UndefValue>(GV->getInitializer())) {
1768 // Change the initial value here.
1769 GV->setInitializer(SOVConstant);
1770
1771 // Clean up any obviously simplifiable users now.
Owen Andersond4d90a02009-07-06 18:42:36 +00001772 CleanupConstantGlobalUsers(GV, GV->getInitializer(), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773
1774 if (GV->use_empty()) {
1775 DOUT << " *** Substituting initializer allowed us to "
1776 << "simplify all users and delete global!\n";
1777 GV->eraseFromParent();
1778 ++NumDeleted;
1779 } else {
1780 GVI = GV;
1781 }
1782 ++NumSubstitute;
1783 return true;
1784 }
1785
1786 // Try to optimize globals based on the knowledge that only one value
1787 // (besides its initializer) is ever stored to the global.
1788 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Owen Anderson086ea052009-07-06 01:34:54 +00001789 getAnalysis<TargetData>(), Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001790 return true;
1791
1792 // Otherwise, if the global was not a boolean, we can shrink it to be a
1793 // boolean.
1794 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Anderson086ea052009-07-06 01:34:54 +00001795 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 ++NumShrunkToBool;
1797 return true;
1798 }
1799 }
1800 }
1801 return false;
1802}
1803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1805/// function, changing them to FastCC.
1806static void ChangeCalleesToFastCall(Function *F) {
1807 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001808 CallSite User(cast<Instruction>(*UI));
1809 User.setCallingConv(CallingConv::Fast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 }
1811}
1812
Devang Pateld222f862008-09-25 21:00:45 +00001813static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner1c8733e2008-03-12 17:45:29 +00001814 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Pateld222f862008-09-25 21:00:45 +00001815 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands551ec902008-02-18 17:32:13 +00001816 continue;
1817
Duncan Sands551ec902008-02-18 17:32:13 +00001818 // There can be only one.
Devang Pateld222f862008-09-25 21:00:45 +00001819 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001820 }
1821
1822 return Attrs;
1823}
1824
1825static void RemoveNestAttribute(Function *F) {
Devang Pateld222f862008-09-25 21:00:45 +00001826 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001827 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001828 CallSite User(cast<Instruction>(*UI));
Devang Pateld222f862008-09-25 21:00:45 +00001829 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001830 }
1831}
1832
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001833bool GlobalOpt::OptimizeFunctions(Module &M) {
1834 bool Changed = false;
1835 // Optimize functions.
1836 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1837 Function *F = FI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001838 // Functions without names cannot be referenced outside this module.
1839 if (!F->hasName() && !F->isDeclaration())
1840 F->setLinkage(GlobalValue::InternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001841 F->removeDeadConstantUsers();
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001842 if (F->use_empty() && (F->hasLocalLinkage() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001843 F->hasLinkOnceLinkage())) {
1844 M.getFunctionList().erase(F);
1845 Changed = true;
1846 ++NumFnDeleted;
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001847 } else if (F->hasLocalLinkage()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001848 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad1379d592009-06-10 08:41:11 +00001849 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001850 // If this function has C calling conventions, is not a varargs
1851 // function, and is only called directly, promote it to use the Fast
1852 // calling convention.
1853 F->setCallingConv(CallingConv::Fast);
1854 ChangeCalleesToFastCall(F);
1855 ++NumFastCallFns;
1856 Changed = true;
1857 }
1858
Devang Pateld222f862008-09-25 21:00:45 +00001859 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad1379d592009-06-10 08:41:11 +00001860 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001861 // The function is not used by a trampoline intrinsic, so it is safe
1862 // to remove the 'nest' attribute.
1863 RemoveNestAttribute(F);
1864 ++NumNestRemoved;
1865 Changed = true;
1866 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 }
1868 }
1869 return Changed;
1870}
1871
1872bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1873 bool Changed = false;
1874 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1875 GVI != E; ) {
1876 GlobalVariable *GV = GVI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001877 // Global variables without names cannot be referenced outside this module.
1878 if (!GV->hasName() && !GV->isDeclaration())
1879 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001880 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001881 GV->hasInitializer())
1882 Changed |= ProcessInternalGlobal(GV, GVI);
1883 }
1884 return Changed;
1885}
1886
1887/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1888/// initializers have an init priority of 65535.
1889GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1890 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1891 I != E; ++I)
1892 if (I->getName() == "llvm.global_ctors") {
1893 // Found it, verify it's an array of { int, void()* }.
1894 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1895 if (!ATy) return 0;
1896 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1897 if (!STy || STy->getNumElements() != 2 ||
1898 STy->getElementType(0) != Type::Int32Ty) return 0;
1899 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1900 if (!PFTy) return 0;
1901 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1902 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1903 FTy->getNumParams() != 0)
1904 return 0;
1905
1906 // Verify that the initializer is simple enough for us to handle.
1907 if (!I->hasInitializer()) return 0;
1908 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1909 if (!CA) return 0;
Gabor Greif20f03f52008-05-29 01:59:18 +00001910 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1911 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001912 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1913 continue;
1914
1915 // Must have a function or null ptr.
1916 if (!isa<Function>(CS->getOperand(1)))
1917 return 0;
1918
1919 // Init priority must be standard.
1920 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1921 if (!CI || CI->getZExtValue() != 65535)
1922 return 0;
1923 } else {
1924 return 0;
1925 }
1926
1927 return I;
1928 }
1929 return 0;
1930}
1931
1932/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1933/// return a list of the functions and null terminator as a vector.
1934static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1935 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1936 std::vector<Function*> Result;
1937 Result.reserve(CA->getNumOperands());
Gabor Greif20f03f52008-05-29 01:59:18 +00001938 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1939 ConstantStruct *CS = cast<ConstantStruct>(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001940 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1941 }
1942 return Result;
1943}
1944
1945/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1946/// specified array, returning the new global to use.
1947static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson086ea052009-07-06 01:34:54 +00001948 const std::vector<Function*> &Ctors,
Owen Anderson5349f052009-07-06 23:00:19 +00001949 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001950 // If we made a change, reassemble the initializer list.
1951 std::vector<Constant*> CSVals;
Owen Anderson086ea052009-07-06 01:34:54 +00001952 CSVals.push_back(Context->getConstantInt(Type::Int32Ty, 65535));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001953 CSVals.push_back(0);
1954
1955 // Create the new init list.
1956 std::vector<Constant*> CAList;
1957 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1958 if (Ctors[i]) {
1959 CSVals[1] = Ctors[i];
1960 } else {
Owen Anderson086ea052009-07-06 01:34:54 +00001961 const Type *FTy = Context->getFunctionType(Type::VoidTy, false);
1962 const PointerType *PFTy = Context->getPointerTypeUnqual(FTy);
1963 CSVals[1] = Context->getNullValue(PFTy);
1964 CSVals[0] = Context->getConstantInt(Type::Int32Ty, 2147483647);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965 }
Owen Anderson086ea052009-07-06 01:34:54 +00001966 CAList.push_back(Context->getConstantStruct(CSVals));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001967 }
1968
1969 // Create the array initializer.
1970 const Type *StructTy =
1971 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson086ea052009-07-06 01:34:54 +00001972 Constant *CA = Context->getConstantArray(ArrayType::get(StructTy,
1973 CAList.size()), CAList);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974
1975 // If we didn't change the number of elements, don't create a new GV.
1976 if (CA->getType() == GCL->getInitializer()->getType()) {
1977 GCL->setInitializer(CA);
1978 return GCL;
1979 }
1980
1981 // Create the new global and insert it next to the existing list.
Owen Andersone0f136d2009-07-08 01:26:06 +00001982 GlobalVariable *NGV = new GlobalVariable(*Context, CA->getType(),
1983 GCL->isConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 GCL->getLinkage(), CA, "",
1985 (Module *)NULL,
1986 GCL->isThreadLocal());
1987 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1988 NGV->takeName(GCL);
1989
1990 // Nuke the old list, replacing any uses with the new one.
1991 if (!GCL->use_empty()) {
1992 Constant *V = NGV;
1993 if (V->getType() != GCL->getType())
Owen Anderson086ea052009-07-06 01:34:54 +00001994 V = Context->getConstantExprBitCast(V, GCL->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995 GCL->replaceAllUsesWith(V);
1996 }
1997 GCL->eraseFromParent();
1998
1999 if (Ctors.size())
2000 return NGV;
2001 else
2002 return 0;
2003}
2004
2005
Chris Lattner4cd08c22008-12-16 07:34:30 +00002006static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002007 Value *V) {
2008 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2009 Constant *R = ComputedValues[V];
2010 assert(R && "Reference to an uncomputed value!");
2011 return R;
2012}
2013
2014/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2015/// enough for us to understand. In particular, if it is a cast of something,
2016/// we punt. We basically just support direct accesses to globals and GEP's of
2017/// globals. This should be kept up to date with CommitValueTo.
Owen Anderson5349f052009-07-06 23:00:19 +00002018static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002019 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002020 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2022 return !GV->isDeclaration(); // reject external globals.
2023 }
2024 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2025 // Handle a constantexpr gep.
2026 if (CE->getOpcode() == Instruction::GetElementPtr &&
2027 isa<GlobalVariable>(CE->getOperand(0))) {
2028 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002029 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2031 return GV->hasInitializer() &&
Owen Andersond4d90a02009-07-06 18:42:36 +00002032 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2033 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002034 }
2035 return false;
2036}
2037
2038/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2039/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2040/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2041static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson086ea052009-07-06 01:34:54 +00002042 ConstantExpr *Addr, unsigned OpNo,
Owen Anderson5349f052009-07-06 23:00:19 +00002043 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044 // Base case of the recursion.
2045 if (OpNo == Addr->getNumOperands()) {
2046 assert(Val->getType() == Init->getType() && "Type mismatch!");
2047 return Val;
2048 }
2049
2050 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2051 std::vector<Constant*> Elts;
2052
2053 // Break up the constant into its elements.
2054 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002055 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2056 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057 } else if (isa<ConstantAggregateZero>(Init)) {
2058 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson086ea052009-07-06 01:34:54 +00002059 Elts.push_back(Context->getNullValue(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060 } else if (isa<UndefValue>(Init)) {
2061 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson086ea052009-07-06 01:34:54 +00002062 Elts.push_back(Context->getUndef(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 } else {
2064 assert(0 && "This code is out of sync with "
2065 " ConstantFoldLoadThroughGEPConstantExpr");
2066 }
2067
2068 // Replace the element that we are supposed to.
2069 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2070 unsigned Idx = CU->getZExtValue();
2071 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson086ea052009-07-06 01:34:54 +00002072 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002073
2074 // Return the modified struct.
Owen Anderson086ea052009-07-06 01:34:54 +00002075 return Context->getConstantStruct(&Elts[0], Elts.size(), STy->isPacked());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076 } else {
2077 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2078 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2079
2080 // Break up the array into elements.
2081 std::vector<Constant*> Elts;
2082 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002083 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2084 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002086 Constant *Elt = Context->getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002087 Elts.assign(ATy->getNumElements(), Elt);
2088 } else if (isa<UndefValue>(Init)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002089 Constant *Elt = Context->getUndef(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002090 Elts.assign(ATy->getNumElements(), Elt);
2091 } else {
2092 assert(0 && "This code is out of sync with "
2093 " ConstantFoldLoadThroughGEPConstantExpr");
2094 }
2095
2096 assert(CI->getZExtValue() < ATy->getNumElements());
2097 Elts[CI->getZExtValue()] =
Owen Anderson086ea052009-07-06 01:34:54 +00002098 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
2099 return Context->getConstantArray(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100 }
2101}
2102
2103/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2104/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson086ea052009-07-06 01:34:54 +00002105static void CommitValueTo(Constant *Val, Constant *Addr,
Owen Anderson5349f052009-07-06 23:00:19 +00002106 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2108 assert(GV->hasInitializer());
2109 GV->setInitializer(Val);
2110 return;
2111 }
2112
2113 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2114 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2115
2116 Constant *Init = GV->getInitializer();
Owen Anderson086ea052009-07-06 01:34:54 +00002117 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118 GV->setInitializer(Init);
2119}
2120
2121/// ComputeLoadResult - Return the value that would be computed by a load from
2122/// P after the stores reflected by 'memory' have been performed. If we can't
2123/// decide, return null.
2124static Constant *ComputeLoadResult(Constant *P,
Owen Andersond4d90a02009-07-06 18:42:36 +00002125 const DenseMap<Constant*, Constant*> &Memory,
Owen Anderson5349f052009-07-06 23:00:19 +00002126 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127 // If this memory location has been recently stored, use the stored value: it
2128 // is the most up-to-date.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002129 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130 if (I != Memory.end()) return I->second;
2131
2132 // Access it.
2133 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2134 if (GV->hasInitializer())
2135 return GV->getInitializer();
2136 return 0;
2137 }
2138
2139 // Handle a constantexpr getelementptr.
2140 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2141 if (CE->getOpcode() == Instruction::GetElementPtr &&
2142 isa<GlobalVariable>(CE->getOperand(0))) {
2143 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2144 if (GV->hasInitializer())
Owen Andersond4d90a02009-07-06 18:42:36 +00002145 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2146 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002147 }
2148
2149 return 0; // don't know how to evaluate.
2150}
2151
2152/// EvaluateFunction - Evaluate a call to function F, returning true if
2153/// successful, false if we can't evaluate it. ActualArgs contains the formal
2154/// arguments for the function.
2155static bool EvaluateFunction(Function *F, Constant *&RetVal,
2156 const std::vector<Constant*> &ActualArgs,
2157 std::vector<Function*> &CallStack,
Chris Lattner4cd08c22008-12-16 07:34:30 +00002158 DenseMap<Constant*, Constant*> &MutatedMemory,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159 std::vector<GlobalVariable*> &AllocaTmps) {
2160 // Check to see if this function is already executing (recursion). If so,
2161 // bail out. TODO: we might want to accept limited recursion.
2162 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2163 return false;
2164
Owen Anderson5349f052009-07-06 23:00:19 +00002165 LLVMContext *Context = F->getContext();
Owen Anderson086ea052009-07-06 01:34:54 +00002166
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002167 CallStack.push_back(F);
2168
2169 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002170 DenseMap<Value*, Constant*> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002171
2172 // Initialize arguments to the incoming values specified.
2173 unsigned ArgNo = 0;
2174 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2175 ++AI, ++ArgNo)
2176 Values[AI] = ActualArgs[ArgNo];
2177
2178 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2179 /// we can only evaluate any one basic block at most once. This set keeps
2180 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002181 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002182
2183 // CurInst - The current instruction we're evaluating.
2184 BasicBlock::iterator CurInst = F->begin()->begin();
2185
2186 // This is the main evaluation loop.
2187 while (1) {
2188 Constant *InstResult = 0;
2189
2190 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2191 if (SI->isVolatile()) return false; // no volatile accesses.
2192 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Andersond4d90a02009-07-06 18:42:36 +00002193 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194 // If this is too complex for us to commit, reject it.
2195 return false;
2196 Constant *Val = getVal(Values, SI->getOperand(0));
2197 MutatedMemory[Ptr] = Val;
2198 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002199 InstResult = Context->getConstantExpr(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200 getVal(Values, BO->getOperand(0)),
2201 getVal(Values, BO->getOperand(1)));
2202 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002203 InstResult = Context->getConstantExprCompare(CI->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002204 getVal(Values, CI->getOperand(0)),
2205 getVal(Values, CI->getOperand(1)));
2206 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002207 InstResult = Context->getConstantExprCast(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002208 getVal(Values, CI->getOperand(0)),
2209 CI->getType());
2210 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002211 InstResult =
2212 Context->getConstantExprSelect(getVal(Values, SI->getOperand(0)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002213 getVal(Values, SI->getOperand(1)),
2214 getVal(Values, SI->getOperand(2)));
2215 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2216 Constant *P = getVal(Values, GEP->getOperand(0));
2217 SmallVector<Constant*, 8> GEPOps;
Gabor Greif20f03f52008-05-29 01:59:18 +00002218 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2219 i != e; ++i)
2220 GEPOps.push_back(getVal(Values, *i));
Owen Anderson086ea052009-07-06 01:34:54 +00002221 InstResult =
2222 Context->getConstantExprGetElementPtr(P, &GEPOps[0], GEPOps.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002223 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2224 if (LI->isVolatile()) return false; // no volatile accesses.
2225 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Andersond4d90a02009-07-06 18:42:36 +00002226 MutatedMemory, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002227 if (InstResult == 0) return false; // Could not evaluate load.
2228 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2229 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2230 const Type *Ty = AI->getType()->getElementType();
Owen Andersone0f136d2009-07-08 01:26:06 +00002231 AllocaTmps.push_back(new GlobalVariable(*Context, Ty, false,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002232 GlobalValue::InternalLinkage,
Owen Anderson086ea052009-07-06 01:34:54 +00002233 Context->getUndef(Ty),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002234 AI->getName()));
2235 InstResult = AllocaTmps.back();
2236 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel5b1082b2009-03-09 23:04:12 +00002237
2238 // Debug info can safely be ignored here.
2239 if (isa<DbgInfoIntrinsic>(CI)) {
2240 ++CurInst;
2241 continue;
2242 }
2243
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244 // Cannot handle inline asm.
2245 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2246
2247 // Resolve function pointers.
2248 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2249 if (!Callee) return false; // Cannot resolve.
2250
2251 std::vector<Constant*> Formals;
Gabor Greif20f03f52008-05-29 01:59:18 +00002252 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2253 i != e; ++i)
2254 Formals.push_back(getVal(Values, *i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255
2256 if (Callee->isDeclaration()) {
2257 // If this is a function we can constant fold, do it.
2258 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2259 Formals.size())) {
2260 InstResult = C;
2261 } else {
2262 return false;
2263 }
2264 } else {
2265 if (Callee->getFunctionType()->isVarArg())
2266 return false;
2267
2268 Constant *RetVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 // Execute the call, if successful, use the return value.
2270 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2271 MutatedMemory, AllocaTmps))
2272 return false;
2273 InstResult = RetVal;
2274 }
2275 } else if (isa<TerminatorInst>(CurInst)) {
2276 BasicBlock *NewBB = 0;
2277 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2278 if (BI->isUnconditional()) {
2279 NewBB = BI->getSuccessor(0);
2280 } else {
2281 ConstantInt *Cond =
2282 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2283 if (!Cond) return false; // Cannot determine.
2284
2285 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2286 }
2287 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2288 ConstantInt *Val =
2289 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2290 if (!Val) return false; // Cannot determine.
2291 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2292 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2293 if (RI->getNumOperands())
2294 RetVal = getVal(Values, RI->getOperand(0));
2295
2296 CallStack.pop_back(); // return from fn.
2297 return true; // We succeeded at evaluating this ctor!
2298 } else {
2299 // invoke, unwind, unreachable.
2300 return false; // Cannot handle this terminator.
2301 }
2302
2303 // Okay, we succeeded in evaluating this control flow. See if we have
2304 // executed the new block before. If so, we have a looping function,
2305 // which we cannot evaluate in reasonable time.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002306 if (!ExecutedBlocks.insert(NewBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 return false; // looped!
2308
2309 // Okay, we have never been in this block before. Check to see if there
2310 // are any PHI nodes. If so, evaluate them with information about where
2311 // we came from.
2312 BasicBlock *OldBB = CurInst->getParent();
2313 CurInst = NewBB->begin();
2314 PHINode *PN;
2315 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2316 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2317
2318 // Do NOT increment CurInst. We know that the terminator had no value.
2319 continue;
2320 } else {
2321 // Did not know how to evaluate this!
2322 return false;
2323 }
2324
2325 if (!CurInst->use_empty())
2326 Values[CurInst] = InstResult;
2327
2328 // Advance program counter.
2329 ++CurInst;
2330 }
2331}
2332
2333/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2334/// we can. Return true if we can, false otherwise.
2335static bool EvaluateStaticConstructor(Function *F) {
2336 /// MutatedMemory - For each store we execute, we update this map. Loads
2337 /// check this to get the most up-to-date value. If evaluation is successful,
2338 /// this state is committed to the process.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002339 DenseMap<Constant*, Constant*> MutatedMemory;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002340
2341 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2342 /// to represent its body. This vector is needed so we can delete the
2343 /// temporary globals when we are done.
2344 std::vector<GlobalVariable*> AllocaTmps;
2345
2346 /// CallStack - This is used to detect recursion. In pathological situations
2347 /// we could hit exponential behavior, but at least there is nothing
2348 /// unbounded.
2349 std::vector<Function*> CallStack;
2350
2351 // Call the function.
2352 Constant *RetValDummy;
2353 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2354 CallStack, MutatedMemory, AllocaTmps);
2355 if (EvalSuccess) {
2356 // We succeeded at evaluation: commit the result.
2357 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2358 << F->getName() << "' to " << MutatedMemory.size()
2359 << " stores.\n";
Chris Lattner4cd08c22008-12-16 07:34:30 +00002360 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002361 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson086ea052009-07-06 01:34:54 +00002362 CommitValueTo(I->second, I->first, F->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002363 }
2364
2365 // At this point, we are done interpreting. If we created any 'alloca'
2366 // temporaries, release them now.
2367 while (!AllocaTmps.empty()) {
2368 GlobalVariable *Tmp = AllocaTmps.back();
2369 AllocaTmps.pop_back();
2370
2371 // If there are still users of the alloca, the program is doing something
2372 // silly, e.g. storing the address of the alloca somewhere and using it
2373 // later. Since this is undefined, we'll just make it be null.
2374 if (!Tmp->use_empty())
Owen Anderson086ea052009-07-06 01:34:54 +00002375 Tmp->replaceAllUsesWith(F->getContext()->getNullValue(Tmp->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002376 delete Tmp;
2377 }
2378
2379 return EvalSuccess;
2380}
2381
2382
2383
2384/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2385/// Return true if anything changed.
2386bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2387 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2388 bool MadeChange = false;
2389 if (Ctors.empty()) return false;
2390
2391 // Loop over global ctors, optimizing them when we can.
2392 for (unsigned i = 0; i != Ctors.size(); ++i) {
2393 Function *F = Ctors[i];
2394 // Found a null terminator in the middle of the list, prune off the rest of
2395 // the list.
2396 if (F == 0) {
2397 if (i != Ctors.size()-1) {
2398 Ctors.resize(i+1);
2399 MadeChange = true;
2400 }
2401 break;
2402 }
2403
2404 // We cannot simplify external ctor functions.
2405 if (F->empty()) continue;
2406
2407 // If we can evaluate the ctor at compile time, do.
2408 if (EvaluateStaticConstructor(F)) {
2409 Ctors.erase(Ctors.begin()+i);
2410 MadeChange = true;
2411 --i;
2412 ++NumCtorsEvaluated;
2413 continue;
2414 }
2415 }
2416
2417 if (!MadeChange) return false;
2418
Owen Anderson086ea052009-07-06 01:34:54 +00002419 GCL = InstallGlobalCtors(GCL, Ctors, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002420 return true;
2421}
2422
Duncan Sands0c7b6332009-03-06 10:21:56 +00002423bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002424 bool Changed = false;
2425
Duncan Sands0f064b92009-01-07 20:01:06 +00002426 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002427 I != E;) {
2428 Module::alias_iterator J = I++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00002429 // Aliases without names cannot be referenced outside this module.
2430 if (!J->hasName() && !J->isDeclaration())
2431 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002432 // If the aliasee may change at link time, nothing can be done - bail out.
2433 if (J->mayBeOverridden())
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002434 continue;
2435
Duncan Sandse7f431f2009-02-15 09:56:08 +00002436 Constant *Aliasee = J->getAliasee();
2437 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7531ad62009-02-18 17:55:38 +00002438 Target->removeDeadConstantUsers();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002439 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2440
2441 // Make all users of the alias use the aliasee instead.
2442 if (!J->use_empty()) {
2443 J->replaceAllUsesWith(Aliasee);
2444 ++NumAliasesResolved;
2445 Changed = true;
2446 }
2447
2448 // If the aliasee has internal linkage, give it the name and linkage
2449 // of the alias, and delete the alias. This turns:
2450 // define internal ... @f(...)
2451 // @a = alias ... @f
2452 // into:
2453 // define ... @a(...)
Duncan Sands8f723612009-02-17 17:50:04 +00002454 if (!Target->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002455 continue;
2456
2457 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands8f723612009-02-17 17:50:04 +00002458 if (J->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002459 continue;
2460
Duncan Sandse10858a2009-02-15 11:54:49 +00002461 // Do not perform the transform if multiple aliases potentially target the
2462 // aliasee. This check also ensures that it is safe to replace the section
2463 // and other attributes of the aliasee with those of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002464 if (!hasOneUse)
2465 continue;
2466
Duncan Sandse10858a2009-02-15 11:54:49 +00002467 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002468 Target->takeName(J);
2469 Target->setLinkage(J->getLinkage());
Duncan Sandse10858a2009-02-15 11:54:49 +00002470 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002471
2472 // Delete the alias.
2473 M.getAliasList().erase(J);
2474 ++NumAliasesRemoved;
2475 Changed = true;
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002476 }
2477
2478 return Changed;
2479}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002480
2481bool GlobalOpt::runOnModule(Module &M) {
2482 bool Changed = false;
2483
2484 // Try to find the llvm.globalctors list.
2485 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2486
2487 bool LocalChange = true;
2488 while (LocalChange) {
2489 LocalChange = false;
2490
2491 // Delete functions that are trivially dead, ccc -> fastcc
2492 LocalChange |= OptimizeFunctions(M);
2493
2494 // Optimize global_ctors list.
2495 if (GlobalCtors)
2496 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2497
2498 // Optimize non-address-taken globals.
2499 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002500
2501 // Resolve aliases, when possible.
Duncan Sands0c7b6332009-03-06 10:21:56 +00002502 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002503 Changed |= LocalChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 }
2505
2506 // TODO: Move all global ctors functions to the end of the module for code
2507 // layout.
2508
2509 return Changed;
2510}