blob: 0c03676f7d7a9ccac2097f649c9839c3a8168c46 [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,
249 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,
286 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,
468 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?");
493 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
494 GlobalVariable::InternalLinkage,
495 In, GV->getName()+"."+utostr(i),
496 (Module *)NULL,
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000497 GV->isThreadLocal(),
498 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499 Globals.insert(GV, NGV);
500 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000501
502 // Calculate the known alignment of the field. If the original aggregate
503 // had 256 byte alignment for example, something might depend on that:
504 // propagate info to each field.
505 uint64_t FieldOffset = Layout.getElementOffset(i);
506 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
507 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
508 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 }
510 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
511 unsigned NumElements = 0;
512 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
513 NumElements = ATy->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 else
Chris Lattner20846272008-04-26 07:40:11 +0000515 NumElements = cast<VectorType>(STy)->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516
517 if (NumElements > 16 && GV->hasNUsesOrMore(16))
518 return 0; // It's not worth it.
519 NewGlobals.reserve(NumElements);
Chris Lattner20846272008-04-26 07:40:11 +0000520
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000521 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
Chris Lattner20846272008-04-26 07:40:11 +0000522 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 for (unsigned i = 0, e = NumElements; i != e; ++i) {
524 Constant *In = getAggregateConstantElement(Init,
Owen Anderson086ea052009-07-06 01:34:54 +0000525 Context->getConstantInt(Type::Int32Ty, i),
526 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 assert(In && "Couldn't get element of initializer?");
528
529 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
530 GlobalVariable::InternalLinkage,
531 In, GV->getName()+"."+utostr(i),
532 (Module *)NULL,
Matthijs Kooijman36693bb2008-07-17 11:59:53 +0000533 GV->isThreadLocal(),
534 GV->getType()->getAddressSpace());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 Globals.insert(GV, NGV);
536 NewGlobals.push_back(NGV);
Chris Lattner20846272008-04-26 07:40:11 +0000537
538 // Calculate the known alignment of the field. If the original aggregate
539 // had 256 byte alignment for example, something might depend on that:
540 // propagate info to each field.
541 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
542 if (NewAlign > EltAlign)
543 NGV->setAlignment(NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 }
545 }
546
547 if (NewGlobals.empty())
548 return 0;
549
550 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
551
Owen Anderson086ea052009-07-06 01:34:54 +0000552 Constant *NullInt = Context->getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553
554 // Loop over all of the uses of the global, replacing the constantexpr geps,
555 // with smaller constantexpr geps or direct references.
556 while (!GV->use_empty()) {
557 User *GEP = GV->use_back();
558 assert(((isa<ConstantExpr>(GEP) &&
559 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
560 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
561
562 // Ignore the 1th operand, which has to be zero or else the program is quite
563 // broken (undefined). Get the 2nd operand, which is the structure or array
564 // index.
565 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
566 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
567
568 Value *NewPtr = NewGlobals[Val];
569
570 // Form a shorter GEP if needed.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000571 if (GEP->getNumOperands() > 3) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
573 SmallVector<Constant*, 8> Idxs;
574 Idxs.push_back(NullInt);
575 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
576 Idxs.push_back(CE->getOperand(i));
Owen Anderson086ea052009-07-06 01:34:54 +0000577 NewPtr = Context->getConstantExprGetElementPtr(cast<Constant>(NewPtr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 &Idxs[0], Idxs.size());
579 } else {
580 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
581 SmallVector<Value*, 8> Idxs;
582 Idxs.push_back(NullInt);
583 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
584 Idxs.push_back(GEPI->getOperand(i));
Gabor Greifd6da1d02008-04-06 20:25:17 +0000585 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
586 GEPI->getName()+"."+utostr(Val), GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000588 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 GEP->replaceAllUsesWith(NewPtr);
590
591 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
592 GEPI->eraseFromParent();
593 else
594 cast<ConstantExpr>(GEP)->destroyConstant();
595 }
596
597 // Delete the old global, now that it is dead.
598 Globals.erase(GV);
599 ++NumSRA;
600
601 // Loop over the new globals array deleting any globals that are obviously
602 // dead. This can arise due to scalarization of a structure or an array that
603 // has elements that are dead.
604 unsigned FirstGlobal = 0;
605 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
606 if (NewGlobals[i]->use_empty()) {
607 Globals.erase(NewGlobals[i]);
608 if (FirstGlobal == i) ++FirstGlobal;
609 }
610
611 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
612}
613
614/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattnerbdf77462007-09-13 16:30:19 +0000615/// value will trap if the value is dynamically null. PHIs keeps track of any
616/// phi nodes we've seen to avoid reprocessing them.
617static bool AllUsesOfValueWillTrapIfNull(Value *V,
618 SmallPtrSet<PHINode*, 8> &PHIs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
620 if (isa<LoadInst>(*UI)) {
621 // Will trap.
622 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
623 if (SI->getOperand(0) == V) {
624 //cerr << "NONTRAPPING USE: " << **UI;
625 return false; // Storing the value.
626 }
627 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
628 if (CI->getOperand(0) != V) {
629 //cerr << "NONTRAPPING USE: " << **UI;
630 return false; // Not calling the ptr
631 }
632 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
633 if (II->getOperand(0) != V) {
634 //cerr << "NONTRAPPING USE: " << **UI;
635 return false; // Not calling the ptr
636 }
Chris Lattnerbdf77462007-09-13 16:30:19 +0000637 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
638 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000640 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
641 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
642 // If we've already seen this phi node, ignore it, it has already been
643 // checked.
644 if (PHIs.insert(PN))
645 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 } else if (isa<ICmpInst>(*UI) &&
647 isa<ConstantPointerNull>(UI->getOperand(1))) {
648 // Ignore setcc X, null
649 } else {
650 //cerr << "NONTRAPPING USE: " << **UI;
651 return false;
652 }
653 return true;
654}
655
656/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
657/// from GV will trap if the loaded value is null. Note that this also permits
658/// comparisons of the loaded value against null, as a special case.
659static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
660 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
661 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattnerbdf77462007-09-13 16:30:19 +0000662 SmallPtrSet<PHINode*, 8> PHIs;
663 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 return false;
665 } else if (isa<StoreInst>(*UI)) {
666 // Ignore stores to the global.
667 } else {
668 // We don't know or understand this user, bail out.
669 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
670 return false;
671 }
672
673 return true;
674}
675
Owen Anderson086ea052009-07-06 01:34:54 +0000676static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV,
677 LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 bool Changed = false;
679 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
680 Instruction *I = cast<Instruction>(*UI++);
681 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
682 LI->setOperand(0, NewV);
683 Changed = true;
684 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
685 if (SI->getOperand(1) == V) {
686 SI->setOperand(1, NewV);
687 Changed = true;
688 }
689 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
690 if (I->getOperand(0) == V) {
691 // Calling through the pointer! Turn into a direct call, but be careful
692 // that the pointer is not also being passed as an argument.
693 I->setOperand(0, NewV);
694 Changed = true;
695 bool PassedAsArg = false;
696 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
697 if (I->getOperand(i) == V) {
698 PassedAsArg = true;
699 I->setOperand(i, NewV);
700 }
701
702 if (PassedAsArg) {
703 // Being passed as an argument also. Be careful to not invalidate UI!
704 UI = V->use_begin();
705 }
706 }
707 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
708 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Owen Anderson086ea052009-07-06 01:34:54 +0000709 Context->getConstantExprCast(CI->getOpcode(),
710 NewV, CI->getType()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711 if (CI->use_empty()) {
712 Changed = true;
713 CI->eraseFromParent();
714 }
715 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
716 // Should handle GEP here.
717 SmallVector<Constant*, 8> Idxs;
718 Idxs.reserve(GEPI->getNumOperands()-1);
Gabor Greif20f03f52008-05-29 01:59:18 +0000719 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
720 i != e; ++i)
721 if (Constant *C = dyn_cast<Constant>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 Idxs.push_back(C);
723 else
724 break;
725 if (Idxs.size() == GEPI->getNumOperands()-1)
726 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Owen Anderson086ea052009-07-06 01:34:54 +0000727 Context->getConstantExprGetElementPtr(NewV, &Idxs[0],
728 Idxs.size()), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 if (GEPI->use_empty()) {
730 Changed = true;
731 GEPI->eraseFromParent();
732 }
733 }
734 }
735
736 return Changed;
737}
738
739
740/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
741/// value stored into it. If there are uses of the loaded value that would trap
742/// if the loaded value is dynamically null, then we know that they cannot be
743/// reachable with a null optimize away the load.
Owen Anderson086ea052009-07-06 01:34:54 +0000744static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
745 LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 bool Changed = false;
747
Chris Lattner9806cc12009-01-14 00:12:58 +0000748 // Keep track of whether we are able to remove all the uses of the global
749 // other than the store that defines it.
750 bool AllNonStoreUsesGone = true;
751
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 // Replace all uses of loads with uses of uses of the stored value.
Chris Lattner9806cc12009-01-14 00:12:58 +0000753 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
754 User *GlobalUser = *GUI++;
755 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Owen Anderson086ea052009-07-06 01:34:54 +0000756 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV, Context);
Chris Lattner9806cc12009-01-14 00:12:58 +0000757 // If we were able to delete all uses of the loads
758 if (LI->use_empty()) {
759 LI->eraseFromParent();
760 Changed = true;
761 } else {
762 AllNonStoreUsesGone = false;
763 }
764 } else if (isa<StoreInst>(GlobalUser)) {
765 // Ignore the store that stores "LV" to the global.
766 assert(GlobalUser->getOperand(1) == GV &&
767 "Must be storing *to* the global");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 } else {
Chris Lattner9806cc12009-01-14 00:12:58 +0000769 AllNonStoreUsesGone = false;
770
771 // If we get here we could have other crazy uses that are transitively
772 // loaded.
773 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
774 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 }
Chris Lattner9806cc12009-01-14 00:12:58 +0000776 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777
778 if (Changed) {
779 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
780 ++NumGlobUses;
781 }
782
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 // If we nuked all of the loads, then none of the stores are needed either,
784 // nor is the global.
Chris Lattner9806cc12009-01-14 00:12:58 +0000785 if (AllNonStoreUsesGone) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 DOUT << " *** GLOBAL NOW DEAD!\n";
Owen Andersond4d90a02009-07-06 18:42:36 +0000787 CleanupConstantGlobalUsers(GV, 0, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 if (GV->use_empty()) {
789 GV->eraseFromParent();
790 ++NumDeleted;
791 }
792 Changed = true;
793 }
794 return Changed;
795}
796
797/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
798/// instructions that are foldable.
Owen Andersond4d90a02009-07-06 18:42:36 +0000799static void ConstantPropUsersOf(Value *V, LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
801 if (Instruction *I = dyn_cast<Instruction>(*UI++))
Owen Andersond4d90a02009-07-06 18:42:36 +0000802 if (Constant *NewC = ConstantFoldInstruction(I, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 I->replaceAllUsesWith(NewC);
804
805 // Advance UI to the next non-I use to avoid invalidating it!
806 // Instructions could multiply use V.
807 while (UI != E && *UI == I)
808 ++UI;
809 I->eraseFromParent();
810 }
811}
812
813/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
814/// variable, and transforms the program as if it always contained the result of
815/// the specified malloc. Because it is always the result of the specified
816/// malloc, there is no reason to actually DO the malloc. Instead, turn the
817/// malloc into a global, and any loads of GV as uses of the new global.
818static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
Owen Anderson086ea052009-07-06 01:34:54 +0000819 MallocInst *MI,
820 LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
822 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
823
824 if (NElements->getZExtValue() != 1) {
825 // If we have an array allocation, transform it to a single element
826 // allocation to make the code below simpler.
Owen Anderson086ea052009-07-06 01:34:54 +0000827 Type *NewTy = Context->getArrayType(MI->getAllocatedType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 NElements->getZExtValue());
829 MallocInst *NewMI =
Owen Anderson086ea052009-07-06 01:34:54 +0000830 new MallocInst(NewTy, Context->getNullValue(Type::Int32Ty),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 MI->getAlignment(), MI->getName(), MI);
832 Value* Indices[2];
Owen Anderson086ea052009-07-06 01:34:54 +0000833 Indices[0] = Indices[1] = Context->getNullValue(Type::Int32Ty);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000834 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
835 NewMI->getName()+".el0", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 MI->replaceAllUsesWith(NewGEP);
837 MI->eraseFromParent();
838 MI = NewMI;
839 }
840
841 // Create the new global variable. The contents of the malloc'd memory is
842 // undefined, so initialize with an undef value.
Owen Anderson086ea052009-07-06 01:34:54 +0000843 Constant *Init = Context->getUndef(MI->getAllocatedType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
845 GlobalValue::InternalLinkage, Init,
846 GV->getName()+".body",
847 (Module *)NULL,
848 GV->isThreadLocal());
Chris Lattner20846272008-04-26 07:40:11 +0000849 // FIXME: This new global should have the alignment returned by malloc. Code
850 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
851 // this would only guarantee some lower alignment.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 GV->getParent()->getGlobalList().insert(GV, NewGV);
853
854 // Anything that used the malloc now uses the global directly.
855 MI->replaceAllUsesWith(NewGV);
856
857 Constant *RepValue = NewGV;
858 if (NewGV->getType() != GV->getType()->getElementType())
Owen Anderson086ea052009-07-06 01:34:54 +0000859 RepValue = Context->getConstantExprBitCast(RepValue,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 GV->getType()->getElementType());
861
862 // If there is a comparison against null, we will insert a global bool to
863 // keep track of whether the global was initialized yet or not.
864 GlobalVariable *InitBool =
865 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Owen Anderson086ea052009-07-06 01:34:54 +0000866 Context->getConstantIntFalse(), GV->getName()+".init",
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 (Module *)NULL, GV->isThreadLocal());
868 bool InitBoolUsed = false;
869
870 // Loop over all uses of GV, processing them in turn.
871 std::vector<StoreInst*> Stores;
872 while (!GV->use_empty())
873 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
874 while (!LI->use_empty()) {
875 Use &LoadUse = LI->use_begin().getUse();
876 if (!isa<ICmpInst>(LoadUse.getUser()))
877 LoadUse = RepValue;
878 else {
879 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
880 // Replace the cmp X, 0 with a use of the bool value.
881 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
882 InitBoolUsed = true;
883 switch (CI->getPredicate()) {
884 default: assert(0 && "Unknown ICmp Predicate!");
885 case ICmpInst::ICMP_ULT:
886 case ICmpInst::ICMP_SLT:
Owen Anderson086ea052009-07-06 01:34:54 +0000887 LV = Context->getConstantIntFalse(); // X < null -> always false
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 break;
889 case ICmpInst::ICMP_ULE:
890 case ICmpInst::ICMP_SLE:
891 case ICmpInst::ICMP_EQ:
Gabor Greifa645dd32008-05-16 19:29:10 +0000892 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 break;
894 case ICmpInst::ICMP_NE:
895 case ICmpInst::ICMP_UGE:
896 case ICmpInst::ICMP_SGE:
897 case ICmpInst::ICMP_UGT:
898 case ICmpInst::ICMP_SGT:
899 break; // no change.
900 }
901 CI->replaceAllUsesWith(LV);
902 CI->eraseFromParent();
903 }
904 }
905 LI->eraseFromParent();
906 } else {
907 StoreInst *SI = cast<StoreInst>(GV->use_back());
908 // The global is initialized when the store to it occurs.
Owen Anderson086ea052009-07-06 01:34:54 +0000909 new StoreInst(Context->getConstantIntTrue(), InitBool, SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 SI->eraseFromParent();
911 }
912
913 // If the initialization boolean was used, insert it, otherwise delete it.
914 if (!InitBoolUsed) {
915 while (!InitBool->use_empty()) // Delete initializations
916 cast<Instruction>(InitBool->use_back())->eraseFromParent();
917 delete InitBool;
918 } else
919 GV->getParent()->getGlobalList().insert(GV, InitBool);
920
921
922 // Now the GV is dead, nuke it and the malloc.
923 GV->eraseFromParent();
924 MI->eraseFromParent();
925
926 // To further other optimizations, loop over all users of NewGV and try to
927 // constant prop them. This will promote GEP instructions with constant
928 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
Owen Andersond4d90a02009-07-06 18:42:36 +0000929 ConstantPropUsersOf(NewGV, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 if (RepValue != NewGV)
Owen Andersond4d90a02009-07-06 18:42:36 +0000931 ConstantPropUsersOf(RepValue, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932
933 return NewGV;
934}
935
936/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
937/// to make sure that there are no complex uses of V. We permit simple things
938/// like dereferencing the pointer, but not storing through the address, unless
939/// it is to the specified global.
940static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnere7606f42007-09-13 16:37:20 +0000941 GlobalVariable *GV,
942 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner183b0cf2008-12-15 21:08:54 +0000943 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Jay Foadd1d6a142009-06-06 17:49:35 +0000944 Instruction *Inst = cast<Instruction>(*UI);
Chris Lattner183b0cf2008-12-15 21:08:54 +0000945
946 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
947 continue; // Fine, ignore.
948 }
949
950 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
952 return false; // Storing the pointer itself... bad.
Chris Lattner183b0cf2008-12-15 21:08:54 +0000953 continue; // Otherwise, storing through it, or storing into GV... fine.
954 }
955
956 if (isa<GetElementPtrInst>(Inst)) {
957 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000959 continue;
960 }
961
962 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
Chris Lattnere7606f42007-09-13 16:37:20 +0000963 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
964 // cycles.
965 if (PHIs.insert(PN))
Chris Lattner4bde3c42007-09-14 03:41:21 +0000966 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
967 return false;
Chris Lattner183b0cf2008-12-15 21:08:54 +0000968 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 }
Chris Lattner183b0cf2008-12-15 21:08:54 +0000970
971 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
972 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
973 return false;
974 continue;
975 }
976
977 return false;
978 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979 return true;
980}
981
982/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
983/// somewhere. Transform all uses of the allocation into loads from the
984/// global and uses of the resultant pointer. Further, delete the store into
985/// GV. This assumes that these value pass the
986/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
987static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
988 GlobalVariable *GV) {
989 while (!Alloc->use_empty()) {
Chris Lattner20eef0f2007-09-13 18:00:31 +0000990 Instruction *U = cast<Instruction>(*Alloc->use_begin());
991 Instruction *InsertPt = U;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
993 // If this is the store of the allocation into the global, remove it.
994 if (SI->getOperand(1) == GV) {
995 SI->eraseFromParent();
996 continue;
997 }
Chris Lattner20eef0f2007-09-13 18:00:31 +0000998 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
999 // Insert the load in the corresponding predecessor, not right before the
1000 // PHI.
Gabor Greif261734d2009-01-23 19:40:15 +00001001 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
Chris Lattner27ef89e2008-12-15 21:44:34 +00001002 } else if (isa<BitCastInst>(U)) {
1003 // Must be bitcast between the malloc and store to initialize the global.
1004 ReplaceUsesOfMallocWithGlobal(U, GV);
1005 U->eraseFromParent();
1006 continue;
1007 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1008 // If this is a "GEP bitcast" and the user is a store to the global, then
1009 // just process it as a bitcast.
1010 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1011 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1012 if (SI->getOperand(1) == GV) {
1013 // Must be bitcast GEP between the malloc and store to initialize
1014 // the global.
1015 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1016 GEPI->eraseFromParent();
1017 continue;
1018 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 }
Chris Lattner27ef89e2008-12-15 21:44:34 +00001020
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 // Insert a load from the global, and use it instead of the malloc.
Chris Lattner20eef0f2007-09-13 18:00:31 +00001022 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 U->replaceUsesOfWith(Alloc, NL);
1024 }
1025}
1026
Chris Lattner7f252db2008-12-16 21:24:51 +00001027/// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1028/// of a load) are simple enough to perform heap SRA on. This permits GEP's
1029/// that index through the array and struct field, icmps of null, and PHIs.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001030static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
Evan Chengb00d9282009-06-02 00:56:07 +00001031 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs,
1032 SmallPtrSet<PHINode*, 32> &LoadUsingPHIsPerLoad) {
Chris Lattner7f252db2008-12-16 21:24:51 +00001033 // We permit two users of the load: setcc comparing against the null
1034 // pointer, and a getelementptr of a specific form.
1035 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1036 Instruction *User = cast<Instruction>(*UI);
1037
1038 // Comparison against null is ok.
1039 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1040 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1041 return false;
1042 continue;
1043 }
1044
1045 // getelementptr is also ok, but only a simple form.
1046 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1047 // Must index into the array and into the struct.
1048 if (GEPI->getNumOperands() < 3)
1049 return false;
1050
1051 // Otherwise the GEP is ok.
1052 continue;
1053 }
1054
1055 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Evan Chengb00d9282009-06-02 00:56:07 +00001056 if (!LoadUsingPHIsPerLoad.insert(PN))
1057 // This means some phi nodes are dependent on each other.
1058 // Avoid infinite looping!
1059 return false;
1060 if (!LoadUsingPHIs.insert(PN))
1061 // If we have already analyzed this PHI, then it is safe.
Chris Lattner7f252db2008-12-16 21:24:51 +00001062 continue;
1063
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001064 // Make sure all uses of the PHI are simple enough to transform.
Evan Chengb00d9282009-06-02 00:56:07 +00001065 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1066 LoadUsingPHIs, LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001067 return false;
1068
1069 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 }
Chris Lattner7f252db2008-12-16 21:24:51 +00001071
1072 // Otherwise we don't know what this is, not ok.
1073 return false;
1074 }
1075
1076 return true;
1077}
1078
1079
1080/// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1081/// GV are simple enough to perform HeapSRA, return true.
1082static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1083 MallocInst *MI) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001084 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
Evan Chengb00d9282009-06-02 00:56:07 +00001085 SmallPtrSet<PHINode*, 32> LoadUsingPHIsPerLoad;
Chris Lattner7f252db2008-12-16 21:24:51 +00001086 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1087 ++UI)
Evan Chengb00d9282009-06-02 00:56:07 +00001088 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1089 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1090 LoadUsingPHIsPerLoad))
Chris Lattner7f252db2008-12-16 21:24:51 +00001091 return false;
Evan Chengb00d9282009-06-02 00:56:07 +00001092 LoadUsingPHIsPerLoad.clear();
1093 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001094
1095 // If we reach here, we know that all uses of the loads and transitive uses
1096 // (through PHI nodes) are simple enough to transform. However, we don't know
1097 // that all inputs the to the PHI nodes are in the same equivalence sets.
1098 // Check to verify that all operands of the PHIs are either PHIS that can be
1099 // transformed, loads from GV, or MI itself.
1100 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1101 E = LoadUsingPHIs.end(); I != E; ++I) {
1102 PHINode *PN = *I;
1103 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1104 Value *InVal = PN->getIncomingValue(op);
1105
1106 // PHI of the stored value itself is ok.
1107 if (InVal == MI) continue;
1108
1109 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1110 // One of the PHIs in our set is (optimistically) ok.
1111 if (LoadUsingPHIs.count(InPN))
1112 continue;
1113 return false;
1114 }
1115
1116 // Load from GV is ok.
1117 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1118 if (LI->getOperand(0) == GV)
1119 continue;
1120
1121 // UNDEF? NULL?
1122
1123 // Anything else is rejected.
1124 return false;
1125 }
1126 }
1127
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 return true;
1129}
1130
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001131static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1132 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001133 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1134 LLVMContext* Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001135 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1136
1137 if (FieldNo >= FieldVals.size())
1138 FieldVals.resize(FieldNo+1);
1139
1140 // If we already have this value, just reuse the previously scalarized
1141 // version.
1142 if (Value *FieldVal = FieldVals[FieldNo])
1143 return FieldVal;
1144
1145 // Depending on what instruction this is, we have several cases.
1146 Value *Result;
1147 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1148 // This is a scalarized version of the load from the global. Just create
1149 // a new Load of the scalarized global.
1150 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1151 InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001152 PHIsToRewrite, Context),
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001153 LI->getName()+".f" + utostr(FieldNo), LI);
1154 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1155 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1156 // field.
1157 const StructType *ST =
1158 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1159
Owen Anderson086ea052009-07-06 01:34:54 +00001160 Result =
1161 PHINode::Create(Context->getPointerTypeUnqual(ST->getElementType(FieldNo)),
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001162 PN->getName()+".f"+utostr(FieldNo), PN);
1163 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1164 } else {
1165 assert(0 && "Unknown usable value");
1166 Result = 0;
1167 }
1168
1169 return FieldVals[FieldNo] = Result;
Chris Lattner20eef0f2007-09-13 18:00:31 +00001170}
1171
Chris Lattneraf82fb82007-09-13 17:29:05 +00001172/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1173/// the load, rewrite the derived value to use the HeapSRoA'd load.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001174static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1175 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001176 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1177 LLVMContext* Context) {
Chris Lattneraf82fb82007-09-13 17:29:05 +00001178 // If this is a comparison against null, handle it.
1179 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1180 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1181 // If we have a setcc of the loaded pointer, we can use a setcc of any
1182 // field.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001183 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
Owen Anderson086ea052009-07-06 01:34:54 +00001184 InsertedScalarizedValues, PHIsToRewrite,
1185 Context);
Chris Lattneraf82fb82007-09-13 17:29:05 +00001186
1187 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
Owen Anderson086ea052009-07-06 01:34:54 +00001188 Context->getNullValue(NPtr->getType()),
Chris Lattneraf82fb82007-09-13 17:29:05 +00001189 SCI->getName(), SCI);
1190 SCI->replaceAllUsesWith(New);
1191 SCI->eraseFromParent();
1192 return;
1193 }
1194
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001195 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
Chris Lattner20eef0f2007-09-13 18:00:31 +00001196 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1197 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1198 && "Unexpected GEPI!");
Chris Lattneraf82fb82007-09-13 17:29:05 +00001199
Chris Lattner20eef0f2007-09-13 18:00:31 +00001200 // Load the pointer for this field.
1201 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001202 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
Owen Anderson086ea052009-07-06 01:34:54 +00001203 InsertedScalarizedValues, PHIsToRewrite,
1204 Context);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001205
1206 // Create the new GEP idx vector.
1207 SmallVector<Value*, 8> GEPIdx;
1208 GEPIdx.push_back(GEPI->getOperand(1));
1209 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1210
Gabor Greifb91ea9d2008-05-15 10:04:30 +00001211 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1212 GEPIdx.begin(), GEPIdx.end(),
Gabor Greifd6da1d02008-04-06 20:25:17 +00001213 GEPI->getName(), GEPI);
Chris Lattner20eef0f2007-09-13 18:00:31 +00001214 GEPI->replaceAllUsesWith(NGEPI);
1215 GEPI->eraseFromParent();
1216 return;
1217 }
Chris Lattnereefff982007-09-13 21:31:36 +00001218
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001219 // Recursively transform the users of PHI nodes. This will lazily create the
1220 // PHIs that are needed for individual elements. Keep track of what PHIs we
1221 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1222 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1223 // already been seen first by another load, so its uses have already been
1224 // processed.
1225 PHINode *PN = cast<PHINode>(LoadUser);
1226 bool Inserted;
1227 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1228 tie(InsertPos, Inserted) =
1229 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1230 if (!Inserted) return;
Chris Lattnereefff982007-09-13 21:31:36 +00001231
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001232 // If this is the first time we've seen this PHI, recursively process all
1233 // users.
Chris Lattnera5e124b2008-12-17 05:42:08 +00001234 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1235 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001236 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1237 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001238 }
Chris Lattneraf82fb82007-09-13 17:29:05 +00001239}
1240
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1242/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1243/// use FieldGlobals instead. All uses of loaded values satisfy
Chris Lattner7f252db2008-12-16 21:24:51 +00001244/// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattneraf82fb82007-09-13 17:29:05 +00001245static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001246 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001247 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite,
1248 LLVMContext* Context) {
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001249 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
Chris Lattnera5e124b2008-12-17 05:42:08 +00001250 UI != E; ) {
1251 Instruction *User = cast<Instruction>(*UI++);
Owen Anderson086ea052009-07-06 01:34:54 +00001252 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite,
1253 Context);
Chris Lattnera5e124b2008-12-17 05:42:08 +00001254 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001255
1256 if (Load->use_empty()) {
1257 Load->eraseFromParent();
1258 InsertedScalarizedValues.erase(Load);
1259 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260}
1261
1262/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1263/// it up into multiple allocations of arrays of the fields.
Owen Anderson086ea052009-07-06 01:34:54 +00001264static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI,
1265 LLVMContext* Context){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
1267 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1268
1269 // There is guaranteed to be at least one use of the malloc (storing
1270 // it into GV). If there are other uses, change them to be uses of
1271 // the global to simplify later code. This also deletes the store
1272 // into GV.
1273 ReplaceUsesOfMallocWithGlobal(MI, GV);
1274
1275 // Okay, at this point, there are no users of the malloc. Insert N
1276 // new mallocs at the same place as MI, and N globals.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001277 std::vector<Value*> FieldGlobals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 std::vector<MallocInst*> FieldMallocs;
1279
1280 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1281 const Type *FieldTy = STy->getElementType(FieldNo);
Owen Anderson086ea052009-07-06 01:34:54 +00001282 const Type *PFieldTy = Context->getPointerTypeUnqual(FieldTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283
1284 GlobalVariable *NGV =
1285 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
Owen Anderson086ea052009-07-06 01:34:54 +00001286 Context->getNullValue(PFieldTy),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 GV->getName() + ".f" + utostr(FieldNo), GV,
1288 GV->isThreadLocal());
1289 FieldGlobals.push_back(NGV);
1290
1291 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1292 MI->getName() + ".f" + utostr(FieldNo),MI);
1293 FieldMallocs.push_back(NMI);
1294 new StoreInst(NMI, NGV, MI);
1295 }
1296
1297 // The tricky aspect of this transformation is handling the case when malloc
1298 // fails. In the original code, malloc failing would set the result pointer
1299 // of malloc to null. In this case, some mallocs could succeed and others
1300 // could fail. As such, we emit code that looks like this:
1301 // F0 = malloc(field0)
1302 // F1 = malloc(field1)
1303 // F2 = malloc(field2)
1304 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1305 // if (F0) { free(F0); F0 = 0; }
1306 // if (F1) { free(F1); F1 = 0; }
1307 // if (F2) { free(F2); F2 = 0; }
1308 // }
1309 Value *RunningOr = 0;
1310 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1311 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Owen Anderson086ea052009-07-06 01:34:54 +00001312 Context->getNullValue(FieldMallocs[i]->getType()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 "isnull", MI);
1314 if (!RunningOr)
1315 RunningOr = Cond; // First seteq
1316 else
Gabor Greifa645dd32008-05-16 19:29:10 +00001317 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 }
1319
1320 // Split the basic block at the old malloc.
1321 BasicBlock *OrigBB = MI->getParent();
1322 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1323
1324 // Create the block to check the first condition. Put all these blocks at the
1325 // end of the function as they are unlikely to be executed.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001326 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1327 OrigBB->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328
1329 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1330 // branch on RunningOr.
1331 OrigBB->getTerminator()->eraseFromParent();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001332 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333
1334 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1335 // pointer, because some may be null while others are not.
1336 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1337 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1338 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
Owen Anderson086ea052009-07-06 01:34:54 +00001339 Context->getNullValue(GVVal->getType()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 "tmp", NullPtrBlock);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001341 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1342 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1343 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344
1345 // Fill in FreeBlock.
1346 new FreeInst(GVVal, FreeBlock);
Owen Anderson086ea052009-07-06 01:34:54 +00001347 new StoreInst(Context->getNullValue(GVVal->getType()), FieldGlobals[i],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001348 FreeBlock);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001349 BranchInst::Create(NextBlock, FreeBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350
1351 NullPtrBlock = NextBlock;
1352 }
1353
Gabor Greifd6da1d02008-04-06 20:25:17 +00001354 BranchInst::Create(ContBB, NullPtrBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355
1356 // MI is no longer needed, remove it.
1357 MI->eraseFromParent();
1358
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001359 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1360 /// update all uses of the load, keep track of what scalarized loads are
1361 /// inserted for a given load.
1362 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1363 InsertedScalarizedValues[GV] = FieldGlobals;
1364
1365 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001366
1367 // Okay, the malloc site is completely handled. All of the uses of GV are now
1368 // loads, and all uses of those loads are simple. Rewrite them to use loads
1369 // of the per-field globals instead.
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001370 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1371 Instruction *User = cast<Instruction>(*UI++);
1372
1373 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson086ea052009-07-06 01:34:54 +00001374 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite,
1375 Context);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001376 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001377 }
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001378
1379 // Must be a store of null.
1380 StoreInst *SI = cast<StoreInst>(User);
1381 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1382 "Unexpected heap-sra user!");
1383
1384 // Insert a store of null into each global.
1385 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1386 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Owen Anderson086ea052009-07-06 01:34:54 +00001387 Constant *Null = Context->getNullValue(PT->getElementType());
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001388 new StoreInst(Null, FieldGlobals[i], SI);
1389 }
1390 // Erase the original store.
1391 SI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 }
1393
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001394 // While we have PHIs that are interesting to rewrite, do it.
1395 while (!PHIsToRewrite.empty()) {
1396 PHINode *PN = PHIsToRewrite.back().first;
1397 unsigned FieldNo = PHIsToRewrite.back().second;
1398 PHIsToRewrite.pop_back();
1399 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1400 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1401
1402 // Add all the incoming values. This can materialize more phis.
1403 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1404 Value *InVal = PN->getIncomingValue(i);
1405 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
Owen Anderson086ea052009-07-06 01:34:54 +00001406 PHIsToRewrite, Context);
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001407 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1408 }
1409 }
1410
1411 // Drop all inter-phi links and any loads that made it this far.
1412 for (DenseMap<Value*, std::vector<Value*> >::iterator
1413 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1414 I != E; ++I) {
1415 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1416 PN->dropAllReferences();
1417 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1418 LI->dropAllReferences();
1419 }
1420
1421 // Delete all the phis and loads now that inter-references are dead.
1422 for (DenseMap<Value*, std::vector<Value*> >::iterator
1423 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1424 I != E; ++I) {
1425 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1426 PN->eraseFromParent();
1427 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1428 LI->eraseFromParent();
1429 }
1430
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 // The old global is now dead, remove it.
1432 GV->eraseFromParent();
1433
1434 ++NumHeapSRA;
Chris Lattner8a2d32e2008-12-17 05:28:49 +00001435 return cast<GlobalVariable>(FieldGlobals[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436}
1437
Chris Lattner78e568b2008-12-15 21:02:25 +00001438/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1439/// pointer global variable with a single value stored it that is a malloc or
1440/// cast of malloc.
1441static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1442 MallocInst *MI,
1443 Module::global_iterator &GVI,
Owen Anderson086ea052009-07-06 01:34:54 +00001444 TargetData &TD,
1445 LLVMContext* Context) {
Chris Lattner78e568b2008-12-15 21:02:25 +00001446 // If this is a malloc of an abstract type, don't touch it.
1447 if (!MI->getAllocatedType()->isSized())
1448 return false;
1449
1450 // We can't optimize this global unless all uses of it are *known* to be
1451 // of the malloc value, not of the null initializer value (consider a use
1452 // that compares the global's value against zero to see if the malloc has
1453 // been reached). To do this, we check to see if all uses of the global
1454 // would trap if the global were null: this proves that they must all
1455 // happen after the malloc.
1456 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1457 return false;
1458
1459 // We can't optimize this if the malloc itself is used in a complex way,
1460 // for example, being stored into multiple globals. This allows the
1461 // malloc to be stored into the specified global, loaded setcc'd, and
1462 // GEP'd. These are all things we could transform to using the global
1463 // for.
1464 {
1465 SmallPtrSet<PHINode*, 8> PHIs;
1466 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1467 return false;
1468 }
1469
1470
1471 // If we have a global that is only initialized with a fixed size malloc,
1472 // transform the program to use global memory instead of malloc'd memory.
1473 // This eliminates dynamic allocation, avoids an indirection accessing the
1474 // data, and exposes the resultant global to further GlobalOpt.
1475 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1476 // Restrict this transformation to only working on small allocations
1477 // (2048 bytes currently), as we don't want to introduce a 16M global or
1478 // something.
1479 if (NElements->getZExtValue()*
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001480 TD.getTypeAllocSize(MI->getAllocatedType()) < 2048) {
Owen Anderson086ea052009-07-06 01:34:54 +00001481 GVI = OptimizeGlobalAddressOfMalloc(GV, MI, Context);
Chris Lattner78e568b2008-12-15 21:02:25 +00001482 return true;
1483 }
1484 }
1485
1486 // If the allocation is an array of structures, consider transforming this
1487 // into multiple malloc'd arrays, one for each field. This is basically
1488 // SRoA for malloc'd memory.
Chris Lattner27ef89e2008-12-15 21:44:34 +00001489 const Type *AllocTy = MI->getAllocatedType();
1490
1491 // If this is an allocation of a fixed size array of structs, analyze as a
1492 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1493 if (!MI->isArrayAllocation())
1494 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1495 AllocTy = AT->getElementType();
1496
1497 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
Chris Lattner78e568b2008-12-15 21:02:25 +00001498 // This the structure has an unreasonable number of fields, leave it
1499 // alone.
Chris Lattner27ef89e2008-12-15 21:44:34 +00001500 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
Chris Lattner7f252db2008-12-16 21:24:51 +00001501 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner27ef89e2008-12-15 21:44:34 +00001502
1503 // If this is a fixed size array, transform the Malloc to be an alloc of
1504 // structs. malloc [100 x struct],1 -> malloc struct, 100
1505 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1506 MallocInst *NewMI =
1507 new MallocInst(AllocSTy,
Owen Anderson086ea052009-07-06 01:34:54 +00001508 Context->getConstantInt(Type::Int32Ty, AT->getNumElements()),
Chris Lattner27ef89e2008-12-15 21:44:34 +00001509 "", MI);
1510 NewMI->takeName(MI);
1511 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1512 MI->replaceAllUsesWith(Cast);
1513 MI->eraseFromParent();
1514 MI = NewMI;
1515 }
1516
Owen Anderson086ea052009-07-06 01:34:54 +00001517 GVI = PerformHeapAllocSRoA(GV, MI, Context);
Chris Lattner78e568b2008-12-15 21:02:25 +00001518 return true;
1519 }
1520 }
1521
1522 return false;
1523}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524
1525// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1526// that only one value (besides its initializer) is ever stored to the global.
1527static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1528 Module::global_iterator &GVI,
Owen Anderson086ea052009-07-06 01:34:54 +00001529 TargetData &TD, LLVMContext* Context) {
Chris Lattner2e729112008-12-15 21:20:32 +00001530 // Ignore no-op GEPs and bitcasts.
1531 StoredOnceVal = StoredOnceVal->stripPointerCasts();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532
1533 // If we are dealing with a pointer global that is initialized to null and
1534 // only has one (non-null) value stored into it, then we can optimize any
1535 // users of the loaded value (often calls and loads) that would trap if the
1536 // value was null.
1537 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1538 GV->getInitializer()->isNullValue()) {
1539 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1540 if (GV->getInitializer()->getType() != SOVC->getType())
Owen Anderson086ea052009-07-06 01:34:54 +00001541 SOVC =
1542 Context->getConstantExprBitCast(SOVC, GV->getInitializer()->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543
1544 // Optimize away any trapping uses of the loaded value.
Owen Anderson086ea052009-07-06 01:34:54 +00001545 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 return true;
1547 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Owen Anderson086ea052009-07-06 01:34:54 +00001548 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD, Context))
Chris Lattner78e568b2008-12-15 21:02:25 +00001549 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550 }
1551 }
1552
1553 return false;
1554}
1555
Chris Lattnerece46db2008-01-14 01:17:44 +00001556/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1557/// two values ever stored into GV are its initializer and OtherVal. See if we
1558/// can shrink the global into a boolean and select between the two values
1559/// whenever it is used. This exposes the values to other scalar optimizations.
Owen Anderson086ea052009-07-06 01:34:54 +00001560static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal,
1561 LLVMContext* Context) {
Chris Lattnerece46db2008-01-14 01:17:44 +00001562 const Type *GVElType = GV->getType()->getElementType();
1563
1564 // If GVElType is already i1, it is already shrunk. If the type of the GV is
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001565 // an FP value, pointer or vector, don't do this optimization because a select
1566 // between them is very expensive and unlikely to lead to later
1567 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1568 // where v1 and v2 both require constant pool loads, a big loss.
Chris Lattnerece46db2008-01-14 01:17:44 +00001569 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
Chris Lattnere1d0fa12009-03-07 23:32:02 +00001570 isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
Chris Lattnerece46db2008-01-14 01:17:44 +00001571 return false;
1572
1573 // Walk the use list of the global seeing if all the uses are load or store.
1574 // If there is anything else, bail out.
1575 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
Devang Patel9b951552009-03-06 01:39:36 +00001576 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
Chris Lattnerece46db2008-01-14 01:17:44 +00001577 return false;
1578
1579 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1580
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001581 // Create the new global, initializing it to false.
1582 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Owen Anderson086ea052009-07-06 01:34:54 +00001583 GlobalValue::InternalLinkage, Context->getConstantIntFalse(),
Nick Lewycky74e96b72009-05-03 03:49:08 +00001584 GV->getName()+".b",
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585 (Module *)NULL,
1586 GV->isThreadLocal());
1587 GV->getParent()->getGlobalList().insert(GV, NewGV);
1588
1589 Constant *InitVal = GV->getInitializer();
1590 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1591
1592 // If initialized to zero and storing one into the global, we can use a cast
1593 // instead of a select to synthesize the desired value.
1594 bool IsOneZero = false;
1595 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1596 IsOneZero = InitVal->isNullValue() && CI->isOne();
1597
1598 while (!GV->use_empty()) {
Devang Patel9b951552009-03-06 01:39:36 +00001599 Instruction *UI = cast<Instruction>(GV->use_back());
1600 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001601 // Change the store into a boolean store.
1602 bool StoringOther = SI->getOperand(0) == OtherVal;
1603 // Only do this if we weren't storing a loaded value.
1604 Value *StoreVal;
1605 if (StoringOther || SI->getOperand(0) == InitVal)
Owen Anderson086ea052009-07-06 01:34:54 +00001606 StoreVal = Context->getConstantInt(Type::Int1Ty, StoringOther);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 else {
1608 // Otherwise, we are storing a previously loaded copy. To do this,
1609 // change the copy from copying the original value to just copying the
1610 // bool.
1611 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1612
1613 // If we're already replaced the input, StoredVal will be a cast or
1614 // select instruction. If not, it will be a load of the original
1615 // global.
1616 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1617 assert(LI->getOperand(0) == GV && "Not a copy!");
1618 // Insert a new load, to preserve the saved value.
1619 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1620 } else {
1621 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1622 "This is not a form that we understand!");
1623 StoreVal = StoredVal->getOperand(0);
1624 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1625 }
1626 }
1627 new StoreInst(StoreVal, NewGV, SI);
Devang Patel9b951552009-03-06 01:39:36 +00001628 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 // Change the load into a load of bool then a select.
Devang Patel9b951552009-03-06 01:39:36 +00001630 LoadInst *LI = cast<LoadInst>(UI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1632 Value *NSI;
1633 if (IsOneZero)
1634 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1635 else
Gabor Greifd6da1d02008-04-06 20:25:17 +00001636 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637 NSI->takeName(LI);
1638 LI->replaceAllUsesWith(NSI);
Devang Patel9b951552009-03-06 01:39:36 +00001639 }
1640 UI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001641 }
1642
1643 GV->eraseFromParent();
Chris Lattnerece46db2008-01-14 01:17:44 +00001644 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645}
1646
1647
1648/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1649/// it if possible. If we make a change, return true.
1650bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1651 Module::global_iterator &GVI) {
Chris Lattner4cd08c22008-12-16 07:34:30 +00001652 SmallPtrSet<PHINode*, 16> PHIUsers;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 GlobalStatus GS;
1654 GV->removeDeadConstantUsers();
1655
1656 if (GV->use_empty()) {
1657 DOUT << "GLOBAL DEAD: " << *GV;
1658 GV->eraseFromParent();
1659 ++NumDeleted;
1660 return true;
1661 }
1662
1663 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1664#if 0
1665 cerr << "Global: " << *GV;
1666 cerr << " isLoaded = " << GS.isLoaded << "\n";
1667 cerr << " StoredType = ";
1668 switch (GS.StoredType) {
1669 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1670 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1671 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1672 case GlobalStatus::isStored: cerr << "stored\n"; break;
1673 }
1674 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1675 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1676 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1677 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1678 << "\n";
1679 cerr << " HasMultipleAccessingFunctions = "
1680 << GS.HasMultipleAccessingFunctions << "\n";
1681 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 cerr << "\n";
1683#endif
1684
1685 // If this is a first class global and has only one accessing function
1686 // and this function is main (which we know is not recursive we can make
1687 // this global a local variable) we replace the global with a local alloca
1688 // in this function.
1689 //
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001690 // NOTE: It doesn't make sense to promote non single-value types since we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691 // are just replacing static memory to stack memory.
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001692 //
1693 // If the global is in different address space, don't bring it to stack.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 if (!GS.HasMultipleAccessingFunctions &&
1695 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001696 GV->getType()->getElementType()->isSingleValueType() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697 GS.AccessingFunction->getName() == "main" &&
Sanjiv Gupta961b5d22009-06-17 06:47:15 +00001698 GS.AccessingFunction->hasExternalLinkage() &&
1699 GV->getType()->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001700 DOUT << "LOCALIZING GLOBAL: " << *GV;
1701 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1702 const Type* ElemTy = GV->getType()->getElementType();
1703 // FIXME: Pass Global's alignment when globals have alignment
1704 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1705 if (!isa<UndefValue>(GV->getInitializer()))
1706 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1707
1708 GV->replaceAllUsesWith(Alloca);
1709 GV->eraseFromParent();
1710 ++NumLocalized;
1711 return true;
1712 }
1713
1714 // If the global is never loaded (but may be stored to), it is dead.
1715 // Delete it now.
1716 if (!GS.isLoaded) {
1717 DOUT << "GLOBAL NEVER LOADED: " << *GV;
1718
1719 // Delete any stores we can find to the global. We may not be able to
1720 // make it completely dead though.
Owen Andersond4d90a02009-07-06 18:42:36 +00001721 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1722 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723
1724 // If the global is dead now, delete it.
1725 if (GV->use_empty()) {
1726 GV->eraseFromParent();
1727 ++NumDeleted;
1728 Changed = true;
1729 }
1730 return Changed;
1731
1732 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1733 DOUT << "MARKING CONSTANT: " << *GV;
1734 GV->setConstant(true);
1735
1736 // Clean up any obviously simplifiable users now.
Owen Andersond4d90a02009-07-06 18:42:36 +00001737 CleanupConstantGlobalUsers(GV, GV->getInitializer(), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738
1739 // If the global is dead now, just nuke it.
1740 if (GV->use_empty()) {
1741 DOUT << " *** Marking constant allowed us to simplify "
1742 << "all users and delete global!\n";
1743 GV->eraseFromParent();
1744 ++NumDeleted;
1745 }
1746
1747 ++NumMarked;
1748 return true;
Dan Gohman5e8fbc22008-05-23 00:17:26 +00001749 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
Chris Lattner20846272008-04-26 07:40:11 +00001750 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
Owen Anderson086ea052009-07-06 01:34:54 +00001751 getAnalysis<TargetData>(),
1752 Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001753 GVI = FirstNewGV; // Don't skip the newly produced globals!
1754 return true;
1755 }
1756 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1757 // If the initial value for the global was an undef value, and if only
1758 // one other value was stored into it, we can just change the
Duncan Sands25464152009-01-13 13:48:44 +00001759 // initializer to be the stored value, then delete all stores to the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 // global. This allows us to mark it constant.
1761 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1762 if (isa<UndefValue>(GV->getInitializer())) {
1763 // Change the initial value here.
1764 GV->setInitializer(SOVConstant);
1765
1766 // Clean up any obviously simplifiable users now.
Owen Andersond4d90a02009-07-06 18:42:36 +00001767 CleanupConstantGlobalUsers(GV, GV->getInitializer(), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768
1769 if (GV->use_empty()) {
1770 DOUT << " *** Substituting initializer allowed us to "
1771 << "simplify all users and delete global!\n";
1772 GV->eraseFromParent();
1773 ++NumDeleted;
1774 } else {
1775 GVI = GV;
1776 }
1777 ++NumSubstitute;
1778 return true;
1779 }
1780
1781 // Try to optimize globals based on the knowledge that only one value
1782 // (besides its initializer) is ever stored to the global.
1783 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
Owen Anderson086ea052009-07-06 01:34:54 +00001784 getAnalysis<TargetData>(), Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 return true;
1786
1787 // Otherwise, if the global was not a boolean, we can shrink it to be a
1788 // boolean.
1789 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Owen Anderson086ea052009-07-06 01:34:54 +00001790 if (TryToShrinkGlobalToBoolean(GV, SOVConstant, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791 ++NumShrunkToBool;
1792 return true;
1793 }
1794 }
1795 }
1796 return false;
1797}
1798
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1800/// function, changing them to FastCC.
1801static void ChangeCalleesToFastCall(Function *F) {
1802 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001803 CallSite User(cast<Instruction>(*UI));
1804 User.setCallingConv(CallingConv::Fast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805 }
1806}
1807
Devang Pateld222f862008-09-25 21:00:45 +00001808static AttrListPtr StripNest(const AttrListPtr &Attrs) {
Chris Lattner1c8733e2008-03-12 17:45:29 +00001809 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
Devang Pateld222f862008-09-25 21:00:45 +00001810 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
Duncan Sands551ec902008-02-18 17:32:13 +00001811 continue;
1812
Duncan Sands551ec902008-02-18 17:32:13 +00001813 // There can be only one.
Devang Pateld222f862008-09-25 21:00:45 +00001814 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001815 }
1816
1817 return Attrs;
1818}
1819
1820static void RemoveNestAttribute(Function *F) {
Devang Pateld222f862008-09-25 21:00:45 +00001821 F->setAttributes(StripNest(F->getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001822 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands551ec902008-02-18 17:32:13 +00001823 CallSite User(cast<Instruction>(*UI));
Devang Pateld222f862008-09-25 21:00:45 +00001824 User.setAttributes(StripNest(User.getAttributes()));
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001825 }
1826}
1827
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001828bool GlobalOpt::OptimizeFunctions(Module &M) {
1829 bool Changed = false;
1830 // Optimize functions.
1831 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1832 Function *F = FI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001833 // Functions without names cannot be referenced outside this module.
1834 if (!F->hasName() && !F->isDeclaration())
1835 F->setLinkage(GlobalValue::InternalLinkage);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001836 F->removeDeadConstantUsers();
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001837 if (F->use_empty() && (F->hasLocalLinkage() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001838 F->hasLinkOnceLinkage())) {
1839 M.getFunctionList().erase(F);
1840 Changed = true;
1841 ++NumFnDeleted;
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001842 } else if (F->hasLocalLinkage()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001843 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
Jay Foad1379d592009-06-10 08:41:11 +00001844 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001845 // If this function has C calling conventions, is not a varargs
1846 // function, and is only called directly, promote it to use the Fast
1847 // calling convention.
1848 F->setCallingConv(CallingConv::Fast);
1849 ChangeCalleesToFastCall(F);
1850 ++NumFastCallFns;
1851 Changed = true;
1852 }
1853
Devang Pateld222f862008-09-25 21:00:45 +00001854 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
Jay Foad1379d592009-06-10 08:41:11 +00001855 !F->hasAddressTaken()) {
Duncan Sandsafa10bf2008-02-16 20:56:04 +00001856 // The function is not used by a trampoline intrinsic, so it is safe
1857 // to remove the 'nest' attribute.
1858 RemoveNestAttribute(F);
1859 ++NumNestRemoved;
1860 Changed = true;
1861 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001862 }
1863 }
1864 return Changed;
1865}
1866
1867bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1868 bool Changed = false;
1869 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1870 GVI != E; ) {
1871 GlobalVariable *GV = GVI++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00001872 // Global variables without names cannot be referenced outside this module.
1873 if (!GV->hasName() && !GV->isDeclaration())
1874 GV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001875 if (!GV->isConstant() && GV->hasLocalLinkage() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001876 GV->hasInitializer())
1877 Changed |= ProcessInternalGlobal(GV, GVI);
1878 }
1879 return Changed;
1880}
1881
1882/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1883/// initializers have an init priority of 65535.
1884GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1885 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1886 I != E; ++I)
1887 if (I->getName() == "llvm.global_ctors") {
1888 // Found it, verify it's an array of { int, void()* }.
1889 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1890 if (!ATy) return 0;
1891 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1892 if (!STy || STy->getNumElements() != 2 ||
1893 STy->getElementType(0) != Type::Int32Ty) return 0;
1894 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1895 if (!PFTy) return 0;
1896 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1897 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1898 FTy->getNumParams() != 0)
1899 return 0;
1900
1901 // Verify that the initializer is simple enough for us to handle.
1902 if (!I->hasInitializer()) return 0;
1903 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1904 if (!CA) return 0;
Gabor Greif20f03f52008-05-29 01:59:18 +00001905 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1906 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1908 continue;
1909
1910 // Must have a function or null ptr.
1911 if (!isa<Function>(CS->getOperand(1)))
1912 return 0;
1913
1914 // Init priority must be standard.
1915 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1916 if (!CI || CI->getZExtValue() != 65535)
1917 return 0;
1918 } else {
1919 return 0;
1920 }
1921
1922 return I;
1923 }
1924 return 0;
1925}
1926
1927/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1928/// return a list of the functions and null terminator as a vector.
1929static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1930 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1931 std::vector<Function*> Result;
1932 Result.reserve(CA->getNumOperands());
Gabor Greif20f03f52008-05-29 01:59:18 +00001933 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1934 ConstantStruct *CS = cast<ConstantStruct>(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001935 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1936 }
1937 return Result;
1938}
1939
1940/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1941/// specified array, returning the new global to use.
1942static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
Owen Anderson086ea052009-07-06 01:34:54 +00001943 const std::vector<Function*> &Ctors,
1944 LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001945 // If we made a change, reassemble the initializer list.
1946 std::vector<Constant*> CSVals;
Owen Anderson086ea052009-07-06 01:34:54 +00001947 CSVals.push_back(Context->getConstantInt(Type::Int32Ty, 65535));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001948 CSVals.push_back(0);
1949
1950 // Create the new init list.
1951 std::vector<Constant*> CAList;
1952 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1953 if (Ctors[i]) {
1954 CSVals[1] = Ctors[i];
1955 } else {
Owen Anderson086ea052009-07-06 01:34:54 +00001956 const Type *FTy = Context->getFunctionType(Type::VoidTy, false);
1957 const PointerType *PFTy = Context->getPointerTypeUnqual(FTy);
1958 CSVals[1] = Context->getNullValue(PFTy);
1959 CSVals[0] = Context->getConstantInt(Type::Int32Ty, 2147483647);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960 }
Owen Anderson086ea052009-07-06 01:34:54 +00001961 CAList.push_back(Context->getConstantStruct(CSVals));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001962 }
1963
1964 // Create the array initializer.
1965 const Type *StructTy =
1966 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Owen Anderson086ea052009-07-06 01:34:54 +00001967 Constant *CA = Context->getConstantArray(ArrayType::get(StructTy,
1968 CAList.size()), CAList);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969
1970 // If we didn't change the number of elements, don't create a new GV.
1971 if (CA->getType() == GCL->getInitializer()->getType()) {
1972 GCL->setInitializer(CA);
1973 return GCL;
1974 }
1975
1976 // Create the new global and insert it next to the existing list.
1977 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1978 GCL->getLinkage(), CA, "",
1979 (Module *)NULL,
1980 GCL->isThreadLocal());
1981 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1982 NGV->takeName(GCL);
1983
1984 // Nuke the old list, replacing any uses with the new one.
1985 if (!GCL->use_empty()) {
1986 Constant *V = NGV;
1987 if (V->getType() != GCL->getType())
Owen Anderson086ea052009-07-06 01:34:54 +00001988 V = Context->getConstantExprBitCast(V, GCL->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 GCL->replaceAllUsesWith(V);
1990 }
1991 GCL->eraseFromParent();
1992
1993 if (Ctors.size())
1994 return NGV;
1995 else
1996 return 0;
1997}
1998
1999
Chris Lattner4cd08c22008-12-16 07:34:30 +00002000static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001 Value *V) {
2002 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2003 Constant *R = ComputedValues[V];
2004 assert(R && "Reference to an uncomputed value!");
2005 return R;
2006}
2007
2008/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2009/// enough for us to understand. In particular, if it is a cast of something,
2010/// we punt. We basically just support direct accesses to globals and GEP's of
2011/// globals. This should be kept up to date with CommitValueTo.
Owen Andersond4d90a02009-07-06 18:42:36 +00002012static bool isSimpleEnoughPointerToCommit(Constant *C, LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002014 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002015 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2016 return !GV->isDeclaration(); // reject external globals.
2017 }
2018 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2019 // Handle a constantexpr gep.
2020 if (CE->getOpcode() == Instruction::GetElementPtr &&
2021 isa<GlobalVariable>(CE->getOperand(0))) {
2022 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Rafael Espindolaa168fc92009-01-15 20:18:42 +00002023 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002024 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
2025 return GV->hasInitializer() &&
Owen Andersond4d90a02009-07-06 18:42:36 +00002026 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2027 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002028 }
2029 return false;
2030}
2031
2032/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2033/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2034/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2035static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
Owen Anderson086ea052009-07-06 01:34:54 +00002036 ConstantExpr *Addr, unsigned OpNo,
2037 LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002038 // Base case of the recursion.
2039 if (OpNo == Addr->getNumOperands()) {
2040 assert(Val->getType() == Init->getType() && "Type mismatch!");
2041 return Val;
2042 }
2043
2044 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2045 std::vector<Constant*> Elts;
2046
2047 // Break up the constant into its elements.
2048 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002049 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2050 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002051 } else if (isa<ConstantAggregateZero>(Init)) {
2052 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson086ea052009-07-06 01:34:54 +00002053 Elts.push_back(Context->getNullValue(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054 } else if (isa<UndefValue>(Init)) {
2055 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Owen Anderson086ea052009-07-06 01:34:54 +00002056 Elts.push_back(Context->getUndef(STy->getElementType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057 } else {
2058 assert(0 && "This code is out of sync with "
2059 " ConstantFoldLoadThroughGEPConstantExpr");
2060 }
2061
2062 // Replace the element that we are supposed to.
2063 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2064 unsigned Idx = CU->getZExtValue();
2065 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Owen Anderson086ea052009-07-06 01:34:54 +00002066 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002067
2068 // Return the modified struct.
Owen Anderson086ea052009-07-06 01:34:54 +00002069 return Context->getConstantStruct(&Elts[0], Elts.size(), STy->isPacked());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070 } else {
2071 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2072 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2073
2074 // Break up the array into elements.
2075 std::vector<Constant*> Elts;
2076 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
Gabor Greif20f03f52008-05-29 01:59:18 +00002077 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2078 Elts.push_back(cast<Constant>(*i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002079 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002080 Constant *Elt = Context->getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002081 Elts.assign(ATy->getNumElements(), Elt);
2082 } else if (isa<UndefValue>(Init)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002083 Constant *Elt = Context->getUndef(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084 Elts.assign(ATy->getNumElements(), Elt);
2085 } else {
2086 assert(0 && "This code is out of sync with "
2087 " ConstantFoldLoadThroughGEPConstantExpr");
2088 }
2089
2090 assert(CI->getZExtValue() < ATy->getNumElements());
2091 Elts[CI->getZExtValue()] =
Owen Anderson086ea052009-07-06 01:34:54 +00002092 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1, Context);
2093 return Context->getConstantArray(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002094 }
2095}
2096
2097/// CommitValueTo - We have decided that Addr (which satisfies the predicate
2098/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
Owen Anderson086ea052009-07-06 01:34:54 +00002099static void CommitValueTo(Constant *Val, Constant *Addr,
2100 LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002101 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2102 assert(GV->hasInitializer());
2103 GV->setInitializer(Val);
2104 return;
2105 }
2106
2107 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2108 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2109
2110 Constant *Init = GV->getInitializer();
Owen Anderson086ea052009-07-06 01:34:54 +00002111 Init = EvaluateStoreInto(Init, Val, CE, 2, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112 GV->setInitializer(Init);
2113}
2114
2115/// ComputeLoadResult - Return the value that would be computed by a load from
2116/// P after the stores reflected by 'memory' have been performed. If we can't
2117/// decide, return null.
2118static Constant *ComputeLoadResult(Constant *P,
Owen Andersond4d90a02009-07-06 18:42:36 +00002119 const DenseMap<Constant*, Constant*> &Memory,
2120 LLVMContext* Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002121 // If this memory location has been recently stored, use the stored value: it
2122 // is the most up-to-date.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002123 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002124 if (I != Memory.end()) return I->second;
2125
2126 // Access it.
2127 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2128 if (GV->hasInitializer())
2129 return GV->getInitializer();
2130 return 0;
2131 }
2132
2133 // Handle a constantexpr getelementptr.
2134 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2135 if (CE->getOpcode() == Instruction::GetElementPtr &&
2136 isa<GlobalVariable>(CE->getOperand(0))) {
2137 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2138 if (GV->hasInitializer())
Owen Andersond4d90a02009-07-06 18:42:36 +00002139 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
2140 Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141 }
2142
2143 return 0; // don't know how to evaluate.
2144}
2145
2146/// EvaluateFunction - Evaluate a call to function F, returning true if
2147/// successful, false if we can't evaluate it. ActualArgs contains the formal
2148/// arguments for the function.
2149static bool EvaluateFunction(Function *F, Constant *&RetVal,
2150 const std::vector<Constant*> &ActualArgs,
2151 std::vector<Function*> &CallStack,
Chris Lattner4cd08c22008-12-16 07:34:30 +00002152 DenseMap<Constant*, Constant*> &MutatedMemory,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002153 std::vector<GlobalVariable*> &AllocaTmps) {
2154 // Check to see if this function is already executing (recursion). If so,
2155 // bail out. TODO: we might want to accept limited recursion.
2156 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2157 return false;
2158
Owen Anderson086ea052009-07-06 01:34:54 +00002159 LLVMContext* Context = F->getContext();
2160
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161 CallStack.push_back(F);
2162
2163 /// Values - As we compute SSA register values, we store their contents here.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002164 DenseMap<Value*, Constant*> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002165
2166 // Initialize arguments to the incoming values specified.
2167 unsigned ArgNo = 0;
2168 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2169 ++AI, ++ArgNo)
2170 Values[AI] = ActualArgs[ArgNo];
2171
2172 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2173 /// we can only evaluate any one basic block at most once. This set keeps
2174 /// track of what we have executed so we can detect recursive cases etc.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002175 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002176
2177 // CurInst - The current instruction we're evaluating.
2178 BasicBlock::iterator CurInst = F->begin()->begin();
2179
2180 // This is the main evaluation loop.
2181 while (1) {
2182 Constant *InstResult = 0;
2183
2184 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2185 if (SI->isVolatile()) return false; // no volatile accesses.
2186 Constant *Ptr = getVal(Values, SI->getOperand(1));
Owen Andersond4d90a02009-07-06 18:42:36 +00002187 if (!isSimpleEnoughPointerToCommit(Ptr, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 // If this is too complex for us to commit, reject it.
2189 return false;
2190 Constant *Val = getVal(Values, SI->getOperand(0));
2191 MutatedMemory[Ptr] = Val;
2192 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002193 InstResult = Context->getConstantExpr(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194 getVal(Values, BO->getOperand(0)),
2195 getVal(Values, BO->getOperand(1)));
2196 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002197 InstResult = Context->getConstantExprCompare(CI->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002198 getVal(Values, CI->getOperand(0)),
2199 getVal(Values, CI->getOperand(1)));
2200 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002201 InstResult = Context->getConstantExprCast(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202 getVal(Values, CI->getOperand(0)),
2203 CI->getType());
2204 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
Owen Anderson086ea052009-07-06 01:34:54 +00002205 InstResult =
2206 Context->getConstantExprSelect(getVal(Values, SI->getOperand(0)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002207 getVal(Values, SI->getOperand(1)),
2208 getVal(Values, SI->getOperand(2)));
2209 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2210 Constant *P = getVal(Values, GEP->getOperand(0));
2211 SmallVector<Constant*, 8> GEPOps;
Gabor Greif20f03f52008-05-29 01:59:18 +00002212 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2213 i != e; ++i)
2214 GEPOps.push_back(getVal(Values, *i));
Owen Anderson086ea052009-07-06 01:34:54 +00002215 InstResult =
2216 Context->getConstantExprGetElementPtr(P, &GEPOps[0], GEPOps.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002217 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2218 if (LI->isVolatile()) return false; // no volatile accesses.
2219 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
Owen Andersond4d90a02009-07-06 18:42:36 +00002220 MutatedMemory, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221 if (InstResult == 0) return false; // Could not evaluate load.
2222 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2223 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2224 const Type *Ty = AI->getType()->getElementType();
2225 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2226 GlobalValue::InternalLinkage,
Owen Anderson086ea052009-07-06 01:34:54 +00002227 Context->getUndef(Ty),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228 AI->getName()));
2229 InstResult = AllocaTmps.back();
2230 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Devang Patel5b1082b2009-03-09 23:04:12 +00002231
2232 // Debug info can safely be ignored here.
2233 if (isa<DbgInfoIntrinsic>(CI)) {
2234 ++CurInst;
2235 continue;
2236 }
2237
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002238 // Cannot handle inline asm.
2239 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2240
2241 // Resolve function pointers.
2242 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2243 if (!Callee) return false; // Cannot resolve.
2244
2245 std::vector<Constant*> Formals;
Gabor Greif20f03f52008-05-29 01:59:18 +00002246 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2247 i != e; ++i)
2248 Formals.push_back(getVal(Values, *i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249
2250 if (Callee->isDeclaration()) {
2251 // If this is a function we can constant fold, do it.
2252 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2253 Formals.size())) {
2254 InstResult = C;
2255 } else {
2256 return false;
2257 }
2258 } else {
2259 if (Callee->getFunctionType()->isVarArg())
2260 return false;
2261
2262 Constant *RetVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 // Execute the call, if successful, use the return value.
2264 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2265 MutatedMemory, AllocaTmps))
2266 return false;
2267 InstResult = RetVal;
2268 }
2269 } else if (isa<TerminatorInst>(CurInst)) {
2270 BasicBlock *NewBB = 0;
2271 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2272 if (BI->isUnconditional()) {
2273 NewBB = BI->getSuccessor(0);
2274 } else {
2275 ConstantInt *Cond =
2276 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2277 if (!Cond) return false; // Cannot determine.
2278
2279 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2280 }
2281 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2282 ConstantInt *Val =
2283 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2284 if (!Val) return false; // Cannot determine.
2285 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2286 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2287 if (RI->getNumOperands())
2288 RetVal = getVal(Values, RI->getOperand(0));
2289
2290 CallStack.pop_back(); // return from fn.
2291 return true; // We succeeded at evaluating this ctor!
2292 } else {
2293 // invoke, unwind, unreachable.
2294 return false; // Cannot handle this terminator.
2295 }
2296
2297 // Okay, we succeeded in evaluating this control flow. See if we have
2298 // executed the new block before. If so, we have a looping function,
2299 // which we cannot evaluate in reasonable time.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002300 if (!ExecutedBlocks.insert(NewBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002301 return false; // looped!
2302
2303 // Okay, we have never been in this block before. Check to see if there
2304 // are any PHI nodes. If so, evaluate them with information about where
2305 // we came from.
2306 BasicBlock *OldBB = CurInst->getParent();
2307 CurInst = NewBB->begin();
2308 PHINode *PN;
2309 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2310 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2311
2312 // Do NOT increment CurInst. We know that the terminator had no value.
2313 continue;
2314 } else {
2315 // Did not know how to evaluate this!
2316 return false;
2317 }
2318
2319 if (!CurInst->use_empty())
2320 Values[CurInst] = InstResult;
2321
2322 // Advance program counter.
2323 ++CurInst;
2324 }
2325}
2326
2327/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2328/// we can. Return true if we can, false otherwise.
2329static bool EvaluateStaticConstructor(Function *F) {
2330 /// MutatedMemory - For each store we execute, we update this map. Loads
2331 /// check this to get the most up-to-date value. If evaluation is successful,
2332 /// this state is committed to the process.
Chris Lattner4cd08c22008-12-16 07:34:30 +00002333 DenseMap<Constant*, Constant*> MutatedMemory;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002334
2335 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2336 /// to represent its body. This vector is needed so we can delete the
2337 /// temporary globals when we are done.
2338 std::vector<GlobalVariable*> AllocaTmps;
2339
2340 /// CallStack - This is used to detect recursion. In pathological situations
2341 /// we could hit exponential behavior, but at least there is nothing
2342 /// unbounded.
2343 std::vector<Function*> CallStack;
2344
2345 // Call the function.
2346 Constant *RetValDummy;
2347 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2348 CallStack, MutatedMemory, AllocaTmps);
2349 if (EvalSuccess) {
2350 // We succeeded at evaluation: commit the result.
2351 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2352 << F->getName() << "' to " << MutatedMemory.size()
2353 << " stores.\n";
Chris Lattner4cd08c22008-12-16 07:34:30 +00002354 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355 E = MutatedMemory.end(); I != E; ++I)
Owen Anderson086ea052009-07-06 01:34:54 +00002356 CommitValueTo(I->second, I->first, F->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002357 }
2358
2359 // At this point, we are done interpreting. If we created any 'alloca'
2360 // temporaries, release them now.
2361 while (!AllocaTmps.empty()) {
2362 GlobalVariable *Tmp = AllocaTmps.back();
2363 AllocaTmps.pop_back();
2364
2365 // If there are still users of the alloca, the program is doing something
2366 // silly, e.g. storing the address of the alloca somewhere and using it
2367 // later. Since this is undefined, we'll just make it be null.
2368 if (!Tmp->use_empty())
Owen Anderson086ea052009-07-06 01:34:54 +00002369 Tmp->replaceAllUsesWith(F->getContext()->getNullValue(Tmp->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002370 delete Tmp;
2371 }
2372
2373 return EvalSuccess;
2374}
2375
2376
2377
2378/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2379/// Return true if anything changed.
2380bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2381 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2382 bool MadeChange = false;
2383 if (Ctors.empty()) return false;
2384
2385 // Loop over global ctors, optimizing them when we can.
2386 for (unsigned i = 0; i != Ctors.size(); ++i) {
2387 Function *F = Ctors[i];
2388 // Found a null terminator in the middle of the list, prune off the rest of
2389 // the list.
2390 if (F == 0) {
2391 if (i != Ctors.size()-1) {
2392 Ctors.resize(i+1);
2393 MadeChange = true;
2394 }
2395 break;
2396 }
2397
2398 // We cannot simplify external ctor functions.
2399 if (F->empty()) continue;
2400
2401 // If we can evaluate the ctor at compile time, do.
2402 if (EvaluateStaticConstructor(F)) {
2403 Ctors.erase(Ctors.begin()+i);
2404 MadeChange = true;
2405 --i;
2406 ++NumCtorsEvaluated;
2407 continue;
2408 }
2409 }
2410
2411 if (!MadeChange) return false;
2412
Owen Anderson086ea052009-07-06 01:34:54 +00002413 GCL = InstallGlobalCtors(GCL, Ctors, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002414 return true;
2415}
2416
Duncan Sands0c7b6332009-03-06 10:21:56 +00002417bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002418 bool Changed = false;
2419
Duncan Sands0f064b92009-01-07 20:01:06 +00002420 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002421 I != E;) {
2422 Module::alias_iterator J = I++;
Duncan Sands0c7b6332009-03-06 10:21:56 +00002423 // Aliases without names cannot be referenced outside this module.
2424 if (!J->hasName() && !J->isDeclaration())
2425 J->setLinkage(GlobalValue::InternalLinkage);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002426 // If the aliasee may change at link time, nothing can be done - bail out.
2427 if (J->mayBeOverridden())
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002428 continue;
2429
Duncan Sandse7f431f2009-02-15 09:56:08 +00002430 Constant *Aliasee = J->getAliasee();
2431 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Duncan Sands7531ad62009-02-18 17:55:38 +00002432 Target->removeDeadConstantUsers();
Duncan Sandse7f431f2009-02-15 09:56:08 +00002433 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2434
2435 // Make all users of the alias use the aliasee instead.
2436 if (!J->use_empty()) {
2437 J->replaceAllUsesWith(Aliasee);
2438 ++NumAliasesResolved;
2439 Changed = true;
2440 }
2441
2442 // If the aliasee has internal linkage, give it the name and linkage
2443 // of the alias, and delete the alias. This turns:
2444 // define internal ... @f(...)
2445 // @a = alias ... @f
2446 // into:
2447 // define ... @a(...)
Duncan Sands8f723612009-02-17 17:50:04 +00002448 if (!Target->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002449 continue;
2450
2451 // The transform is only useful if the alias does not have internal linkage.
Duncan Sands8f723612009-02-17 17:50:04 +00002452 if (J->hasLocalLinkage())
Duncan Sandse7f431f2009-02-15 09:56:08 +00002453 continue;
2454
Duncan Sandse10858a2009-02-15 11:54:49 +00002455 // Do not perform the transform if multiple aliases potentially target the
2456 // aliasee. This check also ensures that it is safe to replace the section
2457 // and other attributes of the aliasee with those of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002458 if (!hasOneUse)
2459 continue;
2460
Duncan Sandse10858a2009-02-15 11:54:49 +00002461 // Give the aliasee the name, linkage and other attributes of the alias.
Duncan Sandse7f431f2009-02-15 09:56:08 +00002462 Target->takeName(J);
2463 Target->setLinkage(J->getLinkage());
Duncan Sandse10858a2009-02-15 11:54:49 +00002464 Target->GlobalValue::copyAttributesFrom(J);
Duncan Sandse7f431f2009-02-15 09:56:08 +00002465
2466 // Delete the alias.
2467 M.getAliasList().erase(J);
2468 ++NumAliasesRemoved;
2469 Changed = true;
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002470 }
2471
2472 return Changed;
2473}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002474
2475bool GlobalOpt::runOnModule(Module &M) {
2476 bool Changed = false;
2477
2478 // Try to find the llvm.globalctors list.
2479 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2480
2481 bool LocalChange = true;
2482 while (LocalChange) {
2483 LocalChange = false;
2484
2485 // Delete functions that are trivially dead, ccc -> fastcc
2486 LocalChange |= OptimizeFunctions(M);
2487
2488 // Optimize global_ctors list.
2489 if (GlobalCtors)
2490 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2491
2492 // Optimize non-address-taken globals.
2493 LocalChange |= OptimizeGlobalVars(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002494
2495 // Resolve aliases, when possible.
Duncan Sands0c7b6332009-03-06 10:21:56 +00002496 LocalChange |= OptimizeGlobalAliases(M);
Anton Korobeynikov76944bd2008-09-09 19:04:59 +00002497 Changed |= LocalChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002498 }
2499
2500 // TODO: Move all global ctors functions to the end of the module for code
2501 // layout.
2502
2503 return Changed;
2504}