blob: e5427766bfa959f806a9196e27ff5f60497e3efb [file] [log] [blame]
Chris Lattner7a90b682004-10-07 04:16:33 +00001//===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner079236d2004-02-25 21:34:36 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner079236d2004-02-25 21:34:36 +00008//===----------------------------------------------------------------------===//
9//
Chris Lattner7a90b682004-10-07 04:16:33 +000010// 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.
Chris Lattner079236d2004-02-25 21:34:36 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner7a90b682004-10-07 04:16:33 +000016#define DEBUG_TYPE "globalopt"
Chris Lattner079236d2004-02-25 21:34:36 +000017#include "llvm/Transforms/IPO.h"
Chris Lattnerfb217ad2005-05-08 22:18:06 +000018#include "llvm/CallingConv.h"
Chris Lattner079236d2004-02-25 21:34:36 +000019#include "llvm/Constants.h"
Chris Lattner7a90b682004-10-07 04:16:33 +000020#include "llvm/DerivedTypes.h"
Chris Lattner7d90a272004-02-27 18:09:25 +000021#include "llvm/Instructions.h"
Chris Lattner35c81b02005-02-27 18:58:52 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner079236d2004-02-25 21:34:36 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
Duncan Sands548448a2008-02-18 17:32:13 +000027#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000028#include "llvm/Support/Compiler.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000029#include "llvm/Support/Debug.h"
Chris Lattner941db492008-01-14 02:09:12 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner81686182007-09-13 16:30:19 +000031#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000032#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000034#include "llvm/ADT/StringExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000035#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000036#include <map>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000037#include <set>
Chris Lattner079236d2004-02-25 21:34:36 +000038using namespace llvm;
39
Chris Lattner86453c52006-12-19 22:09:18 +000040STATISTIC(NumMarked , "Number of globals marked constant");
41STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
42STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
43STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
44STATISTIC(NumDeleted , "Number of globals deleted");
45STATISTIC(NumFnDeleted , "Number of functions deleted");
46STATISTIC(NumGlobUses , "Number of global uses devirtualized");
47STATISTIC(NumLocalized , "Number of globals localized");
48STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
49STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
50STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
Duncan Sands3d5378f2008-02-16 20:56:04 +000051STATISTIC(NumNestRemoved , "Number of nest attributes removed");
Chris Lattner079236d2004-02-25 21:34:36 +000052
Chris Lattner86453c52006-12-19 22:09:18 +000053namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000054 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000055 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<TargetData>();
57 }
Nick Lewyckyecd94c82007-05-06 13:37:16 +000058 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000059 GlobalOpt() : ModulePass((intptr_t)&ID) {}
Misha Brukmanfd939082005-04-21 23:48:37 +000060
Chris Lattnerb12914b2004-09-20 04:48:05 +000061 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000062
63 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000064 GlobalVariable *FindGlobalCtors(Module &M);
65 bool OptimizeFunctions(Module &M);
66 bool OptimizeGlobalVars(Module &M);
67 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000068 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000069 };
70
Devang Patel19974732007-05-03 01:11:54 +000071 char GlobalOpt::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000072 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner079236d2004-02-25 21:34:36 +000073}
74
Chris Lattner7a90b682004-10-07 04:16:33 +000075ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000076
Chris Lattner7a90b682004-10-07 04:16:33 +000077/// GlobalStatus - As we analyze each global, keep track of some information
78/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000079/// this info will be accurate.
Reid Spencer9133fe22007-02-05 23:32:05 +000080struct VISIBILITY_HIDDEN GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000081 /// isLoaded - True if the global is ever loaded. If the global isn't ever
82 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000083 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000084
85 /// StoredType - Keep track of what stores to the global look like.
86 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000087 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000088 /// NotStored - There is no store to this global. It can thus be marked
89 /// constant.
90 NotStored,
91
92 /// isInitializerStored - This global is stored to, but the only thing
93 /// stored is the constant it was initialized with. This is only tracked
94 /// for scalar globals.
95 isInitializerStored,
96
97 /// isStoredOnce - This global is stored to, but only its initializer and
98 /// one other value is ever stored to it. If this global isStoredOnce, we
99 /// track the value stored to it in StoredOnceValue below. This is only
100 /// tracked for scalar globals.
101 isStoredOnce,
102
103 /// isStored - This global is stored to by multiple values or something else
104 /// that we cannot track.
105 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000106 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000107
108 /// StoredOnceValue - If only one value (besides the initializer constant) is
109 /// ever stored to this global, keep track of what value it is.
110 Value *StoredOnceValue;
111
Chris Lattner25de4e52006-11-01 18:03:33 +0000112 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
113 /// null/false. When the first accessing function is noticed, it is recorded.
114 /// When a second different accessing function is noticed,
115 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000116 Function *AccessingFunction;
117 bool HasMultipleAccessingFunctions;
118
Chris Lattner25de4e52006-11-01 18:03:33 +0000119 /// HasNonInstructionUser - Set to true if this global has a user that is not
120 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000121 bool HasNonInstructionUser;
122
Chris Lattner25de4e52006-11-01 18:03:33 +0000123 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
124 bool HasPHIUser;
125
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000126 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000127 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner6a93fc02008-01-14 01:32:52 +0000128 HasNonInstructionUser(false), HasPHIUser(false) {}
Chris Lattner7a90b682004-10-07 04:16:33 +0000129};
Chris Lattnere47ba742004-10-06 20:57:02 +0000130
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000131
132
133/// ConstantIsDead - Return true if the specified constant is (transitively)
134/// dead. The constant may be used by other constants (e.g. constant arrays and
135/// constant exprs) as long as they are dead, but it cannot be used by anything
136/// else.
137static bool ConstantIsDead(Constant *C) {
138 if (isa<GlobalValue>(C)) return false;
139
140 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
141 if (Constant *CU = dyn_cast<Constant>(*UI)) {
142 if (!ConstantIsDead(CU)) return false;
143 } else
144 return false;
145 return true;
146}
147
148
Chris Lattner7a90b682004-10-07 04:16:33 +0000149/// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
150/// structure. If the global has its address taken, return true to indicate we
151/// can't do anything with it.
Chris Lattner079236d2004-02-25 21:34:36 +0000152///
Chris Lattner7a90b682004-10-07 04:16:33 +0000153static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
154 std::set<PHINode*> &PHIUsers) {
Chris Lattner079236d2004-02-25 21:34:36 +0000155 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Chris Lattner96940cb2004-07-18 19:56:20 +0000156 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000157 GS.HasNonInstructionUser = true;
158
Chris Lattner7a90b682004-10-07 04:16:33 +0000159 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
Chris Lattner670c8892004-10-08 17:32:09 +0000160
Chris Lattner079236d2004-02-25 21:34:36 +0000161 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000162 if (!GS.HasMultipleAccessingFunctions) {
163 Function *F = I->getParent()->getParent();
164 if (GS.AccessingFunction == 0)
165 GS.AccessingFunction = F;
166 else if (GS.AccessingFunction != F)
167 GS.HasMultipleAccessingFunctions = true;
168 }
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000169 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000170 GS.isLoaded = true;
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000171 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
Chris Lattner7a90b682004-10-07 04:16:33 +0000172 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000173 // Don't allow a store OF the address, only stores TO the address.
174 if (SI->getOperand(0) == V) return true;
175
Chris Lattnerc69d3c92008-01-29 19:01:37 +0000176 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
177
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000178 // If this is a direct store to the global (i.e., the global is a scalar
179 // value, not an aggregate), keep more specific information about
180 // stores.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000181 if (GS.StoredType != GlobalStatus::isStored) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000182 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000183 Value *StoredVal = SI->getOperand(0);
184 if (StoredVal == GV->getInitializer()) {
185 if (GS.StoredType < GlobalStatus::isInitializerStored)
186 GS.StoredType = GlobalStatus::isInitializerStored;
187 } else if (isa<LoadInst>(StoredVal) &&
188 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
189 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000190 if (GS.StoredType < GlobalStatus::isInitializerStored)
191 GS.StoredType = GlobalStatus::isInitializerStored;
192 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
193 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000194 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000195 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000196 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000197 // noop.
198 } else {
199 GS.StoredType = GlobalStatus::isStored;
200 }
201 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000202 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000203 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000204 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000205 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000206 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000207 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000208 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000209 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
210 // PHI nodes we can check just like select or GEP instructions, but we
211 // have to be careful about infinite recursion.
212 if (PHIUsers.insert(PN).second) // Not already visited.
213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000214 GS.HasPHIUser = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000215 } else if (isa<CmpInst>(I)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000216 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
217 if (I->getOperand(1) == V)
218 GS.StoredType = GlobalStatus::isStored;
219 if (I->getOperand(2) == V)
220 GS.isLoaded = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000221 } else if (isa<MemSetInst>(I)) {
222 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
223 GS.StoredType = GlobalStatus::isStored;
Chris Lattner7a90b682004-10-07 04:16:33 +0000224 } else {
225 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000226 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000227 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000228 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000229 // We might have a dead and dangling constant hanging off of here.
230 if (!ConstantIsDead(C))
231 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000232 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000233 GS.HasNonInstructionUser = true;
234 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000235 return true;
236 }
237
238 return false;
239}
240
Chris Lattner670c8892004-10-08 17:32:09 +0000241static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
242 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
243 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000244 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000245
Chris Lattner670c8892004-10-08 17:32:09 +0000246 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
247 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
248 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
249 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000250 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000251 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000252 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000253 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
254 if (IdxV < STy->getNumElements())
255 return Constant::getNullValue(STy->getElementType(IdxV));
256 } else if (const SequentialType *STy =
257 dyn_cast<SequentialType>(Agg->getType())) {
258 return Constant::getNullValue(STy->getElementType());
259 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000260 } else if (isa<UndefValue>(Agg)) {
261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
263 return UndefValue::get(STy->getElementType(IdxV));
264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
266 return UndefValue::get(STy->getElementType());
267 }
Chris Lattner670c8892004-10-08 17:32:09 +0000268 }
269 return 0;
270}
Chris Lattner7a90b682004-10-07 04:16:33 +0000271
Chris Lattner7a90b682004-10-07 04:16:33 +0000272
Chris Lattnere47ba742004-10-06 20:57:02 +0000273/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
274/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000275/// quick scan over the use list to clean up the easy and obvious cruft. This
276/// returns true if it made a change.
277static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
278 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000279 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
280 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000281
Chris Lattner7a90b682004-10-07 04:16:33 +0000282 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000283 if (Init) {
284 // Replace the load with the initializer.
285 LI->replaceAllUsesWith(Init);
286 LI->eraseFromParent();
287 Changed = true;
288 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000289 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000290 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000291 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000292 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000293 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
294 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000295 Constant *SubInit = 0;
296 if (Init)
297 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000298 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000299 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000300 isa<PointerType>(CE->getType())) {
301 // Pointer cast, delete any stores and memsets to the global.
302 Changed |= CleanupConstantGlobalUsers(CE, 0);
303 }
304
305 if (CE->use_empty()) {
306 CE->destroyConstant();
307 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000308 }
309 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner7b52fe72007-11-09 17:33:02 +0000310 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
311 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
312 // and will invalidate our notion of what Init is.
Chris Lattner19450242007-11-13 21:46:23 +0000313 Constant *SubInit = 0;
Chris Lattner7b52fe72007-11-09 17:33:02 +0000314 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
315 ConstantExpr *CE =
316 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
317 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner19450242007-11-13 21:46:23 +0000318 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner7b52fe72007-11-09 17:33:02 +0000319 }
Chris Lattner19450242007-11-13 21:46:23 +0000320 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000321
Chris Lattner031955d2004-10-10 16:43:46 +0000322 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000323 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000324 Changed = true;
325 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000326 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
327 if (MI->getRawDest() == V) {
328 MI->eraseFromParent();
329 Changed = true;
330 }
331
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000332 } else if (Constant *C = dyn_cast<Constant>(U)) {
333 // If we have a chain of dead constantexprs or other things dangling from
334 // us, and if they are all dead, nuke them without remorse.
335 if (ConstantIsDead(C)) {
336 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000337 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000338 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000339 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000340 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000341 }
342 }
Chris Lattner031955d2004-10-10 16:43:46 +0000343 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000344}
345
Chris Lattner941db492008-01-14 02:09:12 +0000346/// isSafeSROAElementUse - Return true if the specified instruction is a safe
347/// user of a derived expression from a global that we want to SROA.
348static bool isSafeSROAElementUse(Value *V) {
349 // We might have a dead and dangling constant hanging off of here.
350 if (Constant *C = dyn_cast<Constant>(V))
351 return ConstantIsDead(C);
Chris Lattner727c2102008-01-14 01:31:05 +0000352
Chris Lattner941db492008-01-14 02:09:12 +0000353 Instruction *I = dyn_cast<Instruction>(V);
354 if (!I) return false;
355
356 // Loads are ok.
357 if (isa<LoadInst>(I)) return true;
358
359 // Stores *to* the pointer are ok.
360 if (StoreInst *SI = dyn_cast<StoreInst>(I))
361 return SI->getOperand(0) != V;
362
363 // Otherwise, it must be a GEP.
364 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
365 if (GEPI == 0) return false;
366
367 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
368 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
369 return false;
370
371 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
372 I != E; ++I)
373 if (!isSafeSROAElementUse(*I))
374 return false;
Chris Lattner727c2102008-01-14 01:31:05 +0000375 return true;
376}
377
Chris Lattner941db492008-01-14 02:09:12 +0000378
379/// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
380/// Look at it and its uses and decide whether it is safe to SROA this global.
381///
382static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
383 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
384 if (!isa<GetElementPtrInst>(U) &&
385 (!isa<ConstantExpr>(U) ||
386 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
387 return false;
388
389 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
390 // don't like < 3 operand CE's, and we don't like non-constant integer
391 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
392 // value of C.
393 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
394 !cast<Constant>(U->getOperand(1))->isNullValue() ||
395 !isa<ConstantInt>(U->getOperand(2)))
396 return false;
397
398 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
399 ++GEPI; // Skip over the pointer index.
400
401 // If this is a use of an array allocation, do a bit more checking for sanity.
402 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
403 uint64_t NumElements = AT->getNumElements();
404 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
405
406 // Check to make sure that index falls within the array. If not,
407 // something funny is going on, so we won't do the optimization.
408 //
409 if (Idx->getZExtValue() >= NumElements)
410 return false;
411
412 // We cannot scalar repl this level of the array unless any array
413 // sub-indices are in-range constants. In particular, consider:
414 // A[0][i]. We cannot know that the user isn't doing invalid things like
415 // allowing i to index an out-of-range subscript that accesses A[1].
416 //
417 // Scalar replacing *just* the outer index of the array is probably not
418 // going to be a win anyway, so just give up.
419 for (++GEPI; // Skip array index.
420 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
421 ++GEPI) {
422 uint64_t NumElements;
423 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
424 NumElements = SubArrayTy->getNumElements();
425 else
426 NumElements = cast<VectorType>(*GEPI)->getNumElements();
427
428 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
429 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
430 return false;
431 }
432 }
433
434 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
435 if (!isSafeSROAElementUse(*I))
436 return false;
437 return true;
438}
439
440/// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
441/// is safe for us to perform this transformation.
442///
443static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
444 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
445 UI != E; ++UI) {
446 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
447 return false;
448 }
449 return true;
450}
451
452
Chris Lattner670c8892004-10-08 17:32:09 +0000453/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
454/// variable. This opens the door for other optimizations by exposing the
455/// behavior of the program in a more fine-grained way. We have determined that
456/// this transformation is safe already. We return the first global variable we
457/// insert so that the caller can reprocess it.
458static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
Chris Lattner727c2102008-01-14 01:31:05 +0000459 // Make sure this global only has simple uses that we can SRA.
Chris Lattner941db492008-01-14 02:09:12 +0000460 if (!GlobalUsersSafeToSRA(GV))
Chris Lattner727c2102008-01-14 01:31:05 +0000461 return 0;
462
Chris Lattner670c8892004-10-08 17:32:09 +0000463 assert(GV->hasInternalLinkage() && !GV->isConstant());
464 Constant *Init = GV->getInitializer();
465 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000466
Chris Lattner670c8892004-10-08 17:32:09 +0000467 std::vector<GlobalVariable*> NewGlobals;
468 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
469
470 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
471 NewGlobals.reserve(STy->getNumElements());
472 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
473 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000474 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000475 assert(In && "Couldn't get element of initializer?");
476 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
477 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000478 In, GV->getName()+"."+utostr(i),
479 (Module *)NULL,
480 GV->isThreadLocal());
Chris Lattner670c8892004-10-08 17:32:09 +0000481 Globals.insert(GV, NGV);
482 NewGlobals.push_back(NGV);
483 }
484 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
485 unsigned NumElements = 0;
486 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
487 NumElements = ATy->getNumElements();
Reid Spencer9d6565a2007-02-15 02:26:10 +0000488 else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
Chris Lattner670c8892004-10-08 17:32:09 +0000489 NumElements = PTy->getNumElements();
490 else
491 assert(0 && "Unknown aggregate sequential type!");
492
Chris Lattner1f21ef12005-02-23 16:53:04 +0000493 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000494 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000495 NewGlobals.reserve(NumElements);
496 for (unsigned i = 0, e = NumElements; i != e; ++i) {
497 Constant *In = getAggregateConstantElement(Init,
Reid Spencerc5b206b2006-12-31 05:48:39 +0000498 ConstantInt::get(Type::Int32Ty, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000499 assert(In && "Couldn't get element of initializer?");
500
501 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
502 GlobalVariable::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000503 In, GV->getName()+"."+utostr(i),
504 (Module *)NULL,
505 GV->isThreadLocal());
Chris Lattner670c8892004-10-08 17:32:09 +0000506 Globals.insert(GV, NGV);
507 NewGlobals.push_back(NGV);
508 }
509 }
510
511 if (NewGlobals.empty())
512 return 0;
513
Bill Wendling0a81aac2006-11-26 10:02:32 +0000514 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000515
Reid Spencerc5b206b2006-12-31 05:48:39 +0000516 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattner670c8892004-10-08 17:32:09 +0000517
518 // Loop over all of the uses of the global, replacing the constantexpr geps,
519 // with smaller constantexpr geps or direct references.
520 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000521 User *GEP = GV->use_back();
522 assert(((isa<ConstantExpr>(GEP) &&
523 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
524 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000525
Chris Lattner670c8892004-10-08 17:32:09 +0000526 // Ignore the 1th operand, which has to be zero or else the program is quite
527 // broken (undefined). Get the 2nd operand, which is the structure or array
528 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000529 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000530 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
531
Chris Lattner30ba5692004-10-11 05:54:41 +0000532 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000533
534 // Form a shorter GEP if needed.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000535 if (GEP->getNumOperands() > 3) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000536 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
Chris Lattner55eb1c42007-01-31 04:40:53 +0000537 SmallVector<Constant*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000538 Idxs.push_back(NullInt);
539 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
540 Idxs.push_back(CE->getOperand(i));
Chris Lattner55eb1c42007-01-31 04:40:53 +0000541 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
542 &Idxs[0], Idxs.size());
Chris Lattner30ba5692004-10-11 05:54:41 +0000543 } else {
544 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
Chris Lattner699d1442007-01-31 19:59:55 +0000545 SmallVector<Value*, 8> Idxs;
Chris Lattner30ba5692004-10-11 05:54:41 +0000546 Idxs.push_back(NullInt);
547 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
548 Idxs.push_back(GEPI->getOperand(i));
David Greeneb8f74792007-09-04 15:46:09 +0000549 NewPtr = new GetElementPtrInst(NewPtr, Idxs.begin(), Idxs.end(),
Chris Lattner30ba5692004-10-11 05:54:41 +0000550 GEPI->getName()+"."+utostr(Val), GEPI);
551 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000552 }
Chris Lattner30ba5692004-10-11 05:54:41 +0000553 GEP->replaceAllUsesWith(NewPtr);
554
555 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000556 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000557 else
558 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000559 }
560
Chris Lattnere40e2d12004-10-08 20:25:55 +0000561 // Delete the old global, now that it is dead.
562 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000563 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000564
565 // Loop over the new globals array deleting any globals that are obviously
566 // dead. This can arise due to scalarization of a structure or an array that
567 // has elements that are dead.
568 unsigned FirstGlobal = 0;
569 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
570 if (NewGlobals[i]->use_empty()) {
571 Globals.erase(NewGlobals[i]);
572 if (FirstGlobal == i) ++FirstGlobal;
573 }
574
575 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000576}
577
Chris Lattner9b34a612004-10-09 21:48:45 +0000578/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
Chris Lattner81686182007-09-13 16:30:19 +0000579/// value will trap if the value is dynamically null. PHIs keeps track of any
580/// phi nodes we've seen to avoid reprocessing them.
581static bool AllUsesOfValueWillTrapIfNull(Value *V,
582 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner9b34a612004-10-09 21:48:45 +0000583 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
584 if (isa<LoadInst>(*UI)) {
585 // Will trap.
586 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
587 if (SI->getOperand(0) == V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000588 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000589 return false; // Storing the value.
590 }
591 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
592 if (CI->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000593 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000594 return false; // Not calling the ptr
595 }
596 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
597 if (II->getOperand(0) != V) {
Bill Wendlinge8156192006-12-07 01:30:32 +0000598 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000599 return false; // Not calling the ptr
600 }
Chris Lattner81686182007-09-13 16:30:19 +0000601 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
602 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
Chris Lattner9b34a612004-10-09 21:48:45 +0000603 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000604 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
605 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
606 // If we've already seen this phi node, ignore it, it has already been
607 // checked.
608 if (PHIs.insert(PN))
609 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000610 } else if (isa<ICmpInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000611 isa<ConstantPointerNull>(UI->getOperand(1))) {
612 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000613 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000614 //cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000615 return false;
616 }
617 return true;
618}
619
620/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000621/// from GV will trap if the loaded value is null. Note that this also permits
622/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000623static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
624 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
625 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
Chris Lattner81686182007-09-13 16:30:19 +0000626 SmallPtrSet<PHINode*, 8> PHIs;
627 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
Chris Lattner9b34a612004-10-09 21:48:45 +0000628 return false;
629 } else if (isa<StoreInst>(*UI)) {
630 // Ignore stores to the global.
631 } else {
632 // We don't know or understand this user, bail out.
Bill Wendlinge8156192006-12-07 01:30:32 +0000633 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000634 return false;
635 }
636
637 return true;
638}
639
Chris Lattner708148e2004-10-10 23:14:11 +0000640static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
641 bool Changed = false;
642 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
643 Instruction *I = cast<Instruction>(*UI++);
644 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
645 LI->setOperand(0, NewV);
646 Changed = true;
647 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
648 if (SI->getOperand(1) == V) {
649 SI->setOperand(1, NewV);
650 Changed = true;
651 }
652 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
653 if (I->getOperand(0) == V) {
654 // Calling through the pointer! Turn into a direct call, but be careful
655 // that the pointer is not also being passed as an argument.
656 I->setOperand(0, NewV);
657 Changed = true;
658 bool PassedAsArg = false;
659 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
660 if (I->getOperand(i) == V) {
661 PassedAsArg = true;
662 I->setOperand(i, NewV);
663 }
664
665 if (PassedAsArg) {
666 // Being passed as an argument also. Be careful to not invalidate UI!
667 UI = V->use_begin();
668 }
669 }
670 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
671 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000672 ConstantExpr::getCast(CI->getOpcode(),
673 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000674 if (CI->use_empty()) {
675 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000676 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000677 }
678 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
679 // Should handle GEP here.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000680 SmallVector<Constant*, 8> Idxs;
681 Idxs.reserve(GEPI->getNumOperands()-1);
Chris Lattner708148e2004-10-10 23:14:11 +0000682 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
683 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
Chris Lattner55eb1c42007-01-31 04:40:53 +0000684 Idxs.push_back(C);
Chris Lattner708148e2004-10-10 23:14:11 +0000685 else
686 break;
Chris Lattner55eb1c42007-01-31 04:40:53 +0000687 if (Idxs.size() == GEPI->getNumOperands()-1)
Chris Lattner708148e2004-10-10 23:14:11 +0000688 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
Chris Lattner55eb1c42007-01-31 04:40:53 +0000689 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
690 Idxs.size()));
Chris Lattner708148e2004-10-10 23:14:11 +0000691 if (GEPI->use_empty()) {
692 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000693 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000694 }
695 }
696 }
697
698 return Changed;
699}
700
701
702/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
703/// value stored into it. If there are uses of the loaded value that would trap
704/// if the loaded value is dynamically null, then we know that they cannot be
705/// reachable with a null optimize away the load.
706static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
707 std::vector<LoadInst*> Loads;
708 bool Changed = false;
709
710 // Replace all uses of loads with uses of uses of the stored value.
711 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
712 GUI != E; ++GUI)
713 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
714 Loads.push_back(LI);
715 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
716 } else {
Chris Lattnerce3e2bf2007-05-15 06:42:04 +0000717 // If we get here we could have stores, selects, or phi nodes whose values
Chris Lattner79cfddf2007-05-13 21:28:07 +0000718 // are loaded.
Chris Lattnerce3e2bf2007-05-15 06:42:04 +0000719 assert((isa<StoreInst>(*GUI) || isa<PHINode>(*GUI) ||
Chris Lattner9027b3c2008-01-04 05:04:53 +0000720 isa<SelectInst>(*GUI) || isa<ConstantExpr>(*GUI)) &&
Chris Lattner79cfddf2007-05-13 21:28:07 +0000721 "Only expect load and stores!");
Chris Lattner708148e2004-10-10 23:14:11 +0000722 }
723
724 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000725 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000726 ++NumGlobUses;
727 }
728
729 // Delete all of the loads we can, keeping track of whether we nuked them all!
730 bool AllLoadsGone = true;
731 while (!Loads.empty()) {
732 LoadInst *L = Loads.back();
733 if (L->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000734 L->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000735 Changed = true;
736 } else {
737 AllLoadsGone = false;
738 }
739 Loads.pop_back();
740 }
741
742 // If we nuked all of the loads, then none of the stores are needed either,
743 // nor is the global.
744 if (AllLoadsGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000745 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000746 CleanupConstantGlobalUsers(GV, 0);
747 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000748 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000749 ++NumDeleted;
750 }
751 Changed = true;
752 }
753 return Changed;
754}
755
Chris Lattner30ba5692004-10-11 05:54:41 +0000756/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
757/// instructions that are foldable.
758static void ConstantPropUsersOf(Value *V) {
759 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
760 if (Instruction *I = dyn_cast<Instruction>(*UI++))
761 if (Constant *NewC = ConstantFoldInstruction(I)) {
762 I->replaceAllUsesWith(NewC);
763
Chris Lattnerd514d822005-02-01 01:23:31 +0000764 // Advance UI to the next non-I use to avoid invalidating it!
765 // Instructions could multiply use V.
766 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000767 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000768 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000769 }
770}
771
772/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
773/// variable, and transforms the program as if it always contained the result of
774/// the specified malloc. Because it is always the result of the specified
775/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000776/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000777static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
778 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000779 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000780 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
781
Reid Spencerb83eb642006-10-20 07:07:24 +0000782 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000783 // If we have an array allocation, transform it to a single element
784 // allocation to make the code below simpler.
785 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000786 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000787 MallocInst *NewMI =
Reid Spencerc5b206b2006-12-31 05:48:39 +0000788 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
Nate Begeman14b05292005-11-05 09:21:28 +0000789 MI->getAlignment(), MI->getName(), MI);
Chris Lattner699d1442007-01-31 19:59:55 +0000790 Value* Indices[2];
791 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +0000792 Value *NewGEP = new GetElementPtrInst(NewMI, Indices, Indices + 2,
Chris Lattner30ba5692004-10-11 05:54:41 +0000793 NewMI->getName()+".el0", MI);
794 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000795 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000796 MI = NewMI;
797 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000798
Chris Lattner7a7ed022004-10-16 18:09:00 +0000799 // Create the new global variable. The contents of the malloc'd memory is
800 // undefined, so initialize with an undef value.
801 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000802 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
803 GlobalValue::InternalLinkage, Init,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000804 GV->getName()+".body",
805 (Module *)NULL,
806 GV->isThreadLocal());
Chris Lattner30ba5692004-10-11 05:54:41 +0000807 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000808
Chris Lattner30ba5692004-10-11 05:54:41 +0000809 // Anything that used the malloc now uses the global directly.
810 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000811
812 Constant *RepValue = NewGV;
813 if (NewGV->getType() != GV->getType()->getElementType())
Reid Spencerd977d862006-12-12 23:36:14 +0000814 RepValue = ConstantExpr::getBitCast(RepValue,
815 GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000816
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000817 // If there is a comparison against null, we will insert a global bool to
818 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000819 GlobalVariable *InitBool =
Reid Spencer4fe16d62007-01-11 18:21:29 +0000820 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +0000821 ConstantInt::getFalse(), GV->getName()+".init",
822 (Module *)NULL, GV->isThreadLocal());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000823 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000824
Chris Lattner30ba5692004-10-11 05:54:41 +0000825 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000826 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000827 while (!GV->use_empty())
828 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000829 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000830 Use &LoadUse = LI->use_begin().getUse();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000831 if (!isa<ICmpInst>(LoadUse.getUser()))
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000832 LoadUse = RepValue;
833 else {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000834 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
835 // Replace the cmp X, 0 with a use of the bool value.
836 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000837 InitBoolUsed = true;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000838 switch (CI->getPredicate()) {
839 default: assert(0 && "Unknown ICmp Predicate!");
840 case ICmpInst::ICMP_ULT:
841 case ICmpInst::ICMP_SLT:
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000842 LV = ConstantInt::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000843 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000844 case ICmpInst::ICMP_ULE:
845 case ICmpInst::ICMP_SLE:
846 case ICmpInst::ICMP_EQ:
847 LV = BinaryOperator::createNot(LV, "notinit", CI);
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000848 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000849 case ICmpInst::ICMP_NE:
850 case ICmpInst::ICMP_UGE:
851 case ICmpInst::ICMP_SGE:
852 case ICmpInst::ICMP_UGT:
853 case ICmpInst::ICMP_SGT:
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000854 break; // no change.
855 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000856 CI->replaceAllUsesWith(LV);
857 CI->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000858 }
859 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000860 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000861 } else {
862 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000863 // The global is initialized when the store to it occurs.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000864 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000865 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000866 }
867
Chris Lattnerbc965b92004-12-02 06:25:58 +0000868 // If the initialization boolean was used, insert it, otherwise delete it.
869 if (!InitBoolUsed) {
870 while (!InitBool->use_empty()) // Delete initializations
871 cast<Instruction>(InitBool->use_back())->eraseFromParent();
872 delete InitBool;
873 } else
874 GV->getParent()->getGlobalList().insert(GV, InitBool);
875
876
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000877 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000878 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000879 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000880
881 // To further other optimizations, loop over all users of NewGV and try to
882 // constant prop them. This will promote GEP instructions with constant
883 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
884 ConstantPropUsersOf(NewGV);
885 if (RepValue != NewGV)
886 ConstantPropUsersOf(RepValue);
887
888 return NewGV;
889}
Chris Lattner708148e2004-10-10 23:14:11 +0000890
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000891/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
892/// to make sure that there are no complex uses of V. We permit simple things
893/// like dereferencing the pointer, but not storing through the address, unless
894/// it is to the specified global.
895static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000896 GlobalVariable *GV,
897 SmallPtrSet<PHINode*, 8> &PHIs) {
Chris Lattner5e6e4942007-09-14 03:41:21 +0000898 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
Reid Spencere4d87aa2006-12-23 06:05:41 +0000899 if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000900 // Fine, ignore.
901 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
902 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
903 return false; // Storing the pointer itself... bad.
904 // Otherwise, storing through it, or storing into GV... fine.
Chris Lattner5e6e4942007-09-14 03:41:21 +0000905 } else if (isa<GetElementPtrInst>(*UI)) {
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000906 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),
907 GV, PHIs))
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000908 return false;
Chris Lattnerc451f9c2007-09-13 16:37:20 +0000909 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
910 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
911 // cycles.
912 if (PHIs.insert(PN))
Chris Lattner5e6e4942007-09-14 03:41:21 +0000913 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
914 return false;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000915 } else {
916 return false;
917 }
918 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000919}
920
Chris Lattner86395032006-09-30 23:32:09 +0000921/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
922/// somewhere. Transform all uses of the allocation into loads from the
923/// global and uses of the resultant pointer. Further, delete the store into
924/// GV. This assumes that these value pass the
925/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
926static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
927 GlobalVariable *GV) {
928 while (!Alloc->use_empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +0000929 Instruction *U = cast<Instruction>(*Alloc->use_begin());
930 Instruction *InsertPt = U;
Chris Lattner86395032006-09-30 23:32:09 +0000931 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
932 // If this is the store of the allocation into the global, remove it.
933 if (SI->getOperand(1) == GV) {
934 SI->eraseFromParent();
935 continue;
936 }
Chris Lattnera637a8b2007-09-13 18:00:31 +0000937 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
938 // Insert the load in the corresponding predecessor, not right before the
939 // PHI.
940 unsigned PredNo = Alloc->use_begin().getOperandNo()/2;
941 InsertPt = PN->getIncomingBlock(PredNo)->getTerminator();
Chris Lattner86395032006-09-30 23:32:09 +0000942 }
943
944 // Insert a load from the global, and use it instead of the malloc.
Chris Lattnera637a8b2007-09-13 18:00:31 +0000945 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
Chris Lattner86395032006-09-30 23:32:09 +0000946 U->replaceUsesOfWith(Alloc, NL);
947 }
948}
949
950/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
951/// GV are simple enough to perform HeapSRA, return true.
Chris Lattner309f20f2007-09-13 21:31:36 +0000952static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
953 MallocInst *MI) {
Chris Lattner86395032006-09-30 23:32:09 +0000954 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
955 ++UI)
956 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
957 // We permit two users of the load: setcc comparing against the null
958 // pointer, and a getelementptr of a specific form.
959 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
960 ++UI) {
961 // Comparison against null is ok.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000962 if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
963 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
Chris Lattner86395032006-09-30 23:32:09 +0000964 return false;
965 continue;
966 }
967
968 // getelementptr is also ok, but only a simple form.
Chris Lattner309f20f2007-09-13 21:31:36 +0000969 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
970 // Must index into the array and into the struct.
971 if (GEPI->getNumOperands() < 3)
972 return false;
973
974 // Otherwise the GEP is ok.
975 continue;
976 }
Chris Lattner86395032006-09-30 23:32:09 +0000977
Chris Lattner309f20f2007-09-13 21:31:36 +0000978 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
979 // We have a phi of a load from the global. We can only handle this
980 // if the other PHI'd values are actually the same. In this case,
981 // the rewriter will just drop the phi entirely.
982 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
983 Value *IV = PN->getIncomingValue(i);
984 if (IV == LI) continue; // Trivial the same.
985
986 // If the phi'd value is from the malloc that initializes the value,
987 // we can xform it.
988 if (IV == MI) continue;
989
990 // Otherwise, we don't know what it is.
991 return false;
992 }
993 return true;
994 }
Chris Lattner86395032006-09-30 23:32:09 +0000995
Chris Lattner309f20f2007-09-13 21:31:36 +0000996 // Otherwise we don't know what this is, not ok.
997 return false;
Chris Lattner86395032006-09-30 23:32:09 +0000998 }
999 }
1000 return true;
1001}
1002
Chris Lattnera637a8b2007-09-13 18:00:31 +00001003/// GetHeapSROALoad - Return the load for the specified field of the HeapSROA'd
1004/// value, lazily creating it on demand.
Chris Lattner309f20f2007-09-13 21:31:36 +00001005static Value *GetHeapSROALoad(Instruction *Load, unsigned FieldNo,
Chris Lattnera637a8b2007-09-13 18:00:31 +00001006 const std::vector<GlobalVariable*> &FieldGlobals,
1007 std::vector<Value *> &InsertedLoadsForPtr) {
1008 if (InsertedLoadsForPtr.size() <= FieldNo)
1009 InsertedLoadsForPtr.resize(FieldNo+1);
1010 if (InsertedLoadsForPtr[FieldNo] == 0)
1011 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
1012 Load->getName()+".f" +
1013 utostr(FieldNo), Load);
1014 return InsertedLoadsForPtr[FieldNo];
1015}
1016
Chris Lattner330245e2007-09-13 17:29:05 +00001017/// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1018/// the load, rewrite the derived value to use the HeapSRoA'd load.
1019static void RewriteHeapSROALoadUser(LoadInst *Load, Instruction *LoadUser,
1020 const std::vector<GlobalVariable*> &FieldGlobals,
1021 std::vector<Value *> &InsertedLoadsForPtr) {
1022 // If this is a comparison against null, handle it.
1023 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1024 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1025 // If we have a setcc of the loaded pointer, we can use a setcc of any
1026 // field.
1027 Value *NPtr;
1028 if (InsertedLoadsForPtr.empty()) {
Chris Lattnera637a8b2007-09-13 18:00:31 +00001029 NPtr = GetHeapSROALoad(Load, 0, FieldGlobals, InsertedLoadsForPtr);
Chris Lattner330245e2007-09-13 17:29:05 +00001030 } else {
1031 NPtr = InsertedLoadsForPtr.back();
1032 }
1033
1034 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
1035 Constant::getNullValue(NPtr->getType()),
1036 SCI->getName(), SCI);
1037 SCI->replaceAllUsesWith(New);
1038 SCI->eraseFromParent();
1039 return;
1040 }
1041
Chris Lattnera637a8b2007-09-13 18:00:31 +00001042 // Handle 'getelementptr Ptr, Idx, uint FieldNo ...'
1043 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1044 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1045 && "Unexpected GEPI!");
Chris Lattner330245e2007-09-13 17:29:05 +00001046
Chris Lattnera637a8b2007-09-13 18:00:31 +00001047 // Load the pointer for this field.
1048 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1049 Value *NewPtr = GetHeapSROALoad(Load, FieldNo,
1050 FieldGlobals, InsertedLoadsForPtr);
1051
1052 // Create the new GEP idx vector.
1053 SmallVector<Value*, 8> GEPIdx;
1054 GEPIdx.push_back(GEPI->getOperand(1));
1055 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1056
1057 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx.begin(), GEPIdx.end(),
1058 GEPI->getName(), GEPI);
1059 GEPI->replaceAllUsesWith(NGEPI);
1060 GEPI->eraseFromParent();
1061 return;
1062 }
Chris Lattner330245e2007-09-13 17:29:05 +00001063
Chris Lattner309f20f2007-09-13 21:31:36 +00001064 // Handle PHI nodes. PHI nodes must be merging in the same values, plus
1065 // potentially the original malloc. Insert phi nodes for each field, then
1066 // process uses of the PHI.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001067 PHINode *PN = cast<PHINode>(LoadUser);
Chris Lattner309f20f2007-09-13 21:31:36 +00001068 std::vector<Value *> PHIsForField;
1069 PHIsForField.resize(FieldGlobals.size());
1070 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1071 Value *LoadV = GetHeapSROALoad(Load, i, FieldGlobals, InsertedLoadsForPtr);
1072
1073 PHINode *FieldPN = new PHINode(LoadV->getType(),
1074 PN->getName()+"."+utostr(i), PN);
1075 // Fill in the predecessor values.
1076 for (unsigned pred = 0, e = PN->getNumIncomingValues(); pred != e; ++pred) {
1077 // Each predecessor either uses the load or the original malloc.
1078 Value *InVal = PN->getIncomingValue(pred);
1079 BasicBlock *BB = PN->getIncomingBlock(pred);
1080 Value *NewVal;
1081 if (isa<MallocInst>(InVal)) {
1082 // Insert a reload from the global in the predecessor.
1083 NewVal = GetHeapSROALoad(BB->getTerminator(), i, FieldGlobals,
1084 PHIsForField);
1085 } else {
1086 NewVal = InsertedLoadsForPtr[i];
1087 }
1088 FieldPN->addIncoming(NewVal, BB);
1089 }
1090 PHIsForField[i] = FieldPN;
1091 }
1092
1093 // Since PHIsForField specifies a phi for every input value, the lazy inserter
1094 // will never insert a load.
Chris Lattnera637a8b2007-09-13 18:00:31 +00001095 while (!PN->use_empty())
Chris Lattner309f20f2007-09-13 21:31:36 +00001096 RewriteHeapSROALoadUser(Load, PN->use_back(), FieldGlobals, PHIsForField);
Chris Lattnera637a8b2007-09-13 18:00:31 +00001097 PN->eraseFromParent();
Chris Lattner330245e2007-09-13 17:29:05 +00001098}
1099
Chris Lattner86395032006-09-30 23:32:09 +00001100/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1101/// is a value loaded from the global. Eliminate all uses of Ptr, making them
1102/// use FieldGlobals instead. All uses of loaded values satisfy
1103/// GlobalLoadUsesSimpleEnoughForHeapSRA.
Chris Lattner330245e2007-09-13 17:29:05 +00001104static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
Chris Lattner86395032006-09-30 23:32:09 +00001105 const std::vector<GlobalVariable*> &FieldGlobals) {
1106 std::vector<Value *> InsertedLoadsForPtr;
1107 //InsertedLoadsForPtr.resize(FieldGlobals.size());
Chris Lattner330245e2007-09-13 17:29:05 +00001108 while (!Load->use_empty())
1109 RewriteHeapSROALoadUser(Load, Load->use_back(),
1110 FieldGlobals, InsertedLoadsForPtr);
Chris Lattner86395032006-09-30 23:32:09 +00001111}
1112
1113/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1114/// it up into multiple allocations of arrays of the fields.
1115static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +00001116 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +00001117 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1118
1119 // There is guaranteed to be at least one use of the malloc (storing
1120 // it into GV). If there are other uses, change them to be uses of
1121 // the global to simplify later code. This also deletes the store
1122 // into GV.
1123 ReplaceUsesOfMallocWithGlobal(MI, GV);
1124
1125 // Okay, at this point, there are no users of the malloc. Insert N
1126 // new mallocs at the same place as MI, and N globals.
1127 std::vector<GlobalVariable*> FieldGlobals;
1128 std::vector<MallocInst*> FieldMallocs;
1129
1130 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1131 const Type *FieldTy = STy->getElementType(FieldNo);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001132 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
Chris Lattner86395032006-09-30 23:32:09 +00001133
1134 GlobalVariable *NGV =
1135 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1136 Constant::getNullValue(PFieldTy),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001137 GV->getName() + ".f" + utostr(FieldNo), GV,
1138 GV->isThreadLocal());
Chris Lattner86395032006-09-30 23:32:09 +00001139 FieldGlobals.push_back(NGV);
1140
1141 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1142 MI->getName() + ".f" + utostr(FieldNo),MI);
1143 FieldMallocs.push_back(NMI);
1144 new StoreInst(NMI, NGV, MI);
1145 }
1146
1147 // The tricky aspect of this transformation is handling the case when malloc
1148 // fails. In the original code, malloc failing would set the result pointer
1149 // of malloc to null. In this case, some mallocs could succeed and others
1150 // could fail. As such, we emit code that looks like this:
1151 // F0 = malloc(field0)
1152 // F1 = malloc(field1)
1153 // F2 = malloc(field2)
1154 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1155 // if (F0) { free(F0); F0 = 0; }
1156 // if (F1) { free(F1); F1 = 0; }
1157 // if (F2) { free(F2); F2 = 0; }
1158 // }
1159 Value *RunningOr = 0;
1160 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001161 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Chris Lattner86395032006-09-30 23:32:09 +00001162 Constant::getNullValue(FieldMallocs[i]->getType()),
1163 "isnull", MI);
1164 if (!RunningOr)
1165 RunningOr = Cond; // First seteq
1166 else
1167 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
1168 }
1169
1170 // Split the basic block at the old malloc.
1171 BasicBlock *OrigBB = MI->getParent();
1172 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1173
1174 // Create the block to check the first condition. Put all these blocks at the
1175 // end of the function as they are unlikely to be executed.
1176 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
1177 OrigBB->getParent());
1178
1179 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1180 // branch on RunningOr.
1181 OrigBB->getTerminator()->eraseFromParent();
1182 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
1183
1184 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1185 // pointer, because some may be null while others are not.
1186 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1187 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001188 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1189 Constant::getNullValue(GVVal->getType()),
1190 "tmp", NullPtrBlock);
Chris Lattner86395032006-09-30 23:32:09 +00001191 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1192 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1193 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1194
1195 // Fill in FreeBlock.
1196 new FreeInst(GVVal, FreeBlock);
1197 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1198 FreeBlock);
1199 new BranchInst(NextBlock, FreeBlock);
1200
1201 NullPtrBlock = NextBlock;
1202 }
1203
1204 new BranchInst(ContBB, NullPtrBlock);
1205
1206
1207 // MI is no longer needed, remove it.
1208 MI->eraseFromParent();
1209
1210
1211 // Okay, the malloc site is completely handled. All of the uses of GV are now
1212 // loads, and all uses of those loads are simple. Rewrite them to use loads
1213 // of the per-field globals instead.
1214 while (!GV->use_empty()) {
Chris Lattner39ff1e22007-01-09 23:29:37 +00001215 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1216 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1217 LI->eraseFromParent();
1218 } else {
1219 // Must be a store of null.
1220 StoreInst *SI = cast<StoreInst>(GV->use_back());
1221 assert(isa<Constant>(SI->getOperand(0)) &&
1222 cast<Constant>(SI->getOperand(0))->isNullValue() &&
1223 "Unexpected heap-sra user!");
1224
1225 // Insert a store of null into each global.
1226 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1227 Constant *Null =
1228 Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1229 new StoreInst(Null, FieldGlobals[i], SI);
1230 }
1231 // Erase the original store.
1232 SI->eraseFromParent();
1233 }
Chris Lattner86395032006-09-30 23:32:09 +00001234 }
1235
1236 // The old global is now dead, remove it.
1237 GV->eraseFromParent();
1238
1239 ++NumHeapSRA;
1240 return FieldGlobals[0];
1241}
1242
1243
Chris Lattner9b34a612004-10-09 21:48:45 +00001244// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1245// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001246static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001247 Module::global_iterator &GVI,
1248 TargetData &TD) {
Chris Lattner9b34a612004-10-09 21:48:45 +00001249 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1250 StoredOnceVal = CI->getOperand(0);
1251 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattner708148e2004-10-10 23:14:11 +00001252 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner9b34a612004-10-09 21:48:45 +00001253 bool IsJustACast = true;
1254 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1255 if (!isa<Constant>(GEPI->getOperand(i)) ||
1256 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1257 IsJustACast = false;
1258 break;
1259 }
1260 if (IsJustACast)
1261 StoredOnceVal = GEPI->getOperand(0);
1262 }
1263
Chris Lattner708148e2004-10-10 23:14:11 +00001264 // If we are dealing with a pointer global that is initialized to null and
1265 // only has one (non-null) value stored into it, then we can optimize any
1266 // users of the loaded value (often calls and loads) that would trap if the
1267 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001268 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1269 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001270 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1271 if (GV->getInitializer()->getType() != SOVC->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001272 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001273
Chris Lattner708148e2004-10-10 23:14:11 +00001274 // Optimize away any trapping uses of the loaded value.
1275 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001276 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001277 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001278 // If this is a malloc of an abstract type, don't touch it.
1279 if (!MI->getAllocatedType()->isSized())
1280 return false;
1281
Chris Lattner86395032006-09-30 23:32:09 +00001282 // We can't optimize this global unless all uses of it are *known* to be
1283 // of the malloc value, not of the null initializer value (consider a use
1284 // that compares the global's value against zero to see if the malloc has
1285 // been reached). To do this, we check to see if all uses of the global
1286 // would trap if the global were null: this proves that they must all
1287 // happen after the malloc.
1288 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1289 return false;
1290
1291 // We can't optimize this if the malloc itself is used in a complex way,
1292 // for example, being stored into multiple globals. This allows the
1293 // malloc to be stored into the specified global, loaded setcc'd, and
1294 // GEP'd. These are all things we could transform to using the global
1295 // for.
Chris Lattnerc451f9c2007-09-13 16:37:20 +00001296 {
1297 SmallPtrSet<PHINode*, 8> PHIs;
1298 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1299 return false;
1300 }
Chris Lattner86395032006-09-30 23:32:09 +00001301
1302
Chris Lattner30ba5692004-10-11 05:54:41 +00001303 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner86395032006-09-30 23:32:09 +00001304 // transform the program to use global memory instead of malloc'd memory.
1305 // This eliminates dynamic allocation, avoids an indirection accessing the
1306 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattnercff16732006-09-30 19:40:30 +00001307 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner86395032006-09-30 23:32:09 +00001308 // Restrict this transformation to only working on small allocations
1309 // (2048 bytes currently), as we don't want to introduce a 16M global or
1310 // something.
Reid Spencerb83eb642006-10-20 07:07:24 +00001311 if (NElements->getZExtValue()*
Duncan Sands514ab342007-11-01 20:53:16 +00001312 TD.getABITypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001313 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1314 return true;
1315 }
Chris Lattnercff16732006-09-30 19:40:30 +00001316 }
Chris Lattner86395032006-09-30 23:32:09 +00001317
1318 // If the allocation is an array of structures, consider transforming this
1319 // into multiple malloc'd arrays, one for each field. This is basically
1320 // SRoA for malloc'd memory.
1321 if (const StructType *AllocTy =
1322 dyn_cast<StructType>(MI->getAllocatedType())) {
1323 // This the structure has an unreasonable number of fields, leave it
1324 // alone.
1325 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
Chris Lattner309f20f2007-09-13 21:31:36 +00001326 GlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
Chris Lattner86395032006-09-30 23:32:09 +00001327 GVI = PerformHeapAllocSRoA(GV, MI);
1328 return true;
1329 }
1330 }
Chris Lattner708148e2004-10-10 23:14:11 +00001331 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001332 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001333
Chris Lattner9b34a612004-10-09 21:48:45 +00001334 return false;
1335}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001336
Chris Lattner58e44f42008-01-14 01:17:44 +00001337/// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1338/// two values ever stored into GV are its initializer and OtherVal. See if we
1339/// can shrink the global into a boolean and select between the two values
1340/// whenever it is used. This exposes the values to other scalar optimizations.
1341static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1342 const Type *GVElType = GV->getType()->getElementType();
1343
1344 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1345 // an FP value or vector, don't do this optimization because a select between
1346 // them is very expensive and unlikely to lead to later simplification.
1347 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
1348 isa<VectorType>(GVElType))
1349 return false;
1350
1351 // Walk the use list of the global seeing if all the uses are load or store.
1352 // If there is anything else, bail out.
1353 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1354 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1355 return false;
1356
1357 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1358
Chris Lattner96a86b22004-12-12 05:53:50 +00001359 // Create the new global, initializing it to false.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001360 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001361 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001362 GV->getName()+".b",
1363 (Module *)NULL,
1364 GV->isThreadLocal());
Chris Lattner96a86b22004-12-12 05:53:50 +00001365 GV->getParent()->getGlobalList().insert(GV, NewGV);
1366
1367 Constant *InitVal = GV->getInitializer();
Reid Spencer4fe16d62007-01-11 18:21:29 +00001368 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
Chris Lattner96a86b22004-12-12 05:53:50 +00001369
1370 // If initialized to zero and storing one into the global, we can use a cast
1371 // instead of a select to synthesize the desired value.
1372 bool IsOneZero = false;
1373 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
Reid Spencercae57542007-03-02 00:28:52 +00001374 IsOneZero = InitVal->isNullValue() && CI->isOne();
Chris Lattner96a86b22004-12-12 05:53:50 +00001375
1376 while (!GV->use_empty()) {
1377 Instruction *UI = cast<Instruction>(GV->use_back());
1378 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1379 // Change the store into a boolean store.
1380 bool StoringOther = SI->getOperand(0) == OtherVal;
1381 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001382 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001383 if (StoringOther || SI->getOperand(0) == InitVal)
Reid Spencer579dca12007-01-12 04:24:46 +00001384 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
Chris Lattner38c25562004-12-12 19:34:41 +00001385 else {
1386 // Otherwise, we are storing a previously loaded copy. To do this,
1387 // change the copy from copying the original value to just copying the
1388 // bool.
1389 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1390
1391 // If we're already replaced the input, StoredVal will be a cast or
1392 // select instruction. If not, it will be a load of the original
1393 // global.
1394 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1395 assert(LI->getOperand(0) == GV && "Not a copy!");
1396 // Insert a new load, to preserve the saved value.
1397 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1398 } else {
1399 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1400 "This is not a form that we understand!");
1401 StoreVal = StoredVal->getOperand(0);
1402 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1403 }
1404 }
1405 new StoreInst(StoreVal, NewGV, SI);
Chris Lattner58e44f42008-01-14 01:17:44 +00001406 } else {
Chris Lattner96a86b22004-12-12 05:53:50 +00001407 // Change the load into a load of bool then a select.
1408 LoadInst *LI = cast<LoadInst>(UI);
Chris Lattner046800a2007-02-11 01:08:35 +00001409 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001410 Value *NSI;
1411 if (IsOneZero)
Chris Lattner046800a2007-02-11 01:08:35 +00001412 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001413 else
Chris Lattner046800a2007-02-11 01:08:35 +00001414 NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1415 NSI->takeName(LI);
Chris Lattner96a86b22004-12-12 05:53:50 +00001416 LI->replaceAllUsesWith(NSI);
1417 }
1418 UI->eraseFromParent();
1419 }
1420
1421 GV->eraseFromParent();
Chris Lattner58e44f42008-01-14 01:17:44 +00001422 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001423}
1424
1425
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001426/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1427/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001428bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001429 Module::global_iterator &GVI) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001430 std::set<PHINode*> PHIUsers;
1431 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001432 GV->removeDeadConstantUsers();
1433
1434 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001435 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001436 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001437 ++NumDeleted;
1438 return true;
1439 }
1440
1441 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001442#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001443 cerr << "Global: " << *GV;
1444 cerr << " isLoaded = " << GS.isLoaded << "\n";
1445 cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001446 switch (GS.StoredType) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001447 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1448 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1449 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1450 case GlobalStatus::isStored: cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001451 }
1452 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendlinge8156192006-12-07 01:30:32 +00001453 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001454 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendlinge8156192006-12-07 01:30:32 +00001455 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001456 << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001457 cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001458 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001459 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
Bill Wendlinge8156192006-12-07 01:30:32 +00001460 cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001461#endif
1462
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001463 // If this is a first class global and has only one accessing function
1464 // and this function is main (which we know is not recursive we can make
1465 // this global a local variable) we replace the global with a local alloca
1466 // in this function.
1467 //
1468 // NOTE: It doesn't make sense to promote non first class types since we
1469 // are just replacing static memory to stack memory.
1470 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001471 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001472 GV->getType()->getElementType()->isFirstClassType() &&
1473 GS.AccessingFunction->getName() == "main" &&
1474 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001475 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001476 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1477 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001478 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001479 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1480 if (!isa<UndefValue>(GV->getInitializer()))
1481 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001482
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001483 GV->replaceAllUsesWith(Alloca);
1484 GV->eraseFromParent();
1485 ++NumLocalized;
1486 return true;
1487 }
Chris Lattnercff16732006-09-30 19:40:30 +00001488
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001489 // If the global is never loaded (but may be stored to), it is dead.
1490 // Delete it now.
1491 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001492 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001493
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001494 // Delete any stores we can find to the global. We may not be able to
1495 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001496 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001497
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001498 // If the global is dead now, delete it.
1499 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001500 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001501 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001502 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001503 }
Chris Lattner930f4752004-10-09 03:32:52 +00001504 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001505
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001506 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001507 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001508 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001509
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001510 // Clean up any obviously simplifiable users now.
1511 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001512
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001513 // If the global is dead now, just nuke it.
1514 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001515 DOUT << " *** Marking constant allowed us to simplify "
1516 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001517 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001518 ++NumDeleted;
1519 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001520
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001521 ++NumMarked;
1522 return true;
Chris Lattner727c2102008-01-14 01:31:05 +00001523 } else if (!GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001524 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1525 GVI = FirstNewGV; // Don't skip the newly produced globals!
1526 return true;
1527 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001528 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001529 // If the initial value for the global was an undef value, and if only
1530 // one other value was stored into it, we can just change the
1531 // initializer to be an undef value, then delete all stores to the
1532 // global. This allows us to mark it constant.
1533 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1534 if (isa<UndefValue>(GV->getInitializer())) {
1535 // Change the initial value here.
1536 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001537
Chris Lattner96a86b22004-12-12 05:53:50 +00001538 // Clean up any obviously simplifiable users now.
1539 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001540
Chris Lattner96a86b22004-12-12 05:53:50 +00001541 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001542 DOUT << " *** Substituting initializer allowed us to "
1543 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001544 GV->eraseFromParent();
1545 ++NumDeleted;
1546 } else {
1547 GVI = GV;
1548 }
1549 ++NumSubstitute;
1550 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001551 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001552
Chris Lattner9b34a612004-10-09 21:48:45 +00001553 // Try to optimize globals based on the knowledge that only one value
1554 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001555 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1556 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001557 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001558
1559 // Otherwise, if the global was not a boolean, we can shrink it to be a
1560 // boolean.
1561 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner58e44f42008-01-14 01:17:44 +00001562 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001563 ++NumShrunkToBool;
1564 return true;
1565 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001566 }
1567 }
1568 return false;
1569}
1570
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001571/// OnlyCalledDirectly - Return true if the specified function is only called
1572/// directly. In other words, its address is never taken.
1573static bool OnlyCalledDirectly(Function *F) {
1574 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1575 Instruction *User = dyn_cast<Instruction>(*UI);
1576 if (!User) return false;
1577 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1578
1579 // See if the function address is passed as an argument.
1580 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1581 if (User->getOperand(i) == F) return false;
1582 }
1583 return true;
1584}
1585
1586/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1587/// function, changing them to FastCC.
1588static void ChangeCalleesToFastCall(Function *F) {
1589 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001590 CallSite User(cast<Instruction>(*UI));
1591 User.setCallingConv(CallingConv::Fast);
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001592 }
1593}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001594
Chris Lattner58d74912008-03-12 17:45:29 +00001595static PAListPtr StripNest(const PAListPtr &Attrs) {
1596 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1597 if ((Attrs.getSlot(i).Attrs & ParamAttr::Nest) == 0)
Duncan Sands548448a2008-02-18 17:32:13 +00001598 continue;
1599
Duncan Sands548448a2008-02-18 17:32:13 +00001600 // There can be only one.
Chris Lattner58d74912008-03-12 17:45:29 +00001601 return Attrs.removeAttr(Attrs.getSlot(i).Index, ParamAttr::Nest);
Duncan Sands3d5378f2008-02-16 20:56:04 +00001602 }
1603
1604 return Attrs;
1605}
1606
1607static void RemoveNestAttribute(Function *F) {
1608 F->setParamAttrs(StripNest(F->getParamAttrs()));
1609 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Duncan Sands548448a2008-02-18 17:32:13 +00001610 CallSite User(cast<Instruction>(*UI));
1611 User.setParamAttrs(StripNest(User.getParamAttrs()));
Duncan Sands3d5378f2008-02-16 20:56:04 +00001612 }
1613}
1614
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001615bool GlobalOpt::OptimizeFunctions(Module &M) {
1616 bool Changed = false;
1617 // Optimize functions.
1618 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1619 Function *F = FI++;
1620 F->removeDeadConstantUsers();
1621 if (F->use_empty() && (F->hasInternalLinkage() ||
1622 F->hasLinkOnceLinkage())) {
1623 M.getFunctionList().erase(F);
1624 Changed = true;
1625 ++NumFnDeleted;
Duncan Sands3d5378f2008-02-16 20:56:04 +00001626 } else if (F->hasInternalLinkage()) {
1627 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1628 OnlyCalledDirectly(F)) {
1629 // If this function has C calling conventions, is not a varargs
1630 // function, and is only called directly, promote it to use the Fast
1631 // calling convention.
1632 F->setCallingConv(CallingConv::Fast);
1633 ChangeCalleesToFastCall(F);
1634 ++NumFastCallFns;
1635 Changed = true;
1636 }
1637
Chris Lattner58d74912008-03-12 17:45:29 +00001638 if (F->getParamAttrs().hasAttrSomewhere(ParamAttr::Nest) &&
Duncan Sands3d5378f2008-02-16 20:56:04 +00001639 OnlyCalledDirectly(F)) {
1640 // The function is not used by a trampoline intrinsic, so it is safe
1641 // to remove the 'nest' attribute.
1642 RemoveNestAttribute(F);
1643 ++NumNestRemoved;
1644 Changed = true;
1645 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001646 }
1647 }
1648 return Changed;
1649}
1650
1651bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1652 bool Changed = false;
1653 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1654 GVI != E; ) {
1655 GlobalVariable *GV = GVI++;
1656 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1657 GV->hasInitializer())
1658 Changed |= ProcessInternalGlobal(GV, GVI);
1659 }
1660 return Changed;
1661}
1662
1663/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1664/// initializers have an init priority of 65535.
1665GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001666 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1667 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001668 if (I->getName() == "llvm.global_ctors") {
1669 // Found it, verify it's an array of { int, void()* }.
1670 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1671 if (!ATy) return 0;
1672 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1673 if (!STy || STy->getNumElements() != 2 ||
Reid Spencerc5b206b2006-12-31 05:48:39 +00001674 STy->getElementType(0) != Type::Int32Ty) return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001675 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1676 if (!PFTy) return 0;
1677 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1678 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1679 FTy->getNumParams() != 0)
1680 return 0;
1681
1682 // Verify that the initializer is simple enough for us to handle.
1683 if (!I->hasInitializer()) return 0;
1684 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1685 if (!CA) return 0;
1686 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1687 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001688 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1689 continue;
1690
1691 // Must have a function or null ptr.
1692 if (!isa<Function>(CS->getOperand(1)))
1693 return 0;
1694
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001695 // Init priority must be standard.
1696 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001697 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001698 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001699 } else {
1700 return 0;
1701 }
1702
1703 return I;
1704 }
1705 return 0;
1706}
1707
Chris Lattnerdb973e62005-09-26 02:31:18 +00001708/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1709/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001710static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1711 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1712 std::vector<Function*> Result;
1713 Result.reserve(CA->getNumOperands());
1714 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1715 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1716 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1717 }
1718 return Result;
1719}
1720
Chris Lattnerdb973e62005-09-26 02:31:18 +00001721/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1722/// specified array, returning the new global to use.
1723static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1724 const std::vector<Function*> &Ctors) {
1725 // If we made a change, reassemble the initializer list.
1726 std::vector<Constant*> CSVals;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001727 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001728 CSVals.push_back(0);
1729
1730 // Create the new init list.
1731 std::vector<Constant*> CAList;
1732 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001733 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001734 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001735 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001736 const Type *FTy = FunctionType::get(Type::VoidTy,
1737 std::vector<const Type*>(), false);
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001738 const PointerType *PFTy = PointerType::getUnqual(FTy);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001739 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerc5b206b2006-12-31 05:48:39 +00001740 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001741 }
1742 CAList.push_back(ConstantStruct::get(CSVals));
1743 }
1744
1745 // Create the array initializer.
1746 const Type *StructTy =
1747 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1748 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1749 CAList);
1750
1751 // If we didn't change the number of elements, don't create a new GV.
1752 if (CA->getType() == GCL->getInitializer()->getType()) {
1753 GCL->setInitializer(CA);
1754 return GCL;
1755 }
1756
1757 // Create the new global and insert it next to the existing list.
1758 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
Lauro Ramos Venancioc7635522007-04-12 18:32:50 +00001759 GCL->getLinkage(), CA, "",
1760 (Module *)NULL,
1761 GCL->isThreadLocal());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001762 GCL->getParent()->getGlobalList().insert(GCL, NGV);
Chris Lattner046800a2007-02-11 01:08:35 +00001763 NGV->takeName(GCL);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001764
1765 // Nuke the old list, replacing any uses with the new one.
1766 if (!GCL->use_empty()) {
1767 Constant *V = NGV;
1768 if (V->getType() != GCL->getType())
Reid Spencerd977d862006-12-12 23:36:14 +00001769 V = ConstantExpr::getBitCast(V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001770 GCL->replaceAllUsesWith(V);
1771 }
1772 GCL->eraseFromParent();
1773
1774 if (Ctors.size())
1775 return NGV;
1776 else
1777 return 0;
1778}
Chris Lattner79c11012005-09-26 04:44:35 +00001779
1780
1781static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1782 Value *V) {
1783 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1784 Constant *R = ComputedValues[V];
1785 assert(R && "Reference to an uncomputed value!");
1786 return R;
1787}
1788
1789/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1790/// enough for us to understand. In particular, if it is a cast of something,
1791/// we punt. We basically just support direct accesses to globals and GEP's of
1792/// globals. This should be kept up to date with CommitValueTo.
1793static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00001794 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1795 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001796 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Reid Spencer5cbf9852007-01-30 20:08:39 +00001797 return !GV->isDeclaration(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00001798 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001799 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1800 // Handle a constantexpr gep.
1801 if (CE->getOpcode() == Instruction::GetElementPtr &&
1802 isa<GlobalVariable>(CE->getOperand(0))) {
1803 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner231308c2005-09-27 04:50:03 +00001804 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001805 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00001806 return GV->hasInitializer() &&
1807 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1808 }
Chris Lattner79c11012005-09-26 04:44:35 +00001809 return false;
1810}
1811
Chris Lattner798b4d52005-09-26 06:52:44 +00001812/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1813/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1814/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1815static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1816 ConstantExpr *Addr, unsigned OpNo) {
1817 // Base case of the recursion.
1818 if (OpNo == Addr->getNumOperands()) {
1819 assert(Val->getType() == Init->getType() && "Type mismatch!");
1820 return Val;
1821 }
1822
1823 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1824 std::vector<Constant*> Elts;
1825
1826 // Break up the constant into its elements.
1827 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1828 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1829 Elts.push_back(CS->getOperand(i));
1830 } else if (isa<ConstantAggregateZero>(Init)) {
1831 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1832 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1833 } else if (isa<UndefValue>(Init)) {
1834 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1835 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1836 } else {
1837 assert(0 && "This code is out of sync with "
1838 " ConstantFoldLoadThroughGEPConstantExpr");
1839 }
1840
1841 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00001842 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1843 unsigned Idx = CU->getZExtValue();
1844 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00001845 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1846
1847 // Return the modified struct.
Chris Lattnerf0a9aab2007-06-04 22:23:42 +00001848 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
Chris Lattner798b4d52005-09-26 06:52:44 +00001849 } else {
1850 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1851 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1852
1853 // Break up the array into elements.
1854 std::vector<Constant*> Elts;
1855 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1856 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1857 Elts.push_back(CA->getOperand(i));
1858 } else if (isa<ConstantAggregateZero>(Init)) {
1859 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1860 Elts.assign(ATy->getNumElements(), Elt);
1861 } else if (isa<UndefValue>(Init)) {
1862 Constant *Elt = UndefValue::get(ATy->getElementType());
1863 Elts.assign(ATy->getNumElements(), Elt);
1864 } else {
1865 assert(0 && "This code is out of sync with "
1866 " ConstantFoldLoadThroughGEPConstantExpr");
1867 }
1868
Reid Spencerb83eb642006-10-20 07:07:24 +00001869 assert(CI->getZExtValue() < ATy->getNumElements());
1870 Elts[CI->getZExtValue()] =
1871 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00001872 return ConstantArray::get(ATy, Elts);
1873 }
1874}
1875
Chris Lattner79c11012005-09-26 04:44:35 +00001876/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1877/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1878static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00001879 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1880 assert(GV->hasInitializer());
1881 GV->setInitializer(Val);
1882 return;
1883 }
1884
1885 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1886 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1887
1888 Constant *Init = GV->getInitializer();
1889 Init = EvaluateStoreInto(Init, Val, CE, 2);
1890 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00001891}
1892
Chris Lattner562a0552005-09-26 05:16:34 +00001893/// ComputeLoadResult - Return the value that would be computed by a load from
1894/// P after the stores reflected by 'memory' have been performed. If we can't
1895/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001896static Constant *ComputeLoadResult(Constant *P,
1897 const std::map<Constant*, Constant*> &Memory) {
1898 // If this memory location has been recently stored, use the stored value: it
1899 // is the most up-to-date.
1900 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1901 if (I != Memory.end()) return I->second;
1902
1903 // Access it.
1904 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1905 if (GV->hasInitializer())
1906 return GV->getInitializer();
1907 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00001908 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001909
1910 // Handle a constantexpr getelementptr.
1911 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1912 if (CE->getOpcode() == Instruction::GetElementPtr &&
1913 isa<GlobalVariable>(CE->getOperand(0))) {
1914 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1915 if (GV->hasInitializer())
1916 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1917 }
1918
1919 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001920}
1921
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001922/// EvaluateFunction - Evaluate a call to function F, returning true if
1923/// successful, false if we can't evaluate it. ActualArgs contains the formal
1924/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00001925static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001926 const std::vector<Constant*> &ActualArgs,
1927 std::vector<Function*> &CallStack,
1928 std::map<Constant*, Constant*> &MutatedMemory,
1929 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00001930 // Check to see if this function is already executing (recursion). If so,
1931 // bail out. TODO: we might want to accept limited recursion.
1932 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1933 return false;
1934
1935 CallStack.push_back(F);
1936
Chris Lattner79c11012005-09-26 04:44:35 +00001937 /// Values - As we compute SSA register values, we store their contents here.
1938 std::map<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00001939
1940 // Initialize arguments to the incoming values specified.
1941 unsigned ArgNo = 0;
1942 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1943 ++AI, ++ArgNo)
1944 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001945
Chris Lattnercdf98be2005-09-26 04:57:38 +00001946 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1947 /// we can only evaluate any one basic block at most once. This set keeps
1948 /// track of what we have executed so we can detect recursive cases etc.
1949 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00001950
Chris Lattner79c11012005-09-26 04:44:35 +00001951 // CurInst - The current instruction we're evaluating.
1952 BasicBlock::iterator CurInst = F->begin()->begin();
1953
1954 // This is the main evaluation loop.
1955 while (1) {
1956 Constant *InstResult = 0;
1957
1958 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001959 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00001960 Constant *Ptr = getVal(Values, SI->getOperand(1));
1961 if (!isSimpleEnoughPointerToCommit(Ptr))
1962 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00001963 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00001964 Constant *Val = getVal(Values, SI->getOperand(0));
1965 MutatedMemory[Ptr] = Val;
1966 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1967 InstResult = ConstantExpr::get(BO->getOpcode(),
1968 getVal(Values, BO->getOperand(0)),
1969 getVal(Values, BO->getOperand(1)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001970 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1971 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1972 getVal(Values, CI->getOperand(0)),
1973 getVal(Values, CI->getOperand(1)));
Chris Lattner79c11012005-09-26 04:44:35 +00001974 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00001975 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1976 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00001977 CI->getType());
1978 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1979 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1980 getVal(Values, SI->getOperand(1)),
1981 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00001982 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1983 Constant *P = getVal(Values, GEP->getOperand(0));
Chris Lattner55eb1c42007-01-31 04:40:53 +00001984 SmallVector<Constant*, 8> GEPOps;
Chris Lattner04de1cf2005-09-26 05:15:37 +00001985 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1986 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
Chris Lattner55eb1c42007-01-31 04:40:53 +00001987 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
Chris Lattner04de1cf2005-09-26 05:15:37 +00001988 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001989 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001990 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1991 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00001992 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001993 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001994 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001995 const Type *Ty = AI->getType()->getElementType();
1996 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1997 GlobalValue::InternalLinkage,
1998 UndefValue::get(Ty),
1999 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00002000 InstResult = AllocaTmps.back();
2001 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattner7cd580f2006-07-07 21:37:01 +00002002 // Cannot handle inline asm.
2003 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2004
Chris Lattnercd271422005-09-27 04:45:34 +00002005 // Resolve function pointers.
2006 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2007 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002008
Chris Lattnercd271422005-09-27 04:45:34 +00002009 std::vector<Constant*> Formals;
2010 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
2011 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattnercd271422005-09-27 04:45:34 +00002012
Reid Spencer5cbf9852007-01-30 20:08:39 +00002013 if (Callee->isDeclaration()) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002014 // If this is a function we can constant fold, do it.
Chris Lattner6c1f5652007-01-30 23:14:52 +00002015 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2016 Formals.size())) {
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00002017 InstResult = C;
2018 } else {
2019 return false;
2020 }
2021 } else {
2022 if (Callee->getFunctionType()->isVarArg())
2023 return false;
2024
2025 Constant *RetVal;
2026
2027 // Execute the call, if successful, use the return value.
2028 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2029 MutatedMemory, AllocaTmps))
2030 return false;
2031 InstResult = RetVal;
2032 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00002033 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00002034 BasicBlock *NewBB = 0;
2035 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2036 if (BI->isUnconditional()) {
2037 NewBB = BI->getSuccessor(0);
2038 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002039 ConstantInt *Cond =
2040 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
Chris Lattner97d1fad2007-01-12 18:30:11 +00002041 if (!Cond) return false; // Cannot determine.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002042
Reid Spencer579dca12007-01-12 04:24:46 +00002043 NewBB = BI->getSuccessor(!Cond->getZExtValue());
Chris Lattnercdf98be2005-09-26 04:57:38 +00002044 }
2045 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2046 ConstantInt *Val =
2047 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00002048 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002049 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2050 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00002051 if (RI->getNumOperands())
2052 RetVal = getVal(Values, RI->getOperand(0));
2053
2054 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002055 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002056 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00002057 // invoke, unwind, unreachable.
2058 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002059 }
2060
2061 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00002062 // executed the new block before. If so, we have a looping function,
2063 // which we cannot evaluate in reasonable time.
Chris Lattnercdf98be2005-09-26 04:57:38 +00002064 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattnercd271422005-09-27 04:45:34 +00002065 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00002066
2067 // Okay, we have never been in this block before. Check to see if there
2068 // are any PHI nodes. If so, evaluate them with information about where
2069 // we came from.
2070 BasicBlock *OldBB = CurInst->getParent();
2071 CurInst = NewBB->begin();
2072 PHINode *PN;
2073 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2074 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2075
2076 // Do NOT increment CurInst. We know that the terminator had no value.
2077 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00002078 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00002079 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00002080 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00002081 }
2082
2083 if (!CurInst->use_empty())
2084 Values[CurInst] = InstResult;
2085
2086 // Advance program counter.
2087 ++CurInst;
2088 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002089}
2090
2091/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2092/// we can. Return true if we can, false otherwise.
2093static bool EvaluateStaticConstructor(Function *F) {
2094 /// MutatedMemory - For each store we execute, we update this map. Loads
2095 /// check this to get the most up-to-date value. If evaluation is successful,
2096 /// this state is committed to the process.
2097 std::map<Constant*, Constant*> MutatedMemory;
2098
2099 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2100 /// to represent its body. This vector is needed so we can delete the
2101 /// temporary globals when we are done.
2102 std::vector<GlobalVariable*> AllocaTmps;
2103
2104 /// CallStack - This is used to detect recursion. In pathological situations
2105 /// we could hit exponential behavior, but at least there is nothing
2106 /// unbounded.
2107 std::vector<Function*> CallStack;
2108
2109 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00002110 Constant *RetValDummy;
2111 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2112 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002113 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00002114 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00002115 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2116 << F->getName() << "' to " << MutatedMemory.size()
2117 << " stores.\n";
Chris Lattnera22fdb02005-09-26 17:07:09 +00002118 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2119 E = MutatedMemory.end(); I != E; ++I)
2120 CommitValueTo(I->second, I->first);
2121 }
Chris Lattner79c11012005-09-26 04:44:35 +00002122
Chris Lattnera22fdb02005-09-26 17:07:09 +00002123 // At this point, we are done interpreting. If we created any 'alloca'
2124 // temporaries, release them now.
2125 while (!AllocaTmps.empty()) {
2126 GlobalVariable *Tmp = AllocaTmps.back();
2127 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002128
Chris Lattnera22fdb02005-09-26 17:07:09 +00002129 // If there are still users of the alloca, the program is doing something
2130 // silly, e.g. storing the address of the alloca somewhere and using it
2131 // later. Since this is undefined, we'll just make it be null.
2132 if (!Tmp->use_empty())
2133 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2134 delete Tmp;
2135 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00002136
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002137 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00002138}
2139
Chris Lattnerdb973e62005-09-26 02:31:18 +00002140
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00002141
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002142/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2143/// Return true if anything changed.
2144bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2145 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2146 bool MadeChange = false;
2147 if (Ctors.empty()) return false;
2148
2149 // Loop over global ctors, optimizing them when we can.
2150 for (unsigned i = 0; i != Ctors.size(); ++i) {
2151 Function *F = Ctors[i];
2152 // Found a null terminator in the middle of the list, prune off the rest of
2153 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00002154 if (F == 0) {
2155 if (i != Ctors.size()-1) {
2156 Ctors.resize(i+1);
2157 MadeChange = true;
2158 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002159 break;
2160 }
2161
Chris Lattner79c11012005-09-26 04:44:35 +00002162 // We cannot simplify external ctor functions.
2163 if (F->empty()) continue;
2164
2165 // If we can evaluate the ctor at compile time, do.
2166 if (EvaluateStaticConstructor(F)) {
2167 Ctors.erase(Ctors.begin()+i);
2168 MadeChange = true;
2169 --i;
2170 ++NumCtorsEvaluated;
2171 continue;
2172 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002173 }
2174
2175 if (!MadeChange) return false;
2176
Chris Lattnerdb973e62005-09-26 02:31:18 +00002177 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002178 return true;
2179}
2180
2181
Chris Lattner7a90b682004-10-07 04:16:33 +00002182bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00002183 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002184
2185 // Try to find the llvm.globalctors list.
2186 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002187
Chris Lattner7a90b682004-10-07 04:16:33 +00002188 bool LocalChange = true;
2189 while (LocalChange) {
2190 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002191
2192 // Delete functions that are trivially dead, ccc -> fastcc
2193 LocalChange |= OptimizeFunctions(M);
2194
2195 // Optimize global_ctors list.
2196 if (GlobalCtors)
2197 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2198
2199 // Optimize non-address-taken globals.
2200 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00002201 Changed |= LocalChange;
2202 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00002203
2204 // TODO: Move all global ctors functions to the end of the module for code
2205 // layout.
2206
Chris Lattner079236d2004-02-25 21:34:36 +00002207 return Changed;
2208}