blob: af3bf6a887cba5360b6af21e2549398583bb7902 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/Debug.h"
Chris Lattner30ba5692004-10-11 05:54:41 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/Statistic.h"
Chris Lattner670c8892004-10-08 17:32:09 +000029#include "llvm/ADT/StringExtras.h"
Chris Lattnere47ba742004-10-06 20:57:02 +000030#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000031#include <set>
Chris Lattner079236d2004-02-25 21:34:36 +000032using namespace llvm;
33
34namespace {
Chris Lattner670c8892004-10-08 17:32:09 +000035 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
36 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
37 "into scalars");
Chris Lattner86395032006-09-30 23:32:09 +000038 Statistic<> NumHeapSRA ("globalopt", "Number of heap objects SRA'd");
Chris Lattner7a7ed022004-10-16 18:09:00 +000039 Statistic<> NumSubstitute("globalopt",
40 "Number of globals with initializers stored into them");
Chris Lattner670c8892004-10-08 17:32:09 +000041 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
Chris Lattner7a90b682004-10-07 04:16:33 +000042 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
Chris Lattner708148e2004-10-10 23:14:11 +000043 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +000044 Statistic<> NumLocalized("globalopt", "Number of globals localized");
Chris Lattner96a86b22004-12-12 05:53:50 +000045 Statistic<> NumShrunkToBool("globalopt",
46 "Number of global vars shrunk to booleans");
Chris Lattnerfb217ad2005-05-08 22:18:06 +000047 Statistic<> NumFastCallFns("globalopt",
48 "Number of functions converted to fastcc");
Chris Lattner79c11012005-09-26 04:44:35 +000049 Statistic<> NumCtorsEvaluated("globalopt","Number of static ctors evaluated");
Chris Lattner079236d2004-02-25 21:34:36 +000050
Chris Lattner7a90b682004-10-07 04:16:33 +000051 struct GlobalOpt : public ModulePass {
Chris Lattner30ba5692004-10-11 05:54:41 +000052 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53 AU.addRequired<TargetData>();
54 }
Misha Brukmanfd939082005-04-21 23:48:37 +000055
Chris Lattnerb12914b2004-09-20 04:48:05 +000056 bool runOnModule(Module &M);
Chris Lattner30ba5692004-10-11 05:54:41 +000057
58 private:
Chris Lattnerb1ab4582005-09-26 01:43:45 +000059 GlobalVariable *FindGlobalCtors(Module &M);
60 bool OptimizeFunctions(Module &M);
61 bool OptimizeGlobalVars(Module &M);
62 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
Chris Lattner7f8897f2006-08-27 22:42:52 +000063 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
Chris Lattner079236d2004-02-25 21:34:36 +000064 };
65
Chris Lattner7f8897f2006-08-27 22:42:52 +000066 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
Chris Lattner079236d2004-02-25 21:34:36 +000067}
68
Chris Lattner7a90b682004-10-07 04:16:33 +000069ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
Chris Lattner079236d2004-02-25 21:34:36 +000070
Chris Lattner7a90b682004-10-07 04:16:33 +000071/// GlobalStatus - As we analyze each global, keep track of some information
72/// about it. If we find out that the address of the global is taken, none of
Chris Lattnercf4d2a52004-10-07 21:30:30 +000073/// this info will be accurate.
Chris Lattner7a90b682004-10-07 04:16:33 +000074struct GlobalStatus {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000075 /// isLoaded - True if the global is ever loaded. If the global isn't ever
76 /// loaded it can be deleted.
Chris Lattner7a90b682004-10-07 04:16:33 +000077 bool isLoaded;
Chris Lattnercf4d2a52004-10-07 21:30:30 +000078
79 /// StoredType - Keep track of what stores to the global look like.
80 ///
Chris Lattner7a90b682004-10-07 04:16:33 +000081 enum StoredType {
Chris Lattnercf4d2a52004-10-07 21:30:30 +000082 /// NotStored - There is no store to this global. It can thus be marked
83 /// constant.
84 NotStored,
85
86 /// isInitializerStored - This global is stored to, but the only thing
87 /// stored is the constant it was initialized with. This is only tracked
88 /// for scalar globals.
89 isInitializerStored,
90
91 /// isStoredOnce - This global is stored to, but only its initializer and
92 /// one other value is ever stored to it. If this global isStoredOnce, we
93 /// track the value stored to it in StoredOnceValue below. This is only
94 /// tracked for scalar globals.
95 isStoredOnce,
96
97 /// isStored - This global is stored to by multiple values or something else
98 /// that we cannot track.
99 isStored
Chris Lattner7a90b682004-10-07 04:16:33 +0000100 } StoredType;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000101
102 /// StoredOnceValue - If only one value (besides the initializer constant) is
103 /// ever stored to this global, keep track of what value it is.
104 Value *StoredOnceValue;
105
Chris Lattner25de4e52006-11-01 18:03:33 +0000106 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
107 /// null/false. When the first accessing function is noticed, it is recorded.
108 /// When a second different accessing function is noticed,
109 /// HasMultipleAccessingFunctions is set to true.
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000110 Function *AccessingFunction;
111 bool HasMultipleAccessingFunctions;
112
Chris Lattner25de4e52006-11-01 18:03:33 +0000113 /// HasNonInstructionUser - Set to true if this global has a user that is not
114 /// an instruction (e.g. a constant expr or GV initializer).
Chris Lattner553ca522005-06-15 21:11:48 +0000115 bool HasNonInstructionUser;
116
Chris Lattner25de4e52006-11-01 18:03:33 +0000117 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
118 bool HasPHIUser;
119
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000120 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
121 /// the global exist. Such users include GEP instruction with variable
122 /// indexes, and non-gep/load/store users like constant expr casts.
Chris Lattner7a90b682004-10-07 04:16:33 +0000123 bool isNotSuitableForSRA;
Chris Lattner9ce30002004-07-20 03:58:07 +0000124
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000125 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000126 AccessingFunction(0), HasMultipleAccessingFunctions(false),
Chris Lattner25de4e52006-11-01 18:03:33 +0000127 HasNonInstructionUser(false), HasPHIUser(false),
128 isNotSuitableForSRA(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;
160 if (CE->getOpcode() != Instruction::GetElementPtr)
161 GS.isNotSuitableForSRA = true;
Chris Lattner670c8892004-10-08 17:32:09 +0000162 else if (!GS.isNotSuitableForSRA) {
163 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
164 // don't like < 3 operand CE's, and we don't like non-constant integer
165 // indices.
166 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
167 GS.isNotSuitableForSRA = true;
168 else {
169 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
170 if (!isa<ConstantInt>(CE->getOperand(i))) {
171 GS.isNotSuitableForSRA = true;
172 break;
173 }
174 }
175 }
176
Chris Lattner079236d2004-02-25 21:34:36 +0000177 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +0000178 if (!GS.HasMultipleAccessingFunctions) {
179 Function *F = I->getParent()->getParent();
180 if (GS.AccessingFunction == 0)
181 GS.AccessingFunction = F;
182 else if (GS.AccessingFunction != F)
183 GS.HasMultipleAccessingFunctions = true;
184 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000185 if (isa<LoadInst>(I)) {
186 GS.isLoaded = true;
187 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Chris Lattner36025492004-10-07 06:01:25 +0000188 // Don't allow a store OF the address, only stores TO the address.
189 if (SI->getOperand(0) == V) return true;
190
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000191 // If this is a direct store to the global (i.e., the global is a scalar
192 // value, not an aggregate), keep more specific information about
193 // stores.
194 if (GS.StoredType != GlobalStatus::isStored)
195 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000196 Value *StoredVal = SI->getOperand(0);
197 if (StoredVal == GV->getInitializer()) {
198 if (GS.StoredType < GlobalStatus::isInitializerStored)
199 GS.StoredType = GlobalStatus::isInitializerStored;
200 } else if (isa<LoadInst>(StoredVal) &&
201 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
202 // G = G
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000203 if (GS.StoredType < GlobalStatus::isInitializerStored)
204 GS.StoredType = GlobalStatus::isInitializerStored;
205 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
206 GS.StoredType = GlobalStatus::isStoredOnce;
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000207 GS.StoredOnceValue = StoredVal;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000208 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
Chris Lattnerbd38edf2004-11-14 20:50:30 +0000209 GS.StoredOnceValue == StoredVal) {
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000210 // noop.
211 } else {
212 GS.StoredType = GlobalStatus::isStored;
213 }
214 } else {
Chris Lattner7a90b682004-10-07 04:16:33 +0000215 GS.StoredType = GlobalStatus::isStored;
Chris Lattnercf4d2a52004-10-07 21:30:30 +0000216 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000217 } else if (isa<GetElementPtrInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000218 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
Chris Lattner30ba5692004-10-11 05:54:41 +0000219
220 // If the first two indices are constants, this can be SRA'd.
221 if (isa<GlobalVariable>(I->getOperand(0))) {
222 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
Misha Brukmanfd939082005-04-21 23:48:37 +0000223 !cast<Constant>(I->getOperand(1))->isNullValue() ||
Chris Lattner30ba5692004-10-11 05:54:41 +0000224 !isa<ConstantInt>(I->getOperand(2)))
225 GS.isNotSuitableForSRA = true;
226 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
227 if (CE->getOpcode() != Instruction::GetElementPtr ||
228 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
229 !isa<Constant>(I->getOperand(0)) ||
230 !cast<Constant>(I->getOperand(0))->isNullValue())
231 GS.isNotSuitableForSRA = true;
232 } else {
233 GS.isNotSuitableForSRA = true;
234 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000235 } else if (isa<SelectInst>(I)) {
Chris Lattner7a90b682004-10-07 04:16:33 +0000236 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
237 GS.isNotSuitableForSRA = true;
238 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
239 // PHI nodes we can check just like select or GEP instructions, but we
240 // have to be careful about infinite recursion.
241 if (PHIUsers.insert(PN).second) // Not already visited.
242 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
243 GS.isNotSuitableForSRA = true;
Chris Lattner25de4e52006-11-01 18:03:33 +0000244 GS.HasPHIUser = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000245 } else if (isa<SetCondInst>(I)) {
246 GS.isNotSuitableForSRA = true;
Chris Lattner35c81b02005-02-27 18:58:52 +0000247 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
248 if (I->getOperand(1) == V)
249 GS.StoredType = GlobalStatus::isStored;
250 if (I->getOperand(2) == V)
251 GS.isLoaded = true;
252 GS.isNotSuitableForSRA = true;
253 } else if (isa<MemSetInst>(I)) {
254 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
255 GS.StoredType = GlobalStatus::isStored;
256 GS.isNotSuitableForSRA = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000257 } else {
258 return true; // Any other non-load instruction might take address!
Chris Lattner9ce30002004-07-20 03:58:07 +0000259 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000260 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
Chris Lattner553ca522005-06-15 21:11:48 +0000261 GS.HasNonInstructionUser = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000262 // We might have a dead and dangling constant hanging off of here.
263 if (!ConstantIsDead(C))
264 return true;
Chris Lattner079236d2004-02-25 21:34:36 +0000265 } else {
Chris Lattner553ca522005-06-15 21:11:48 +0000266 GS.HasNonInstructionUser = true;
267 // Otherwise must be some other user.
Chris Lattner079236d2004-02-25 21:34:36 +0000268 return true;
269 }
270
271 return false;
272}
273
Chris Lattner670c8892004-10-08 17:32:09 +0000274static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
275 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
276 if (!CI) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000277 unsigned IdxV = CI->getZExtValue();
Chris Lattner7a90b682004-10-07 04:16:33 +0000278
Chris Lattner670c8892004-10-08 17:32:09 +0000279 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
280 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
281 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
282 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
283 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
284 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000285 } else if (isa<ConstantAggregateZero>(Agg)) {
Chris Lattner670c8892004-10-08 17:32:09 +0000286 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
287 if (IdxV < STy->getNumElements())
288 return Constant::getNullValue(STy->getElementType(IdxV));
289 } else if (const SequentialType *STy =
290 dyn_cast<SequentialType>(Agg->getType())) {
291 return Constant::getNullValue(STy->getElementType());
292 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000293 } else if (isa<UndefValue>(Agg)) {
294 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
295 if (IdxV < STy->getNumElements())
296 return UndefValue::get(STy->getElementType(IdxV));
297 } else if (const SequentialType *STy =
298 dyn_cast<SequentialType>(Agg->getType())) {
299 return UndefValue::get(STy->getElementType());
300 }
Chris Lattner670c8892004-10-08 17:32:09 +0000301 }
302 return 0;
303}
Chris Lattner7a90b682004-10-07 04:16:33 +0000304
Chris Lattner7a90b682004-10-07 04:16:33 +0000305
Chris Lattnere47ba742004-10-06 20:57:02 +0000306/// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
307/// users of the global, cleaning up the obvious ones. This is largely just a
Chris Lattner031955d2004-10-10 16:43:46 +0000308/// quick scan over the use list to clean up the easy and obvious cruft. This
309/// returns true if it made a change.
310static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
311 bool Changed = false;
Chris Lattner7a90b682004-10-07 04:16:33 +0000312 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
313 User *U = *UI++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000314
Chris Lattner7a90b682004-10-07 04:16:33 +0000315 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner35c81b02005-02-27 18:58:52 +0000316 if (Init) {
317 // Replace the load with the initializer.
318 LI->replaceAllUsesWith(Init);
319 LI->eraseFromParent();
320 Changed = true;
321 }
Chris Lattner7a90b682004-10-07 04:16:33 +0000322 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnere47ba742004-10-06 20:57:02 +0000323 // Store must be unreachable or storing Init into the global.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000324 SI->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000325 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000326 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
327 if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattneraae4a1c2005-09-26 07:34:35 +0000328 Constant *SubInit = 0;
329 if (Init)
330 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000331 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
Reid Spencer3da59db2006-11-27 01:05:10 +0000332 } else if (CE->getOpcode() == Instruction::BitCast &&
Chris Lattner35c81b02005-02-27 18:58:52 +0000333 isa<PointerType>(CE->getType())) {
334 // Pointer cast, delete any stores and memsets to the global.
335 Changed |= CleanupConstantGlobalUsers(CE, 0);
336 }
337
338 if (CE->use_empty()) {
339 CE->destroyConstant();
340 Changed = true;
Chris Lattner7a90b682004-10-07 04:16:33 +0000341 }
342 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner0b142e32005-09-26 05:34:07 +0000343 Constant *SubInit = 0;
Chris Lattner798b4d52005-09-26 06:52:44 +0000344 ConstantExpr *CE =
345 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
Chris Lattner9a5582f2005-09-27 22:28:11 +0000346 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
Chris Lattner0b142e32005-09-26 05:34:07 +0000347 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Chris Lattner35c81b02005-02-27 18:58:52 +0000348 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
Chris Lattnerc4d81b02004-10-10 16:47:33 +0000349
Chris Lattner031955d2004-10-10 16:43:46 +0000350 if (GEP->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000351 GEP->eraseFromParent();
Chris Lattner031955d2004-10-10 16:43:46 +0000352 Changed = true;
353 }
Chris Lattner35c81b02005-02-27 18:58:52 +0000354 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
355 if (MI->getRawDest() == V) {
356 MI->eraseFromParent();
357 Changed = true;
358 }
359
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000360 } else if (Constant *C = dyn_cast<Constant>(U)) {
361 // If we have a chain of dead constantexprs or other things dangling from
362 // us, and if they are all dead, nuke them without remorse.
363 if (ConstantIsDead(C)) {
364 C->destroyConstant();
Chris Lattner35c81b02005-02-27 18:58:52 +0000365 // This could have invalidated UI, start over from scratch.
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000366 CleanupConstantGlobalUsers(V, Init);
Chris Lattner031955d2004-10-10 16:43:46 +0000367 return true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +0000368 }
Chris Lattnere47ba742004-10-06 20:57:02 +0000369 }
370 }
Chris Lattner031955d2004-10-10 16:43:46 +0000371 return Changed;
Chris Lattnere47ba742004-10-06 20:57:02 +0000372}
373
Chris Lattner670c8892004-10-08 17:32:09 +0000374/// SRAGlobal - Perform scalar replacement of aggregates on the specified global
375/// variable. This opens the door for other optimizations by exposing the
376/// behavior of the program in a more fine-grained way. We have determined that
377/// this transformation is safe already. We return the first global variable we
378/// insert so that the caller can reprocess it.
379static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
380 assert(GV->hasInternalLinkage() && !GV->isConstant());
381 Constant *Init = GV->getInitializer();
382 const Type *Ty = Init->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +0000383
Chris Lattner670c8892004-10-08 17:32:09 +0000384 std::vector<GlobalVariable*> NewGlobals;
385 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
386
387 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
388 NewGlobals.reserve(STy->getNumElements());
389 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
390 Constant *In = getAggregateConstantElement(Init,
Reid Spencerb83eb642006-10-20 07:07:24 +0000391 ConstantInt::get(Type::UIntTy, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000392 assert(In && "Couldn't get element of initializer?");
393 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
394 GlobalVariable::InternalLinkage,
395 In, GV->getName()+"."+utostr(i));
396 Globals.insert(GV, NGV);
397 NewGlobals.push_back(NGV);
398 }
399 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
400 unsigned NumElements = 0;
401 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
402 NumElements = ATy->getNumElements();
403 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
404 NumElements = PTy->getNumElements();
405 else
406 assert(0 && "Unknown aggregate sequential type!");
407
Chris Lattner1f21ef12005-02-23 16:53:04 +0000408 if (NumElements > 16 && GV->hasNUsesOrMore(16))
Chris Lattnerd514d822005-02-01 01:23:31 +0000409 return 0; // It's not worth it.
Chris Lattner670c8892004-10-08 17:32:09 +0000410 NewGlobals.reserve(NumElements);
411 for (unsigned i = 0, e = NumElements; i != e; ++i) {
412 Constant *In = getAggregateConstantElement(Init,
Reid Spencerb83eb642006-10-20 07:07:24 +0000413 ConstantInt::get(Type::UIntTy, i));
Chris Lattner670c8892004-10-08 17:32:09 +0000414 assert(In && "Couldn't get element of initializer?");
415
416 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
417 GlobalVariable::InternalLinkage,
418 In, GV->getName()+"."+utostr(i));
419 Globals.insert(GV, NGV);
420 NewGlobals.push_back(NGV);
421 }
422 }
423
424 if (NewGlobals.empty())
425 return 0;
426
Bill Wendling0a81aac2006-11-26 10:02:32 +0000427 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Chris Lattner30ba5692004-10-11 05:54:41 +0000428
Chris Lattner670c8892004-10-08 17:32:09 +0000429 Constant *NullInt = Constant::getNullValue(Type::IntTy);
430
431 // Loop over all of the uses of the global, replacing the constantexpr geps,
432 // with smaller constantexpr geps or direct references.
433 while (!GV->use_empty()) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000434 User *GEP = GV->use_back();
435 assert(((isa<ConstantExpr>(GEP) &&
436 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
437 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000438
Chris Lattner670c8892004-10-08 17:32:09 +0000439 // Ignore the 1th operand, which has to be zero or else the program is quite
440 // broken (undefined). Get the 2nd operand, which is the structure or array
441 // index.
Reid Spencerb83eb642006-10-20 07:07:24 +0000442 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner670c8892004-10-08 17:32:09 +0000443 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
444
Chris Lattner30ba5692004-10-11 05:54:41 +0000445 Value *NewPtr = NewGlobals[Val];
Chris Lattner670c8892004-10-08 17:32:09 +0000446
447 // Form a shorter GEP if needed.
Chris Lattner30ba5692004-10-11 05:54:41 +0000448 if (GEP->getNumOperands() > 3)
449 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
450 std::vector<Constant*> Idxs;
451 Idxs.push_back(NullInt);
452 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
453 Idxs.push_back(CE->getOperand(i));
454 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
455 } else {
456 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
457 std::vector<Value*> Idxs;
458 Idxs.push_back(NullInt);
459 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
460 Idxs.push_back(GEPI->getOperand(i));
461 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
462 GEPI->getName()+"."+utostr(Val), GEPI);
463 }
464 GEP->replaceAllUsesWith(NewPtr);
465
466 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
Chris Lattner7a7ed022004-10-16 18:09:00 +0000467 GEPI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000468 else
469 cast<ConstantExpr>(GEP)->destroyConstant();
Chris Lattner670c8892004-10-08 17:32:09 +0000470 }
471
Chris Lattnere40e2d12004-10-08 20:25:55 +0000472 // Delete the old global, now that it is dead.
473 Globals.erase(GV);
Chris Lattner670c8892004-10-08 17:32:09 +0000474 ++NumSRA;
Chris Lattner30ba5692004-10-11 05:54:41 +0000475
476 // Loop over the new globals array deleting any globals that are obviously
477 // dead. This can arise due to scalarization of a structure or an array that
478 // has elements that are dead.
479 unsigned FirstGlobal = 0;
480 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
481 if (NewGlobals[i]->use_empty()) {
482 Globals.erase(NewGlobals[i]);
483 if (FirstGlobal == i) ++FirstGlobal;
484 }
485
486 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
Chris Lattner670c8892004-10-08 17:32:09 +0000487}
488
Chris Lattner9b34a612004-10-09 21:48:45 +0000489/// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
490/// value will trap if the value is dynamically null.
491static bool AllUsesOfValueWillTrapIfNull(Value *V) {
492 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
493 if (isa<LoadInst>(*UI)) {
494 // Will trap.
495 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
496 if (SI->getOperand(0) == V) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000497 //llvm_cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000498 return false; // Storing the value.
499 }
500 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
501 if (CI->getOperand(0) != V) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000502 //llvm_cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000503 return false; // Not calling the ptr
504 }
505 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
506 if (II->getOperand(0) != V) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000507 //llvm_cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000508 return false; // Not calling the ptr
509 }
510 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
511 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
512 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
513 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000514 } else if (isa<SetCondInst>(*UI) &&
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000515 isa<ConstantPointerNull>(UI->getOperand(1))) {
516 // Ignore setcc X, null
Chris Lattner9b34a612004-10-09 21:48:45 +0000517 } else {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000518 //llvm_cerr << "NONTRAPPING USE: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000519 return false;
520 }
521 return true;
522}
523
524/// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000525/// from GV will trap if the loaded value is null. Note that this also permits
526/// comparisons of the loaded value against null, as a special case.
Chris Lattner9b34a612004-10-09 21:48:45 +0000527static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
528 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
529 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
530 if (!AllUsesOfValueWillTrapIfNull(LI))
531 return false;
532 } else if (isa<StoreInst>(*UI)) {
533 // Ignore stores to the global.
534 } else {
535 // We don't know or understand this user, bail out.
Bill Wendling0a81aac2006-11-26 10:02:32 +0000536 //llvm_cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
Chris Lattner9b34a612004-10-09 21:48:45 +0000537 return false;
538 }
539
540 return true;
541}
542
Chris Lattner708148e2004-10-10 23:14:11 +0000543static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
544 bool Changed = false;
545 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
546 Instruction *I = cast<Instruction>(*UI++);
547 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
548 LI->setOperand(0, NewV);
549 Changed = true;
550 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
551 if (SI->getOperand(1) == V) {
552 SI->setOperand(1, NewV);
553 Changed = true;
554 }
555 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
556 if (I->getOperand(0) == V) {
557 // Calling through the pointer! Turn into a direct call, but be careful
558 // that the pointer is not also being passed as an argument.
559 I->setOperand(0, NewV);
560 Changed = true;
561 bool PassedAsArg = false;
562 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
563 if (I->getOperand(i) == V) {
564 PassedAsArg = true;
565 I->setOperand(i, NewV);
566 }
567
568 if (PassedAsArg) {
569 // Being passed as an argument also. Be careful to not invalidate UI!
570 UI = V->use_begin();
571 }
572 }
573 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
574 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000575 ConstantExpr::getCast(CI->getOpcode(),
576 NewV, CI->getType()));
Chris Lattner708148e2004-10-10 23:14:11 +0000577 if (CI->use_empty()) {
578 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000579 CI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000580 }
581 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
582 // Should handle GEP here.
583 std::vector<Constant*> Indices;
584 Indices.reserve(GEPI->getNumOperands()-1);
585 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
586 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
587 Indices.push_back(C);
588 else
589 break;
590 if (Indices.size() == GEPI->getNumOperands()-1)
591 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
592 ConstantExpr::getGetElementPtr(NewV, Indices));
593 if (GEPI->use_empty()) {
594 Changed = true;
Chris Lattner7a7ed022004-10-16 18:09:00 +0000595 GEPI->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000596 }
597 }
598 }
599
600 return Changed;
601}
602
603
604/// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
605/// value stored into it. If there are uses of the loaded value that would trap
606/// if the loaded value is dynamically null, then we know that they cannot be
607/// reachable with a null optimize away the load.
608static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
609 std::vector<LoadInst*> Loads;
610 bool Changed = false;
611
612 // Replace all uses of loads with uses of uses of the stored value.
613 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
614 GUI != E; ++GUI)
615 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
616 Loads.push_back(LI);
617 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
618 } else {
619 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
620 }
621
622 if (Changed) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000623 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
Chris Lattner708148e2004-10-10 23:14:11 +0000624 ++NumGlobUses;
625 }
626
627 // Delete all of the loads we can, keeping track of whether we nuked them all!
628 bool AllLoadsGone = true;
629 while (!Loads.empty()) {
630 LoadInst *L = Loads.back();
631 if (L->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000632 L->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000633 Changed = true;
634 } else {
635 AllLoadsGone = false;
636 }
637 Loads.pop_back();
638 }
639
640 // If we nuked all of the loads, then none of the stores are needed either,
641 // nor is the global.
642 if (AllLoadsGone) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000643 DOUT << " *** GLOBAL NOW DEAD!\n";
Chris Lattner708148e2004-10-10 23:14:11 +0000644 CleanupConstantGlobalUsers(GV, 0);
645 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +0000646 GV->eraseFromParent();
Chris Lattner708148e2004-10-10 23:14:11 +0000647 ++NumDeleted;
648 }
649 Changed = true;
650 }
651 return Changed;
652}
653
Chris Lattner30ba5692004-10-11 05:54:41 +0000654/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
655/// instructions that are foldable.
656static void ConstantPropUsersOf(Value *V) {
657 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
658 if (Instruction *I = dyn_cast<Instruction>(*UI++))
659 if (Constant *NewC = ConstantFoldInstruction(I)) {
660 I->replaceAllUsesWith(NewC);
661
Chris Lattnerd514d822005-02-01 01:23:31 +0000662 // Advance UI to the next non-I use to avoid invalidating it!
663 // Instructions could multiply use V.
664 while (UI != E && *UI == I)
Chris Lattner30ba5692004-10-11 05:54:41 +0000665 ++UI;
Chris Lattnerd514d822005-02-01 01:23:31 +0000666 I->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000667 }
668}
669
670/// OptimizeGlobalAddressOfMalloc - This function takes the specified global
671/// variable, and transforms the program as if it always contained the result of
672/// the specified malloc. Because it is always the result of the specified
673/// malloc, there is no reason to actually DO the malloc. Instead, turn the
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000674/// malloc into a global, and any loads of GV as uses of the new global.
Chris Lattner30ba5692004-10-11 05:54:41 +0000675static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
676 MallocInst *MI) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000677 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
Chris Lattner30ba5692004-10-11 05:54:41 +0000678 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
679
Reid Spencerb83eb642006-10-20 07:07:24 +0000680 if (NElements->getZExtValue() != 1) {
Chris Lattner30ba5692004-10-11 05:54:41 +0000681 // If we have an array allocation, transform it to a single element
682 // allocation to make the code below simpler.
683 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
Reid Spencerb83eb642006-10-20 07:07:24 +0000684 NElements->getZExtValue());
Chris Lattner30ba5692004-10-11 05:54:41 +0000685 MallocInst *NewMI =
686 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
Nate Begeman14b05292005-11-05 09:21:28 +0000687 MI->getAlignment(), MI->getName(), MI);
Chris Lattner30ba5692004-10-11 05:54:41 +0000688 std::vector<Value*> Indices;
689 Indices.push_back(Constant::getNullValue(Type::IntTy));
690 Indices.push_back(Indices[0]);
691 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
692 NewMI->getName()+".el0", MI);
693 MI->replaceAllUsesWith(NewGEP);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000694 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000695 MI = NewMI;
696 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000697
Chris Lattner7a7ed022004-10-16 18:09:00 +0000698 // Create the new global variable. The contents of the malloc'd memory is
699 // undefined, so initialize with an undef value.
700 Constant *Init = UndefValue::get(MI->getAllocatedType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000701 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
702 GlobalValue::InternalLinkage, Init,
703 GV->getName()+".body");
704 GV->getParent()->getGlobalList().insert(GV, NewGV);
Misha Brukmanfd939082005-04-21 23:48:37 +0000705
Chris Lattner30ba5692004-10-11 05:54:41 +0000706 // Anything that used the malloc now uses the global directly.
707 MI->replaceAllUsesWith(NewGV);
Chris Lattner30ba5692004-10-11 05:54:41 +0000708
709 Constant *RepValue = NewGV;
710 if (NewGV->getType() != GV->getType()->getElementType())
Chris Lattner6e8fbad2006-11-30 17:32:29 +0000711 RepValue = ConstantExpr::getCast(Instruction::BitCast,
712 RepValue, GV->getType()->getElementType());
Chris Lattner30ba5692004-10-11 05:54:41 +0000713
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000714 // If there is a comparison against null, we will insert a global bool to
715 // keep track of whether the global was initialized yet or not.
Misha Brukmanfd939082005-04-21 23:48:37 +0000716 GlobalVariable *InitBool =
717 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
Chris Lattner47811b72006-09-28 23:35:22 +0000718 ConstantBool::getFalse(), GV->getName()+".init");
Chris Lattnerbc965b92004-12-02 06:25:58 +0000719 bool InitBoolUsed = false;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000720
Chris Lattner30ba5692004-10-11 05:54:41 +0000721 // Loop over all uses of GV, processing them in turn.
Chris Lattnerbc965b92004-12-02 06:25:58 +0000722 std::vector<StoreInst*> Stores;
Chris Lattner30ba5692004-10-11 05:54:41 +0000723 while (!GV->use_empty())
724 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000725 while (!LI->use_empty()) {
Chris Lattnerd514d822005-02-01 01:23:31 +0000726 Use &LoadUse = LI->use_begin().getUse();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000727 if (!isa<SetCondInst>(LoadUse.getUser()))
728 LoadUse = RepValue;
729 else {
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000730 // Replace the setcc X, 0 with a use of the bool value.
731 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
732 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
Chris Lattnerbc965b92004-12-02 06:25:58 +0000733 InitBoolUsed = true;
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000734 switch (SCI->getOpcode()) {
735 default: assert(0 && "Unknown opcode!");
736 case Instruction::SetLT:
Chris Lattner47811b72006-09-28 23:35:22 +0000737 LV = ConstantBool::getFalse(); // X < null -> always false
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000738 break;
739 case Instruction::SetEQ:
740 case Instruction::SetLE:
741 LV = BinaryOperator::createNot(LV, "notinit", SCI);
742 break;
743 case Instruction::SetNE:
744 case Instruction::SetGE:
745 case Instruction::SetGT:
746 break; // no change.
747 }
748 SCI->replaceAllUsesWith(LV);
749 SCI->eraseFromParent();
750 }
751 }
Chris Lattner7a7ed022004-10-16 18:09:00 +0000752 LI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000753 } else {
754 StoreInst *SI = cast<StoreInst>(GV->use_back());
Chris Lattnerbc965b92004-12-02 06:25:58 +0000755 // The global is initialized when the store to it occurs.
Chris Lattner47811b72006-09-28 23:35:22 +0000756 new StoreInst(ConstantBool::getTrue(), InitBool, SI);
Chris Lattner7a7ed022004-10-16 18:09:00 +0000757 SI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000758 }
759
Chris Lattnerbc965b92004-12-02 06:25:58 +0000760 // If the initialization boolean was used, insert it, otherwise delete it.
761 if (!InitBoolUsed) {
762 while (!InitBool->use_empty()) // Delete initializations
763 cast<Instruction>(InitBool->use_back())->eraseFromParent();
764 delete InitBool;
765 } else
766 GV->getParent()->getGlobalList().insert(GV, InitBool);
767
768
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000769 // Now the GV is dead, nuke it and the malloc.
Chris Lattner7a7ed022004-10-16 18:09:00 +0000770 GV->eraseFromParent();
Chris Lattnere9ece2a2004-10-22 06:43:28 +0000771 MI->eraseFromParent();
Chris Lattner30ba5692004-10-11 05:54:41 +0000772
773 // To further other optimizations, loop over all users of NewGV and try to
774 // constant prop them. This will promote GEP instructions with constant
775 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
776 ConstantPropUsersOf(NewGV);
777 if (RepValue != NewGV)
778 ConstantPropUsersOf(RepValue);
779
780 return NewGV;
781}
Chris Lattner708148e2004-10-10 23:14:11 +0000782
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000783/// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
784/// to make sure that there are no complex uses of V. We permit simple things
785/// like dereferencing the pointer, but not storing through the address, unless
786/// it is to the specified global.
787static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
788 GlobalVariable *GV) {
789 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
790 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
791 // Fine, ignore.
792 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
793 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
794 return false; // Storing the pointer itself... bad.
795 // Otherwise, storing through it, or storing into GV... fine.
796 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
797 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
798 return false;
799 } else {
800 return false;
801 }
802 return true;
Chris Lattnerfa07e4f2004-12-02 07:11:07 +0000803}
804
Chris Lattner86395032006-09-30 23:32:09 +0000805/// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
806/// somewhere. Transform all uses of the allocation into loads from the
807/// global and uses of the resultant pointer. Further, delete the store into
808/// GV. This assumes that these value pass the
809/// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
810static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
811 GlobalVariable *GV) {
812 while (!Alloc->use_empty()) {
813 Instruction *U = Alloc->use_back();
814 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
815 // If this is the store of the allocation into the global, remove it.
816 if (SI->getOperand(1) == GV) {
817 SI->eraseFromParent();
818 continue;
819 }
820 }
821
822 // Insert a load from the global, and use it instead of the malloc.
823 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
824 U->replaceUsesOfWith(Alloc, NL);
825 }
826}
827
828/// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
829/// GV are simple enough to perform HeapSRA, return true.
830static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
831 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
832 ++UI)
833 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
834 // We permit two users of the load: setcc comparing against the null
835 // pointer, and a getelementptr of a specific form.
836 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
837 ++UI) {
838 // Comparison against null is ok.
839 if (SetCondInst *SCI = dyn_cast<SetCondInst>(*UI)) {
840 if (!isa<ConstantPointerNull>(SCI->getOperand(1)))
841 return false;
842 continue;
843 }
844
845 // getelementptr is also ok, but only a simple form.
846 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
847 if (!GEPI) return false;
848
849 // Must index into the array and into the struct.
850 if (GEPI->getNumOperands() < 3)
851 return false;
852
853 // Otherwise the GEP is ok.
854 continue;
855 }
856 }
857 return true;
858}
859
860/// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
861/// is a value loaded from the global. Eliminate all uses of Ptr, making them
862/// use FieldGlobals instead. All uses of loaded values satisfy
863/// GlobalLoadUsesSimpleEnoughForHeapSRA.
864static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
865 const std::vector<GlobalVariable*> &FieldGlobals) {
866 std::vector<Value *> InsertedLoadsForPtr;
867 //InsertedLoadsForPtr.resize(FieldGlobals.size());
868 while (!Ptr->use_empty()) {
869 Instruction *User = Ptr->use_back();
870
871 // If this is a comparison against null, handle it.
872 if (SetCondInst *SCI = dyn_cast<SetCondInst>(User)) {
873 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
874 // If we have a setcc of the loaded pointer, we can use a setcc of any
875 // field.
876 Value *NPtr;
877 if (InsertedLoadsForPtr.empty()) {
878 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
879 InsertedLoadsForPtr.push_back(Ptr);
880 } else {
881 NPtr = InsertedLoadsForPtr.back();
882 }
883
884 Value *New = new SetCondInst(SCI->getOpcode(), NPtr,
885 Constant::getNullValue(NPtr->getType()),
886 SCI->getName(), SCI);
887 SCI->replaceAllUsesWith(New);
888 SCI->eraseFromParent();
889 continue;
890 }
891
892 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
893 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
Reid Spencerb83eb642006-10-20 07:07:24 +0000894 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
895 && GEPI->getOperand(2)->getType()->isUnsigned()
Chris Lattner86395032006-09-30 23:32:09 +0000896 && "Unexpected GEPI!");
897
898 // Load the pointer for this field.
Reid Spencerb83eb642006-10-20 07:07:24 +0000899 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Chris Lattner86395032006-09-30 23:32:09 +0000900 if (InsertedLoadsForPtr.size() <= FieldNo)
901 InsertedLoadsForPtr.resize(FieldNo+1);
902 if (InsertedLoadsForPtr[FieldNo] == 0)
903 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
904 Ptr->getName()+".f" +
905 utostr(FieldNo), Ptr);
906 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
907
908 // Create the new GEP idx vector.
909 std::vector<Value*> GEPIdx;
910 GEPIdx.push_back(GEPI->getOperand(1));
911 GEPIdx.insert(GEPIdx.end(), GEPI->op_begin()+3, GEPI->op_end());
912
913 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx, GEPI->getName(), GEPI);
914 GEPI->replaceAllUsesWith(NGEPI);
915 GEPI->eraseFromParent();
916 }
917}
918
919/// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
920/// it up into multiple allocations of arrays of the fields.
921static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
Bill Wendling0a81aac2006-11-26 10:02:32 +0000922 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
Chris Lattner86395032006-09-30 23:32:09 +0000923 const StructType *STy = cast<StructType>(MI->getAllocatedType());
924
925 // There is guaranteed to be at least one use of the malloc (storing
926 // it into GV). If there are other uses, change them to be uses of
927 // the global to simplify later code. This also deletes the store
928 // into GV.
929 ReplaceUsesOfMallocWithGlobal(MI, GV);
930
931 // Okay, at this point, there are no users of the malloc. Insert N
932 // new mallocs at the same place as MI, and N globals.
933 std::vector<GlobalVariable*> FieldGlobals;
934 std::vector<MallocInst*> FieldMallocs;
935
936 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
937 const Type *FieldTy = STy->getElementType(FieldNo);
938 const Type *PFieldTy = PointerType::get(FieldTy);
939
940 GlobalVariable *NGV =
941 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
942 Constant::getNullValue(PFieldTy),
943 GV->getName() + ".f" + utostr(FieldNo), GV);
944 FieldGlobals.push_back(NGV);
945
946 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
947 MI->getName() + ".f" + utostr(FieldNo),MI);
948 FieldMallocs.push_back(NMI);
949 new StoreInst(NMI, NGV, MI);
950 }
951
952 // The tricky aspect of this transformation is handling the case when malloc
953 // fails. In the original code, malloc failing would set the result pointer
954 // of malloc to null. In this case, some mallocs could succeed and others
955 // could fail. As such, we emit code that looks like this:
956 // F0 = malloc(field0)
957 // F1 = malloc(field1)
958 // F2 = malloc(field2)
959 // if (F0 == 0 || F1 == 0 || F2 == 0) {
960 // if (F0) { free(F0); F0 = 0; }
961 // if (F1) { free(F1); F1 = 0; }
962 // if (F2) { free(F2); F2 = 0; }
963 // }
964 Value *RunningOr = 0;
965 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
966 Value *Cond = new SetCondInst(Instruction::SetEQ, FieldMallocs[i],
967 Constant::getNullValue(FieldMallocs[i]->getType()),
968 "isnull", MI);
969 if (!RunningOr)
970 RunningOr = Cond; // First seteq
971 else
972 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
973 }
974
975 // Split the basic block at the old malloc.
976 BasicBlock *OrigBB = MI->getParent();
977 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
978
979 // Create the block to check the first condition. Put all these blocks at the
980 // end of the function as they are unlikely to be executed.
981 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
982 OrigBB->getParent());
983
984 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
985 // branch on RunningOr.
986 OrigBB->getTerminator()->eraseFromParent();
987 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
988
989 // Within the NullPtrBlock, we need to emit a comparison and branch for each
990 // pointer, because some may be null while others are not.
991 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
992 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
993 Value *Cmp = new SetCondInst(Instruction::SetNE, GVVal,
994 Constant::getNullValue(GVVal->getType()),
995 "tmp", NullPtrBlock);
996 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
997 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
998 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
999
1000 // Fill in FreeBlock.
1001 new FreeInst(GVVal, FreeBlock);
1002 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1003 FreeBlock);
1004 new BranchInst(NextBlock, FreeBlock);
1005
1006 NullPtrBlock = NextBlock;
1007 }
1008
1009 new BranchInst(ContBB, NullPtrBlock);
1010
1011
1012 // MI is no longer needed, remove it.
1013 MI->eraseFromParent();
1014
1015
1016 // Okay, the malloc site is completely handled. All of the uses of GV are now
1017 // loads, and all uses of those loads are simple. Rewrite them to use loads
1018 // of the per-field globals instead.
1019 while (!GV->use_empty()) {
1020 LoadInst *LI = cast<LoadInst>(GV->use_back());
1021 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1022 LI->eraseFromParent();
1023 }
1024
1025 // The old global is now dead, remove it.
1026 GV->eraseFromParent();
1027
1028 ++NumHeapSRA;
1029 return FieldGlobals[0];
1030}
1031
1032
Chris Lattner9b34a612004-10-09 21:48:45 +00001033// OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1034// that only one value (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001035static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Chris Lattner7f8897f2006-08-27 22:42:52 +00001036 Module::global_iterator &GVI,
1037 TargetData &TD) {
Chris Lattner9b34a612004-10-09 21:48:45 +00001038 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1039 StoredOnceVal = CI->getOperand(0);
1040 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
Chris Lattner708148e2004-10-10 23:14:11 +00001041 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
Chris Lattner9b34a612004-10-09 21:48:45 +00001042 bool IsJustACast = true;
1043 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1044 if (!isa<Constant>(GEPI->getOperand(i)) ||
1045 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1046 IsJustACast = false;
1047 break;
1048 }
1049 if (IsJustACast)
1050 StoredOnceVal = GEPI->getOperand(0);
1051 }
1052
Chris Lattner708148e2004-10-10 23:14:11 +00001053 // If we are dealing with a pointer global that is initialized to null and
1054 // only has one (non-null) value stored into it, then we can optimize any
1055 // users of the loaded value (often calls and loads) that would trap if the
1056 // value was null.
Chris Lattner9b34a612004-10-09 21:48:45 +00001057 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1058 GV->getInitializer()->isNullValue()) {
Chris Lattner708148e2004-10-10 23:14:11 +00001059 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1060 if (GV->getInitializer()->getType() != SOVC->getType())
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001061 SOVC = ConstantExpr::getCast(Instruction::BitCast,
1062 SOVC, GV->getInitializer()->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001063
Chris Lattner708148e2004-10-10 23:14:11 +00001064 // Optimize away any trapping uses of the loaded value.
1065 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
Chris Lattner8be80122004-10-10 17:07:12 +00001066 return true;
Chris Lattner30ba5692004-10-11 05:54:41 +00001067 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001068 // If this is a malloc of an abstract type, don't touch it.
1069 if (!MI->getAllocatedType()->isSized())
1070 return false;
1071
Chris Lattner86395032006-09-30 23:32:09 +00001072 // We can't optimize this global unless all uses of it are *known* to be
1073 // of the malloc value, not of the null initializer value (consider a use
1074 // that compares the global's value against zero to see if the malloc has
1075 // been reached). To do this, we check to see if all uses of the global
1076 // would trap if the global were null: this proves that they must all
1077 // happen after the malloc.
1078 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1079 return false;
1080
1081 // We can't optimize this if the malloc itself is used in a complex way,
1082 // for example, being stored into multiple globals. This allows the
1083 // malloc to be stored into the specified global, loaded setcc'd, and
1084 // GEP'd. These are all things we could transform to using the global
1085 // for.
1086 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1087 return false;
1088
1089
Chris Lattner30ba5692004-10-11 05:54:41 +00001090 // If we have a global that is only initialized with a fixed size malloc,
Chris Lattner86395032006-09-30 23:32:09 +00001091 // transform the program to use global memory instead of malloc'd memory.
1092 // This eliminates dynamic allocation, avoids an indirection accessing the
1093 // data, and exposes the resultant global to further GlobalOpt.
Chris Lattnercff16732006-09-30 19:40:30 +00001094 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
Chris Lattner86395032006-09-30 23:32:09 +00001095 // Restrict this transformation to only working on small allocations
1096 // (2048 bytes currently), as we don't want to introduce a 16M global or
1097 // something.
Reid Spencerb83eb642006-10-20 07:07:24 +00001098 if (NElements->getZExtValue()*
Chris Lattner86395032006-09-30 23:32:09 +00001099 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
Chris Lattner30ba5692004-10-11 05:54:41 +00001100 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1101 return true;
1102 }
Chris Lattnercff16732006-09-30 19:40:30 +00001103 }
Chris Lattner86395032006-09-30 23:32:09 +00001104
1105 // If the allocation is an array of structures, consider transforming this
1106 // into multiple malloc'd arrays, one for each field. This is basically
1107 // SRoA for malloc'd memory.
1108 if (const StructType *AllocTy =
1109 dyn_cast<StructType>(MI->getAllocatedType())) {
1110 // This the structure has an unreasonable number of fields, leave it
1111 // alone.
1112 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1113 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1114 GVI = PerformHeapAllocSRoA(GV, MI);
1115 return true;
1116 }
1117 }
Chris Lattner708148e2004-10-10 23:14:11 +00001118 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001119 }
Chris Lattner30ba5692004-10-11 05:54:41 +00001120
Chris Lattner9b34a612004-10-09 21:48:45 +00001121 return false;
1122}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001123
Chris Lattner96a86b22004-12-12 05:53:50 +00001124/// ShrinkGlobalToBoolean - At this point, we have learned that the only two
Misha Brukmanfd939082005-04-21 23:48:37 +00001125/// values ever stored into GV are its initializer and OtherVal.
Chris Lattner96a86b22004-12-12 05:53:50 +00001126static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1127 // Create the new global, initializing it to false.
1128 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
Chris Lattner47811b72006-09-28 23:35:22 +00001129 GlobalValue::InternalLinkage, ConstantBool::getFalse(),
1130 GV->getName()+".b");
Chris Lattner96a86b22004-12-12 05:53:50 +00001131 GV->getParent()->getGlobalList().insert(GV, NewGV);
1132
1133 Constant *InitVal = GV->getInitializer();
1134 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
1135
1136 // If initialized to zero and storing one into the global, we can use a cast
1137 // instead of a select to synthesize the desired value.
1138 bool IsOneZero = false;
1139 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1140 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
1141
1142 while (!GV->use_empty()) {
1143 Instruction *UI = cast<Instruction>(GV->use_back());
1144 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1145 // Change the store into a boolean store.
1146 bool StoringOther = SI->getOperand(0) == OtherVal;
1147 // Only do this if we weren't storing a loaded value.
Chris Lattner38c25562004-12-12 19:34:41 +00001148 Value *StoreVal;
Chris Lattner96a86b22004-12-12 05:53:50 +00001149 if (StoringOther || SI->getOperand(0) == InitVal)
Chris Lattner38c25562004-12-12 19:34:41 +00001150 StoreVal = ConstantBool::get(StoringOther);
1151 else {
1152 // Otherwise, we are storing a previously loaded copy. To do this,
1153 // change the copy from copying the original value to just copying the
1154 // bool.
1155 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1156
1157 // If we're already replaced the input, StoredVal will be a cast or
1158 // select instruction. If not, it will be a load of the original
1159 // global.
1160 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1161 assert(LI->getOperand(0) == GV && "Not a copy!");
1162 // Insert a new load, to preserve the saved value.
1163 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1164 } else {
1165 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1166 "This is not a form that we understand!");
1167 StoreVal = StoredVal->getOperand(0);
1168 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1169 }
1170 }
1171 new StoreInst(StoreVal, NewGV, SI);
1172 } else if (!UI->use_empty()) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001173 // Change the load into a load of bool then a select.
1174 LoadInst *LI = cast<LoadInst>(UI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001175
Chris Lattner96a86b22004-12-12 05:53:50 +00001176 std::string Name = LI->getName(); LI->setName("");
1177 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
1178 Value *NSI;
1179 if (IsOneZero)
Chris Lattnerd0a6a7a2006-11-30 17:35:08 +00001180 NSI = new ZExtInst(NLI, LI->getType(), Name, LI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001181 else
Chris Lattner96a86b22004-12-12 05:53:50 +00001182 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
1183 LI->replaceAllUsesWith(NSI);
1184 }
1185 UI->eraseFromParent();
1186 }
1187
1188 GV->eraseFromParent();
1189}
1190
1191
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001192/// ProcessInternalGlobal - Analyze the specified global variable and optimize
1193/// it if possible. If we make a change, return true.
Chris Lattner30ba5692004-10-11 05:54:41 +00001194bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Chris Lattnere4d5c442005-03-15 04:54:21 +00001195 Module::global_iterator &GVI) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001196 std::set<PHINode*> PHIUsers;
1197 GlobalStatus GS;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001198 GV->removeDeadConstantUsers();
1199
1200 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001201 DOUT << "GLOBAL DEAD: " << *GV;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001202 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001203 ++NumDeleted;
1204 return true;
1205 }
1206
1207 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
Chris Lattnercff16732006-09-30 19:40:30 +00001208#if 0
Bill Wendling0a81aac2006-11-26 10:02:32 +00001209 llvm_cerr << "Global: " << *GV;
1210 llvm_cerr << " isLoaded = " << GS.isLoaded << "\n";
1211 llvm_cerr << " StoredType = ";
Chris Lattnercff16732006-09-30 19:40:30 +00001212 switch (GS.StoredType) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001213 case GlobalStatus::NotStored: llvm_cerr << "NEVER STORED\n"; break;
1214 case GlobalStatus::isInitializerStored: llvm_cerr << "INIT STORED\n"; break;
1215 case GlobalStatus::isStoredOnce: llvm_cerr << "STORED ONCE\n"; break;
1216 case GlobalStatus::isStored: llvm_cerr << "stored\n"; break;
Chris Lattnercff16732006-09-30 19:40:30 +00001217 }
1218 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
Bill Wendling0a81aac2006-11-26 10:02:32 +00001219 llvm_cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001220 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
Bill Wendling0a81aac2006-11-26 10:02:32 +00001221 llvm_cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
Chris Lattnercff16732006-09-30 19:40:30 +00001222 << "\n";
Bill Wendling0a81aac2006-11-26 10:02:32 +00001223 llvm_cerr << " HasMultipleAccessingFunctions = "
Chris Lattnercff16732006-09-30 19:40:30 +00001224 << GS.HasMultipleAccessingFunctions << "\n";
Bill Wendling0a81aac2006-11-26 10:02:32 +00001225 llvm_cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1226 llvm_cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1227 llvm_cerr << "\n";
Chris Lattnercff16732006-09-30 19:40:30 +00001228#endif
1229
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001230 // If this is a first class global and has only one accessing function
1231 // and this function is main (which we know is not recursive we can make
1232 // this global a local variable) we replace the global with a local alloca
1233 // in this function.
1234 //
1235 // NOTE: It doesn't make sense to promote non first class types since we
1236 // are just replacing static memory to stack memory.
1237 if (!GS.HasMultipleAccessingFunctions &&
Chris Lattner553ca522005-06-15 21:11:48 +00001238 GS.AccessingFunction && !GS.HasNonInstructionUser &&
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001239 GV->getType()->getElementType()->isFirstClassType() &&
1240 GS.AccessingFunction->getName() == "main" &&
1241 GS.AccessingFunction->hasExternalLinkage()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001242 DOUT << "LOCALIZING GLOBAL: " << *GV;
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001243 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1244 const Type* ElemTy = GV->getType()->getElementType();
Nate Begeman14b05292005-11-05 09:21:28 +00001245 // FIXME: Pass Global's alignment when globals have alignment
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001246 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1247 if (!isa<UndefValue>(GV->getInitializer()))
1248 new StoreInst(GV->getInitializer(), Alloca, FirstI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001249
Alkis Evlogimenosf64ea9d2005-02-10 18:36:30 +00001250 GV->replaceAllUsesWith(Alloca);
1251 GV->eraseFromParent();
1252 ++NumLocalized;
1253 return true;
1254 }
Chris Lattnercff16732006-09-30 19:40:30 +00001255
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001256 // If the global is never loaded (but may be stored to), it is dead.
1257 // Delete it now.
1258 if (!GS.isLoaded) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001259 DOUT << "GLOBAL NEVER LOADED: " << *GV;
Chris Lattner930f4752004-10-09 03:32:52 +00001260
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001261 // Delete any stores we can find to the global. We may not be able to
1262 // make it completely dead though.
Chris Lattner031955d2004-10-10 16:43:46 +00001263 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
Chris Lattner930f4752004-10-09 03:32:52 +00001264
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001265 // If the global is dead now, delete it.
1266 if (GV->use_empty()) {
Chris Lattner7a7ed022004-10-16 18:09:00 +00001267 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001268 ++NumDeleted;
Chris Lattner930f4752004-10-09 03:32:52 +00001269 Changed = true;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001270 }
Chris Lattner930f4752004-10-09 03:32:52 +00001271 return Changed;
Misha Brukmanfd939082005-04-21 23:48:37 +00001272
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001273 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001274 DOUT << "MARKING CONSTANT: " << *GV;
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001275 GV->setConstant(true);
Misha Brukmanfd939082005-04-21 23:48:37 +00001276
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001277 // Clean up any obviously simplifiable users now.
1278 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001279
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001280 // If the global is dead now, just nuke it.
1281 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001282 DOUT << " *** Marking constant allowed us to simplify "
1283 << "all users and delete global!\n";
Chris Lattner7a7ed022004-10-16 18:09:00 +00001284 GV->eraseFromParent();
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001285 ++NumDeleted;
1286 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001287
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001288 ++NumMarked;
1289 return true;
1290 } else if (!GS.isNotSuitableForSRA &&
1291 !GV->getInitializer()->getType()->isFirstClassType()) {
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001292 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1293 GVI = FirstNewGV; // Don't skip the newly produced globals!
1294 return true;
1295 }
Chris Lattner9b34a612004-10-09 21:48:45 +00001296 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
Chris Lattner96a86b22004-12-12 05:53:50 +00001297 // If the initial value for the global was an undef value, and if only
1298 // one other value was stored into it, we can just change the
1299 // initializer to be an undef value, then delete all stores to the
1300 // global. This allows us to mark it constant.
1301 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1302 if (isa<UndefValue>(GV->getInitializer())) {
1303 // Change the initial value here.
1304 GV->setInitializer(SOVConstant);
Misha Brukmanfd939082005-04-21 23:48:37 +00001305
Chris Lattner96a86b22004-12-12 05:53:50 +00001306 // Clean up any obviously simplifiable users now.
1307 CleanupConstantGlobalUsers(GV, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00001308
Chris Lattner96a86b22004-12-12 05:53:50 +00001309 if (GV->use_empty()) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001310 DOUT << " *** Substituting initializer allowed us to "
1311 << "simplify all users and delete global!\n";
Chris Lattner96a86b22004-12-12 05:53:50 +00001312 GV->eraseFromParent();
1313 ++NumDeleted;
1314 } else {
1315 GVI = GV;
1316 }
1317 ++NumSubstitute;
1318 return true;
Chris Lattner7a7ed022004-10-16 18:09:00 +00001319 }
Chris Lattner7a7ed022004-10-16 18:09:00 +00001320
Chris Lattner9b34a612004-10-09 21:48:45 +00001321 // Try to optimize globals based on the knowledge that only one value
1322 // (besides its initializer) is ever stored to the global.
Chris Lattner30ba5692004-10-11 05:54:41 +00001323 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1324 getAnalysis<TargetData>()))
Chris Lattner9b34a612004-10-09 21:48:45 +00001325 return true;
Chris Lattner96a86b22004-12-12 05:53:50 +00001326
1327 // Otherwise, if the global was not a boolean, we can shrink it to be a
1328 // boolean.
1329 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
Chris Lattner077f1a82004-12-12 06:03:06 +00001330 if (GV->getType()->getElementType() != Type::BoolTy &&
Chris Lattner25de4e52006-11-01 18:03:33 +00001331 !GV->getType()->getElementType()->isFloatingPoint() &&
1332 !GS.HasPHIUser) {
Bill Wendling0a81aac2006-11-26 10:02:32 +00001333 DOUT << " *** SHRINKING TO BOOL: " << *GV;
Chris Lattner96a86b22004-12-12 05:53:50 +00001334 ShrinkGlobalToBoolean(GV, SOVConstant);
1335 ++NumShrunkToBool;
1336 return true;
1337 }
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001338 }
1339 }
1340 return false;
1341}
1342
Chris Lattnerfb217ad2005-05-08 22:18:06 +00001343/// OnlyCalledDirectly - Return true if the specified function is only called
1344/// directly. In other words, its address is never taken.
1345static bool OnlyCalledDirectly(Function *F) {
1346 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1347 Instruction *User = dyn_cast<Instruction>(*UI);
1348 if (!User) return false;
1349 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1350
1351 // See if the function address is passed as an argument.
1352 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1353 if (User->getOperand(i) == F) return false;
1354 }
1355 return true;
1356}
1357
1358/// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1359/// function, changing them to FastCC.
1360static void ChangeCalleesToFastCall(Function *F) {
1361 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1362 Instruction *User = cast<Instruction>(*UI);
1363 if (CallInst *CI = dyn_cast<CallInst>(User))
1364 CI->setCallingConv(CallingConv::Fast);
1365 else
1366 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1367 }
1368}
Chris Lattnera4be1dc2004-10-08 20:59:28 +00001369
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001370bool GlobalOpt::OptimizeFunctions(Module &M) {
1371 bool Changed = false;
1372 // Optimize functions.
1373 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1374 Function *F = FI++;
1375 F->removeDeadConstantUsers();
1376 if (F->use_empty() && (F->hasInternalLinkage() ||
1377 F->hasLinkOnceLinkage())) {
1378 M.getFunctionList().erase(F);
1379 Changed = true;
1380 ++NumFnDeleted;
1381 } else if (F->hasInternalLinkage() &&
1382 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1383 OnlyCalledDirectly(F)) {
1384 // If this function has C calling conventions, is not a varargs
1385 // function, and is only called directly, promote it to use the Fast
1386 // calling convention.
1387 F->setCallingConv(CallingConv::Fast);
1388 ChangeCalleesToFastCall(F);
1389 ++NumFastCallFns;
1390 Changed = true;
1391 }
1392 }
1393 return Changed;
1394}
1395
1396bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1397 bool Changed = false;
1398 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1399 GVI != E; ) {
1400 GlobalVariable *GV = GVI++;
1401 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1402 GV->hasInitializer())
1403 Changed |= ProcessInternalGlobal(GV, GVI);
1404 }
1405 return Changed;
1406}
1407
1408/// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1409/// initializers have an init priority of 65535.
1410GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
Alkis Evlogimenose9c6d362005-10-25 11:18:06 +00001411 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1412 I != E; ++I)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001413 if (I->getName() == "llvm.global_ctors") {
1414 // Found it, verify it's an array of { int, void()* }.
1415 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1416 if (!ATy) return 0;
1417 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1418 if (!STy || STy->getNumElements() != 2 ||
1419 STy->getElementType(0) != Type::IntTy) return 0;
1420 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1421 if (!PFTy) return 0;
1422 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1423 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1424 FTy->getNumParams() != 0)
1425 return 0;
1426
1427 // Verify that the initializer is simple enough for us to handle.
1428 if (!I->hasInitializer()) return 0;
1429 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1430 if (!CA) return 0;
1431 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1432 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001433 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1434 continue;
1435
1436 // Must have a function or null ptr.
1437 if (!isa<Function>(CS->getOperand(1)))
1438 return 0;
1439
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001440 // Init priority must be standard.
1441 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
Reid Spencerb83eb642006-10-20 07:07:24 +00001442 if (!CI || CI->getZExtValue() != 65535)
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001443 return 0;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001444 } else {
1445 return 0;
1446 }
1447
1448 return I;
1449 }
1450 return 0;
1451}
1452
Chris Lattnerdb973e62005-09-26 02:31:18 +00001453/// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1454/// return a list of the functions and null terminator as a vector.
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001455static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1456 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1457 std::vector<Function*> Result;
1458 Result.reserve(CA->getNumOperands());
1459 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1460 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1461 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1462 }
1463 return Result;
1464}
1465
Chris Lattnerdb973e62005-09-26 02:31:18 +00001466/// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1467/// specified array, returning the new global to use.
1468static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1469 const std::vector<Function*> &Ctors) {
1470 // If we made a change, reassemble the initializer list.
1471 std::vector<Constant*> CSVals;
Reid Spencerb83eb642006-10-20 07:07:24 +00001472 CSVals.push_back(ConstantInt::get(Type::IntTy, 65535));
Chris Lattnerdb973e62005-09-26 02:31:18 +00001473 CSVals.push_back(0);
1474
1475 // Create the new init list.
1476 std::vector<Constant*> CAList;
1477 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
Chris Lattner79c11012005-09-26 04:44:35 +00001478 if (Ctors[i]) {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001479 CSVals[1] = Ctors[i];
Chris Lattner79c11012005-09-26 04:44:35 +00001480 } else {
Chris Lattnerdb973e62005-09-26 02:31:18 +00001481 const Type *FTy = FunctionType::get(Type::VoidTy,
1482 std::vector<const Type*>(), false);
1483 const PointerType *PFTy = PointerType::get(FTy);
1484 CSVals[1] = Constant::getNullValue(PFTy);
Reid Spencerb83eb642006-10-20 07:07:24 +00001485 CSVals[0] = ConstantInt::get(Type::IntTy, 2147483647);
Chris Lattnerdb973e62005-09-26 02:31:18 +00001486 }
1487 CAList.push_back(ConstantStruct::get(CSVals));
1488 }
1489
1490 // Create the array initializer.
1491 const Type *StructTy =
1492 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1493 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1494 CAList);
1495
1496 // If we didn't change the number of elements, don't create a new GV.
1497 if (CA->getType() == GCL->getInitializer()->getType()) {
1498 GCL->setInitializer(CA);
1499 return GCL;
1500 }
1501
1502 // Create the new global and insert it next to the existing list.
1503 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1504 GCL->getLinkage(), CA,
1505 GCL->getName());
1506 GCL->setName("");
1507 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1508
1509 // Nuke the old list, replacing any uses with the new one.
1510 if (!GCL->use_empty()) {
1511 Constant *V = NGV;
1512 if (V->getType() != GCL->getType())
Chris Lattner6e8fbad2006-11-30 17:32:29 +00001513 V = ConstantExpr::getCast(Instruction::BitCast, V, GCL->getType());
Chris Lattnerdb973e62005-09-26 02:31:18 +00001514 GCL->replaceAllUsesWith(V);
1515 }
1516 GCL->eraseFromParent();
1517
1518 if (Ctors.size())
1519 return NGV;
1520 else
1521 return 0;
1522}
Chris Lattner79c11012005-09-26 04:44:35 +00001523
1524
1525static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1526 Value *V) {
1527 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1528 Constant *R = ComputedValues[V];
1529 assert(R && "Reference to an uncomputed value!");
1530 return R;
1531}
1532
1533/// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1534/// enough for us to understand. In particular, if it is a cast of something,
1535/// we punt. We basically just support direct accesses to globals and GEP's of
1536/// globals. This should be kept up to date with CommitValueTo.
1537static bool isSimpleEnoughPointerToCommit(Constant *C) {
Chris Lattner231308c2005-09-27 04:50:03 +00001538 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1539 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001540 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner79c11012005-09-26 04:44:35 +00001541 return !GV->isExternal(); // reject external globals.
Chris Lattner231308c2005-09-27 04:50:03 +00001542 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001543 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1544 // Handle a constantexpr gep.
1545 if (CE->getOpcode() == Instruction::GetElementPtr &&
1546 isa<GlobalVariable>(CE->getOperand(0))) {
1547 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Chris Lattner231308c2005-09-27 04:50:03 +00001548 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001549 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
Chris Lattner798b4d52005-09-26 06:52:44 +00001550 return GV->hasInitializer() &&
1551 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1552 }
Chris Lattner79c11012005-09-26 04:44:35 +00001553 return false;
1554}
1555
Chris Lattner798b4d52005-09-26 06:52:44 +00001556/// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1557/// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1558/// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1559static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1560 ConstantExpr *Addr, unsigned OpNo) {
1561 // Base case of the recursion.
1562 if (OpNo == Addr->getNumOperands()) {
1563 assert(Val->getType() == Init->getType() && "Type mismatch!");
1564 return Val;
1565 }
1566
1567 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1568 std::vector<Constant*> Elts;
1569
1570 // Break up the constant into its elements.
1571 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1572 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1573 Elts.push_back(CS->getOperand(i));
1574 } else if (isa<ConstantAggregateZero>(Init)) {
1575 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1576 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1577 } else if (isa<UndefValue>(Init)) {
1578 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1579 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1580 } else {
1581 assert(0 && "This code is out of sync with "
1582 " ConstantFoldLoadThroughGEPConstantExpr");
1583 }
1584
1585 // Replace the element that we are supposed to.
Reid Spencerb83eb642006-10-20 07:07:24 +00001586 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1587 unsigned Idx = CU->getZExtValue();
1588 assert(Idx < STy->getNumElements() && "Struct index out of range!");
Chris Lattner798b4d52005-09-26 06:52:44 +00001589 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1590
1591 // Return the modified struct.
1592 return ConstantStruct::get(Elts);
1593 } else {
1594 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1595 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1596
1597 // Break up the array into elements.
1598 std::vector<Constant*> Elts;
1599 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1600 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1601 Elts.push_back(CA->getOperand(i));
1602 } else if (isa<ConstantAggregateZero>(Init)) {
1603 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1604 Elts.assign(ATy->getNumElements(), Elt);
1605 } else if (isa<UndefValue>(Init)) {
1606 Constant *Elt = UndefValue::get(ATy->getElementType());
1607 Elts.assign(ATy->getNumElements(), Elt);
1608 } else {
1609 assert(0 && "This code is out of sync with "
1610 " ConstantFoldLoadThroughGEPConstantExpr");
1611 }
1612
Reid Spencerb83eb642006-10-20 07:07:24 +00001613 assert(CI->getZExtValue() < ATy->getNumElements());
1614 Elts[CI->getZExtValue()] =
1615 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
Chris Lattner798b4d52005-09-26 06:52:44 +00001616 return ConstantArray::get(ATy, Elts);
1617 }
1618}
1619
Chris Lattner79c11012005-09-26 04:44:35 +00001620/// CommitValueTo - We have decided that Addr (which satisfies the predicate
1621/// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1622static void CommitValueTo(Constant *Val, Constant *Addr) {
Chris Lattner798b4d52005-09-26 06:52:44 +00001623 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1624 assert(GV->hasInitializer());
1625 GV->setInitializer(Val);
1626 return;
1627 }
1628
1629 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1630 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1631
1632 Constant *Init = GV->getInitializer();
1633 Init = EvaluateStoreInto(Init, Val, CE, 2);
1634 GV->setInitializer(Init);
Chris Lattner79c11012005-09-26 04:44:35 +00001635}
1636
Chris Lattner562a0552005-09-26 05:16:34 +00001637/// ComputeLoadResult - Return the value that would be computed by a load from
1638/// P after the stores reflected by 'memory' have been performed. If we can't
1639/// decide, return null.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001640static Constant *ComputeLoadResult(Constant *P,
1641 const std::map<Constant*, Constant*> &Memory) {
1642 // If this memory location has been recently stored, use the stored value: it
1643 // is the most up-to-date.
1644 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1645 if (I != Memory.end()) return I->second;
1646
1647 // Access it.
1648 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1649 if (GV->hasInitializer())
1650 return GV->getInitializer();
1651 return 0;
Chris Lattner04de1cf2005-09-26 05:15:37 +00001652 }
Chris Lattner798b4d52005-09-26 06:52:44 +00001653
1654 // Handle a constantexpr getelementptr.
1655 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1656 if (CE->getOpcode() == Instruction::GetElementPtr &&
1657 isa<GlobalVariable>(CE->getOperand(0))) {
1658 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1659 if (GV->hasInitializer())
1660 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1661 }
1662
1663 return 0; // don't know how to evaluate.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001664}
1665
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001666/// EvaluateFunction - Evaluate a call to function F, returning true if
1667/// successful, false if we can't evaluate it. ActualArgs contains the formal
1668/// arguments for the function.
Chris Lattnercd271422005-09-27 04:45:34 +00001669static bool EvaluateFunction(Function *F, Constant *&RetVal,
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001670 const std::vector<Constant*> &ActualArgs,
1671 std::vector<Function*> &CallStack,
1672 std::map<Constant*, Constant*> &MutatedMemory,
1673 std::vector<GlobalVariable*> &AllocaTmps) {
Chris Lattnercd271422005-09-27 04:45:34 +00001674 // Check to see if this function is already executing (recursion). If so,
1675 // bail out. TODO: we might want to accept limited recursion.
1676 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1677 return false;
1678
1679 CallStack.push_back(F);
1680
Chris Lattner79c11012005-09-26 04:44:35 +00001681 /// Values - As we compute SSA register values, we store their contents here.
1682 std::map<Value*, Constant*> Values;
Chris Lattnercd271422005-09-27 04:45:34 +00001683
1684 // Initialize arguments to the incoming values specified.
1685 unsigned ArgNo = 0;
1686 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1687 ++AI, ++ArgNo)
1688 Values[AI] = ActualArgs[ArgNo];
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001689
Chris Lattnercdf98be2005-09-26 04:57:38 +00001690 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1691 /// we can only evaluate any one basic block at most once. This set keeps
1692 /// track of what we have executed so we can detect recursive cases etc.
1693 std::set<BasicBlock*> ExecutedBlocks;
Chris Lattnera22fdb02005-09-26 17:07:09 +00001694
Chris Lattner79c11012005-09-26 04:44:35 +00001695 // CurInst - The current instruction we're evaluating.
1696 BasicBlock::iterator CurInst = F->begin()->begin();
1697
1698 // This is the main evaluation loop.
1699 while (1) {
1700 Constant *InstResult = 0;
1701
1702 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001703 if (SI->isVolatile()) return false; // no volatile accesses.
Chris Lattner79c11012005-09-26 04:44:35 +00001704 Constant *Ptr = getVal(Values, SI->getOperand(1));
1705 if (!isSimpleEnoughPointerToCommit(Ptr))
1706 // If this is too complex for us to commit, reject it.
Chris Lattnercd271422005-09-27 04:45:34 +00001707 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00001708 Constant *Val = getVal(Values, SI->getOperand(0));
1709 MutatedMemory[Ptr] = Val;
1710 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1711 InstResult = ConstantExpr::get(BO->getOpcode(),
1712 getVal(Values, BO->getOperand(0)),
1713 getVal(Values, BO->getOperand(1)));
1714 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1715 InstResult = ConstantExpr::get(SI->getOpcode(),
1716 getVal(Values, SI->getOperand(0)),
1717 getVal(Values, SI->getOperand(1)));
1718 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
Chris Lattner9a989f02006-11-30 17:26:08 +00001719 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1720 getVal(Values, CI->getOperand(0)),
Chris Lattner79c11012005-09-26 04:44:35 +00001721 CI->getType());
1722 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1723 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1724 getVal(Values, SI->getOperand(1)),
1725 getVal(Values, SI->getOperand(2)));
Chris Lattner04de1cf2005-09-26 05:15:37 +00001726 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1727 Constant *P = getVal(Values, GEP->getOperand(0));
1728 std::vector<Constant*> GEPOps;
1729 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1730 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1731 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1732 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001733 if (LI->isVolatile()) return false; // no volatile accesses.
Chris Lattner04de1cf2005-09-26 05:15:37 +00001734 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1735 MutatedMemory);
Chris Lattnercd271422005-09-27 04:45:34 +00001736 if (InstResult == 0) return false; // Could not evaluate load.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001737 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001738 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
Chris Lattnera22fdb02005-09-26 17:07:09 +00001739 const Type *Ty = AI->getType()->getElementType();
1740 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1741 GlobalValue::InternalLinkage,
1742 UndefValue::get(Ty),
1743 AI->getName()));
Chris Lattnercd271422005-09-27 04:45:34 +00001744 InstResult = AllocaTmps.back();
1745 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
Chris Lattner7cd580f2006-07-07 21:37:01 +00001746 // Cannot handle inline asm.
1747 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1748
Chris Lattnercd271422005-09-27 04:45:34 +00001749 // Resolve function pointers.
1750 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1751 if (!Callee) return false; // Cannot resolve.
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001752
Chris Lattnercd271422005-09-27 04:45:34 +00001753 std::vector<Constant*> Formals;
1754 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1755 Formals.push_back(getVal(Values, CI->getOperand(i)));
Chris Lattnercd271422005-09-27 04:45:34 +00001756
Chris Lattnera9ec8ab2005-09-27 05:02:43 +00001757 if (Callee->isExternal()) {
1758 // If this is a function we can constant fold, do it.
1759 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
1760 InstResult = C;
1761 } else {
1762 return false;
1763 }
1764 } else {
1765 if (Callee->getFunctionType()->isVarArg())
1766 return false;
1767
1768 Constant *RetVal;
1769
1770 // Execute the call, if successful, use the return value.
1771 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1772 MutatedMemory, AllocaTmps))
1773 return false;
1774 InstResult = RetVal;
1775 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001776 } else if (isa<TerminatorInst>(CurInst)) {
Chris Lattnercdf98be2005-09-26 04:57:38 +00001777 BasicBlock *NewBB = 0;
1778 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1779 if (BI->isUnconditional()) {
1780 NewBB = BI->getSuccessor(0);
1781 } else {
1782 ConstantBool *Cond =
1783 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00001784 if (!Cond) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001785 NewBB = BI->getSuccessor(!Cond->getValue());
1786 }
1787 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1788 ConstantInt *Val =
1789 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
Chris Lattnercd271422005-09-27 04:45:34 +00001790 if (!Val) return false; // Cannot determine.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001791 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1792 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
Chris Lattnercd271422005-09-27 04:45:34 +00001793 if (RI->getNumOperands())
1794 RetVal = getVal(Values, RI->getOperand(0));
1795
1796 CallStack.pop_back(); // return from fn.
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001797 return true; // We succeeded at evaluating this ctor!
Chris Lattnercdf98be2005-09-26 04:57:38 +00001798 } else {
Chris Lattnercd271422005-09-27 04:45:34 +00001799 // invoke, unwind, unreachable.
1800 return false; // Cannot handle this terminator.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001801 }
1802
1803 // Okay, we succeeded in evaluating this control flow. See if we have
Chris Lattnercd271422005-09-27 04:45:34 +00001804 // executed the new block before. If so, we have a looping function,
1805 // which we cannot evaluate in reasonable time.
Chris Lattnercdf98be2005-09-26 04:57:38 +00001806 if (!ExecutedBlocks.insert(NewBB).second)
Chris Lattnercd271422005-09-27 04:45:34 +00001807 return false; // looped!
Chris Lattnercdf98be2005-09-26 04:57:38 +00001808
1809 // Okay, we have never been in this block before. Check to see if there
1810 // are any PHI nodes. If so, evaluate them with information about where
1811 // we came from.
1812 BasicBlock *OldBB = CurInst->getParent();
1813 CurInst = NewBB->begin();
1814 PHINode *PN;
1815 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1816 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1817
1818 // Do NOT increment CurInst. We know that the terminator had no value.
1819 continue;
Chris Lattner79c11012005-09-26 04:44:35 +00001820 } else {
Chris Lattner79c11012005-09-26 04:44:35 +00001821 // Did not know how to evaluate this!
Chris Lattnercd271422005-09-27 04:45:34 +00001822 return false;
Chris Lattner79c11012005-09-26 04:44:35 +00001823 }
1824
1825 if (!CurInst->use_empty())
1826 Values[CurInst] = InstResult;
1827
1828 // Advance program counter.
1829 ++CurInst;
1830 }
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001831}
1832
1833/// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1834/// we can. Return true if we can, false otherwise.
1835static bool EvaluateStaticConstructor(Function *F) {
1836 /// MutatedMemory - For each store we execute, we update this map. Loads
1837 /// check this to get the most up-to-date value. If evaluation is successful,
1838 /// this state is committed to the process.
1839 std::map<Constant*, Constant*> MutatedMemory;
1840
1841 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1842 /// to represent its body. This vector is needed so we can delete the
1843 /// temporary globals when we are done.
1844 std::vector<GlobalVariable*> AllocaTmps;
1845
1846 /// CallStack - This is used to detect recursion. In pathological situations
1847 /// we could hit exponential behavior, but at least there is nothing
1848 /// unbounded.
1849 std::vector<Function*> CallStack;
1850
1851 // Call the function.
Chris Lattnercd271422005-09-27 04:45:34 +00001852 Constant *RetValDummy;
1853 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1854 CallStack, MutatedMemory, AllocaTmps);
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001855 if (EvalSuccess) {
Chris Lattnera22fdb02005-09-26 17:07:09 +00001856 // We succeeded at evaluation: commit the result.
Bill Wendling0a81aac2006-11-26 10:02:32 +00001857 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1858 << F->getName() << "' to " << MutatedMemory.size()
1859 << " stores.\n";
Chris Lattnera22fdb02005-09-26 17:07:09 +00001860 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1861 E = MutatedMemory.end(); I != E; ++I)
1862 CommitValueTo(I->second, I->first);
1863 }
Chris Lattner79c11012005-09-26 04:44:35 +00001864
Chris Lattnera22fdb02005-09-26 17:07:09 +00001865 // At this point, we are done interpreting. If we created any 'alloca'
1866 // temporaries, release them now.
1867 while (!AllocaTmps.empty()) {
1868 GlobalVariable *Tmp = AllocaTmps.back();
1869 AllocaTmps.pop_back();
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001870
Chris Lattnera22fdb02005-09-26 17:07:09 +00001871 // If there are still users of the alloca, the program is doing something
1872 // silly, e.g. storing the address of the alloca somewhere and using it
1873 // later. Since this is undefined, we'll just make it be null.
1874 if (!Tmp->use_empty())
1875 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1876 delete Tmp;
1877 }
Chris Lattneraae4a1c2005-09-26 07:34:35 +00001878
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001879 return EvalSuccess;
Chris Lattner79c11012005-09-26 04:44:35 +00001880}
1881
Chris Lattnerdb973e62005-09-26 02:31:18 +00001882
Chris Lattner8a7cc6e2005-09-27 04:27:01 +00001883
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001884/// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1885/// Return true if anything changed.
1886bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1887 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1888 bool MadeChange = false;
1889 if (Ctors.empty()) return false;
1890
1891 // Loop over global ctors, optimizing them when we can.
1892 for (unsigned i = 0; i != Ctors.size(); ++i) {
1893 Function *F = Ctors[i];
1894 // Found a null terminator in the middle of the list, prune off the rest of
1895 // the list.
Chris Lattner7d8e58f2005-09-26 02:19:27 +00001896 if (F == 0) {
1897 if (i != Ctors.size()-1) {
1898 Ctors.resize(i+1);
1899 MadeChange = true;
1900 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001901 break;
1902 }
1903
Chris Lattner79c11012005-09-26 04:44:35 +00001904 // We cannot simplify external ctor functions.
1905 if (F->empty()) continue;
1906
1907 // If we can evaluate the ctor at compile time, do.
1908 if (EvaluateStaticConstructor(F)) {
1909 Ctors.erase(Ctors.begin()+i);
1910 MadeChange = true;
1911 --i;
1912 ++NumCtorsEvaluated;
1913 continue;
1914 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001915 }
1916
1917 if (!MadeChange) return false;
1918
Chris Lattnerdb973e62005-09-26 02:31:18 +00001919 GCL = InstallGlobalCtors(GCL, Ctors);
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001920 return true;
1921}
1922
1923
Chris Lattner7a90b682004-10-07 04:16:33 +00001924bool GlobalOpt::runOnModule(Module &M) {
Chris Lattner079236d2004-02-25 21:34:36 +00001925 bool Changed = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001926
1927 // Try to find the llvm.globalctors list.
1928 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00001929
Chris Lattner7a90b682004-10-07 04:16:33 +00001930 bool LocalChange = true;
1931 while (LocalChange) {
1932 LocalChange = false;
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001933
1934 // Delete functions that are trivially dead, ccc -> fastcc
1935 LocalChange |= OptimizeFunctions(M);
1936
1937 // Optimize global_ctors list.
1938 if (GlobalCtors)
1939 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1940
1941 // Optimize non-address-taken globals.
1942 LocalChange |= OptimizeGlobalVars(M);
Chris Lattner7a90b682004-10-07 04:16:33 +00001943 Changed |= LocalChange;
1944 }
Chris Lattnerb1ab4582005-09-26 01:43:45 +00001945
1946 // TODO: Move all global ctors functions to the end of the module for code
1947 // layout.
1948
Chris Lattner079236d2004-02-25 21:34:36 +00001949 return Changed;
1950}