1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms simple global variables that never have their address
11 // taken. If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
33 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
34 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
36 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
37 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
38 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
40 struct GlobalOpt : public ModulePass {
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<TargetData>();
45 bool runOnModule(Module &M);
48 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
51 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
54 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
56 /// GlobalStatus - As we analyze each global, keep track of some information
57 /// about it. If we find out that the address of the global is taken, none of
58 /// this info will be accurate.
60 /// isLoaded - True if the global is ever loaded. If the global isn't ever
61 /// loaded it can be deleted.
64 /// StoredType - Keep track of what stores to the global look like.
67 /// NotStored - There is no store to this global. It can thus be marked
71 /// isInitializerStored - This global is stored to, but the only thing
72 /// stored is the constant it was initialized with. This is only tracked
73 /// for scalar globals.
76 /// isStoredOnce - This global is stored to, but only its initializer and
77 /// one other value is ever stored to it. If this global isStoredOnce, we
78 /// track the value stored to it in StoredOnceValue below. This is only
79 /// tracked for scalar globals.
82 /// isStored - This global is stored to by multiple values or something else
83 /// that we cannot track.
87 /// StoredOnceValue - If only one value (besides the initializer constant) is
88 /// ever stored to this global, keep track of what value it is.
89 Value *StoredOnceValue;
91 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
92 /// the global exist. Such users include GEP instruction with variable
93 /// indexes, and non-gep/load/store users like constant expr casts.
94 bool isNotSuitableForSRA;
96 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
97 isNotSuitableForSRA(false) {}
102 /// ConstantIsDead - Return true if the specified constant is (transitively)
103 /// dead. The constant may be used by other constants (e.g. constant arrays and
104 /// constant exprs) as long as they are dead, but it cannot be used by anything
106 static bool ConstantIsDead(Constant *C) {
107 if (isa<GlobalValue>(C)) return false;
109 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
110 if (Constant *CU = dyn_cast<Constant>(*UI)) {
111 if (!ConstantIsDead(CU)) return false;
118 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
119 /// structure. If the global has its address taken, return true to indicate we
120 /// can't do anything with it.
122 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
123 std::set<PHINode*> &PHIUsers) {
124 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
125 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
126 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
127 if (CE->getOpcode() != Instruction::GetElementPtr)
128 GS.isNotSuitableForSRA = true;
129 else if (!GS.isNotSuitableForSRA) {
130 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
131 // don't like < 3 operand CE's, and we don't like non-constant integer
133 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
134 GS.isNotSuitableForSRA = true;
136 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
137 if (!isa<ConstantInt>(CE->getOperand(i))) {
138 GS.isNotSuitableForSRA = true;
144 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
145 if (isa<LoadInst>(I)) {
147 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
148 // Don't allow a store OF the address, only stores TO the address.
149 if (SI->getOperand(0) == V) return true;
151 // If this is a direct store to the global (i.e., the global is a scalar
152 // value, not an aggregate), keep more specific information about
154 if (GS.StoredType != GlobalStatus::isStored)
155 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
156 if (SI->getOperand(0) == GV->getInitializer()) {
157 if (GS.StoredType < GlobalStatus::isInitializerStored)
158 GS.StoredType = GlobalStatus::isInitializerStored;
159 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
160 GS.StoredType = GlobalStatus::isStoredOnce;
161 GS.StoredOnceValue = SI->getOperand(0);
162 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
163 GS.StoredOnceValue == SI->getOperand(0)) {
166 GS.StoredType = GlobalStatus::isStored;
169 GS.StoredType = GlobalStatus::isStored;
171 } else if (I->getOpcode() == Instruction::GetElementPtr) {
172 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
174 // If the first two indices are constants, this can be SRA'd.
175 if (isa<GlobalVariable>(I->getOperand(0))) {
176 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
177 !cast<Constant>(I->getOperand(1))->isNullValue() ||
178 !isa<ConstantInt>(I->getOperand(2)))
179 GS.isNotSuitableForSRA = true;
180 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
181 if (CE->getOpcode() != Instruction::GetElementPtr ||
182 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
183 !isa<Constant>(I->getOperand(0)) ||
184 !cast<Constant>(I->getOperand(0))->isNullValue())
185 GS.isNotSuitableForSRA = true;
187 GS.isNotSuitableForSRA = true;
189 } else if (I->getOpcode() == Instruction::Select) {
190 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
191 GS.isNotSuitableForSRA = true;
192 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
193 // PHI nodes we can check just like select or GEP instructions, but we
194 // have to be careful about infinite recursion.
195 if (PHIUsers.insert(PN).second) // Not already visited.
196 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
197 GS.isNotSuitableForSRA = true;
198 } else if (isa<SetCondInst>(I)) {
199 GS.isNotSuitableForSRA = true;
201 return true; // Any other non-load instruction might take address!
203 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
204 // We might have a dead and dangling constant hanging off of here.
205 if (!ConstantIsDead(C))
208 // Otherwise must be a global or some other user.
215 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
216 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
218 uint64_t IdxV = CI->getRawValue();
220 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
221 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
222 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
223 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
224 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
225 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
226 } else if (ConstantAggregateZero *CAZ =
227 dyn_cast<ConstantAggregateZero>(Agg)) {
228 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
229 if (IdxV < STy->getNumElements())
230 return Constant::getNullValue(STy->getElementType(IdxV));
231 } else if (const SequentialType *STy =
232 dyn_cast<SequentialType>(Agg->getType())) {
233 return Constant::getNullValue(STy->getElementType());
239 static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
240 if (GEP->getNumOperands() == 1 ||
241 !isa<Constant>(GEP->getOperand(1)) ||
242 !cast<Constant>(GEP->getOperand(1))->isNullValue())
245 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
246 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
248 Init = getAggregateConstantElement(Init, Idx);
249 if (Init == 0) return 0;
254 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
255 /// users of the global, cleaning up the obvious ones. This is largely just a
256 /// quick scan over the use list to clean up the easy and obvious cruft. This
257 /// returns true if it made a change.
258 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
259 bool Changed = false;
260 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
263 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
264 // Replace the load with the initializer.
265 LI->replaceAllUsesWith(Init);
266 LI->getParent()->getInstList().erase(LI);
268 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
269 // Store must be unreachable or storing Init into the global.
270 SI->getParent()->getInstList().erase(SI);
272 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
273 if (CE->getOpcode() == Instruction::GetElementPtr) {
274 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
275 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
276 if (CE->use_empty()) {
277 CE->destroyConstant();
281 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
282 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
283 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
285 // If this GEP has variable indexes, we should still be able to delete
286 // any stores through it.
287 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
289 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
290 SI->getParent()->getInstList().erase(SI);
295 if (GEP->use_empty()) {
296 GEP->getParent()->getInstList().erase(GEP);
299 } else if (Constant *C = dyn_cast<Constant>(U)) {
300 // If we have a chain of dead constantexprs or other things dangling from
301 // us, and if they are all dead, nuke them without remorse.
302 if (ConstantIsDead(C)) {
303 C->destroyConstant();
304 // This could have incalidated UI, start over from scratch.x
305 CleanupConstantGlobalUsers(V, Init);
313 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
314 /// variable. This opens the door for other optimizations by exposing the
315 /// behavior of the program in a more fine-grained way. We have determined that
316 /// this transformation is safe already. We return the first global variable we
317 /// insert so that the caller can reprocess it.
318 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
319 assert(GV->hasInternalLinkage() && !GV->isConstant());
320 Constant *Init = GV->getInitializer();
321 const Type *Ty = Init->getType();
323 std::vector<GlobalVariable*> NewGlobals;
324 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
326 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
327 NewGlobals.reserve(STy->getNumElements());
328 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
329 Constant *In = getAggregateConstantElement(Init,
330 ConstantUInt::get(Type::UIntTy, i));
331 assert(In && "Couldn't get element of initializer?");
332 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
333 GlobalVariable::InternalLinkage,
334 In, GV->getName()+"."+utostr(i));
335 Globals.insert(GV, NGV);
336 NewGlobals.push_back(NGV);
338 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
339 unsigned NumElements = 0;
340 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
341 NumElements = ATy->getNumElements();
342 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
343 NumElements = PTy->getNumElements();
345 assert(0 && "Unknown aggregate sequential type!");
347 if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
348 NewGlobals.reserve(NumElements);
349 for (unsigned i = 0, e = NumElements; i != e; ++i) {
350 Constant *In = getAggregateConstantElement(Init,
351 ConstantUInt::get(Type::UIntTy, i));
352 assert(In && "Couldn't get element of initializer?");
354 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
355 GlobalVariable::InternalLinkage,
356 In, GV->getName()+"."+utostr(i));
357 Globals.insert(GV, NGV);
358 NewGlobals.push_back(NGV);
362 if (NewGlobals.empty())
365 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
367 Constant *NullInt = Constant::getNullValue(Type::IntTy);
369 // Loop over all of the uses of the global, replacing the constantexpr geps,
370 // with smaller constantexpr geps or direct references.
371 while (!GV->use_empty()) {
372 User *GEP = GV->use_back();
373 assert(((isa<ConstantExpr>(GEP) &&
374 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
375 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
377 // Ignore the 1th operand, which has to be zero or else the program is quite
378 // broken (undefined). Get the 2nd operand, which is the structure or array
380 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
381 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
383 Value *NewPtr = NewGlobals[Val];
385 // Form a shorter GEP if needed.
386 if (GEP->getNumOperands() > 3)
387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
388 std::vector<Constant*> Idxs;
389 Idxs.push_back(NullInt);
390 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
391 Idxs.push_back(CE->getOperand(i));
392 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
394 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
395 std::vector<Value*> Idxs;
396 Idxs.push_back(NullInt);
397 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
398 Idxs.push_back(GEPI->getOperand(i));
399 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
400 GEPI->getName()+"."+utostr(Val), GEPI);
402 GEP->replaceAllUsesWith(NewPtr);
404 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
405 GEPI->getParent()->getInstList().erase(GEPI);
407 cast<ConstantExpr>(GEP)->destroyConstant();
410 // Delete the old global, now that it is dead.
414 // Loop over the new globals array deleting any globals that are obviously
415 // dead. This can arise due to scalarization of a structure or an array that
416 // has elements that are dead.
417 unsigned FirstGlobal = 0;
418 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
419 if (NewGlobals[i]->use_empty()) {
420 Globals.erase(NewGlobals[i]);
421 if (FirstGlobal == i) ++FirstGlobal;
424 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
427 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
428 /// value will trap if the value is dynamically null.
429 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
430 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
431 if (isa<LoadInst>(*UI)) {
433 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
434 if (SI->getOperand(0) == V) {
435 //std::cerr << "NONTRAPPING USE: " << **UI;
436 return false; // Storing the value.
438 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
439 if (CI->getOperand(0) != V) {
440 //std::cerr << "NONTRAPPING USE: " << **UI;
441 return false; // Not calling the ptr
443 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
444 if (II->getOperand(0) != V) {
445 //std::cerr << "NONTRAPPING USE: " << **UI;
446 return false; // Not calling the ptr
448 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
449 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
450 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
451 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
453 //std::cerr << "NONTRAPPING USE: " << **UI;
459 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
460 /// from GV will trap if the loaded value is null.
461 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
462 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
463 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
464 if (!AllUsesOfValueWillTrapIfNull(LI))
466 } else if (isa<StoreInst>(*UI)) {
467 // Ignore stores to the global.
469 // We don't know or understand this user, bail out.
470 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
477 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
478 bool Changed = false;
479 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
480 Instruction *I = cast<Instruction>(*UI++);
481 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
482 LI->setOperand(0, NewV);
484 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
485 if (SI->getOperand(1) == V) {
486 SI->setOperand(1, NewV);
489 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
490 if (I->getOperand(0) == V) {
491 // Calling through the pointer! Turn into a direct call, but be careful
492 // that the pointer is not also being passed as an argument.
493 I->setOperand(0, NewV);
495 bool PassedAsArg = false;
496 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
497 if (I->getOperand(i) == V) {
499 I->setOperand(i, NewV);
503 // Being passed as an argument also. Be careful to not invalidate UI!
507 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
508 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
509 ConstantExpr::getCast(NewV, CI->getType()));
510 if (CI->use_empty()) {
512 CI->getParent()->getInstList().erase(CI);
514 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
515 // Should handle GEP here.
516 std::vector<Constant*> Indices;
517 Indices.reserve(GEPI->getNumOperands()-1);
518 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
519 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
520 Indices.push_back(C);
523 if (Indices.size() == GEPI->getNumOperands()-1)
524 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
525 ConstantExpr::getGetElementPtr(NewV, Indices));
526 if (GEPI->use_empty()) {
528 GEPI->getParent()->getInstList().erase(GEPI);
537 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
538 /// value stored into it. If there are uses of the loaded value that would trap
539 /// if the loaded value is dynamically null, then we know that they cannot be
540 /// reachable with a null optimize away the load.
541 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
542 std::vector<LoadInst*> Loads;
543 bool Changed = false;
545 // Replace all uses of loads with uses of uses of the stored value.
546 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
548 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
550 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
552 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
556 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
560 // Delete all of the loads we can, keeping track of whether we nuked them all!
561 bool AllLoadsGone = true;
562 while (!Loads.empty()) {
563 LoadInst *L = Loads.back();
564 if (L->use_empty()) {
565 L->getParent()->getInstList().erase(L);
568 AllLoadsGone = false;
573 // If we nuked all of the loads, then none of the stores are needed either,
574 // nor is the global.
576 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
577 CleanupConstantGlobalUsers(GV, 0);
578 if (GV->use_empty()) {
579 GV->getParent()->getGlobalList().erase(GV);
587 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
588 /// instructions that are foldable.
589 static void ConstantPropUsersOf(Value *V) {
590 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
591 if (Instruction *I = dyn_cast<Instruction>(*UI++))
592 if (Constant *NewC = ConstantFoldInstruction(I)) {
593 I->replaceAllUsesWith(NewC);
595 // Back up UI to avoid invalidating it!
596 bool AtBegin = false;
597 if (UI == V->use_begin())
601 I->getParent()->getInstList().erase(I);
609 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
610 /// variable, and transforms the program as if it always contained the result of
611 /// the specified malloc. Because it is always the result of the specified
612 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
613 /// malloc into a global, and any laods of GV as uses of the new global.
614 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
616 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
617 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
619 if (NElements->getRawValue() != 1) {
620 // If we have an array allocation, transform it to a single element
621 // allocation to make the code below simpler.
622 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
623 NElements->getRawValue());
625 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
627 std::vector<Value*> Indices;
628 Indices.push_back(Constant::getNullValue(Type::IntTy));
629 Indices.push_back(Indices[0]);
630 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
631 NewMI->getName()+".el0", MI);
632 MI->replaceAllUsesWith(NewGEP);
633 MI->getParent()->getInstList().erase(MI);
637 // Create the new global variable.
638 Constant *Init = Constant::getNullValue(MI->getAllocatedType());
639 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
640 GlobalValue::InternalLinkage, Init,
641 GV->getName()+".body");
642 GV->getParent()->getGlobalList().insert(GV, NewGV);
644 // Anything that used the malloc now uses the global directly.
645 MI->replaceAllUsesWith(NewGV);
646 MI->getParent()->getInstList().erase(MI);
648 Constant *RepValue = NewGV;
649 if (NewGV->getType() != GV->getType()->getElementType())
650 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
652 // Loop over all uses of GV, processing them in turn.
653 while (!GV->use_empty())
654 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
655 LI->replaceAllUsesWith(RepValue);
656 LI->getParent()->getInstList().erase(LI);
658 StoreInst *SI = cast<StoreInst>(GV->use_back());
659 SI->getParent()->getInstList().erase(SI);
662 // Now the GV is dead, nuke it.
663 GV->getParent()->getGlobalList().erase(GV);
665 // To further other optimizations, loop over all users of NewGV and try to
666 // constant prop them. This will promote GEP instructions with constant
667 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
668 ConstantPropUsersOf(NewGV);
669 if (RepValue != NewGV)
670 ConstantPropUsersOf(RepValue);
675 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
676 // that only one value (besides its initializer) is ever stored to the global.
677 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
678 Module::giterator &GVI, TargetData &TD) {
679 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
680 StoredOnceVal = CI->getOperand(0);
681 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
682 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
683 bool IsJustACast = true;
684 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
685 if (!isa<Constant>(GEPI->getOperand(i)) ||
686 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
691 StoredOnceVal = GEPI->getOperand(0);
694 // If we are dealing with a pointer global that is initialized to null and
695 // only has one (non-null) value stored into it, then we can optimize any
696 // users of the loaded value (often calls and loads) that would trap if the
698 if (isa<PointerType>(GV->getInitializer()->getType()) &&
699 GV->getInitializer()->isNullValue()) {
700 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
701 if (GV->getInitializer()->getType() != SOVC->getType())
702 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
704 // Optimize away any trapping uses of the loaded value.
705 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
707 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
708 // If we have a global that is only initialized with a fixed size malloc,
709 // and if all users of the malloc trap, and if the malloc'd address is not
710 // put anywhere else, transform the program to use global memory instead
711 // of malloc'd memory. This eliminates dynamic allocation (good) and
712 // exposes the resultant global to further GlobalOpt (even better). Note
713 // that we restrict this transformation to only working on small
714 // allocations (2048 bytes currently), as we don't want to introduce a 16M
715 // global or something.
716 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
717 if (MI->getAllocatedType()->isSized() &&
718 NElements->getRawValue()*
719 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
720 AllUsesOfLoadedValueWillTrapIfNull(GV)) {
721 // FIXME: do more correctness checking to make sure the result of the
722 // malloc isn't squirrelled away somewhere.
723 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
732 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
733 /// it if possible. If we make a change, return true.
734 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
735 Module::giterator &GVI) {
736 std::set<PHINode*> PHIUsers;
739 GV->removeDeadConstantUsers();
741 if (GV->use_empty()) {
742 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
743 GV->getParent()->getGlobalList().erase(GV);
748 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
749 // If the global is never loaded (but may be stored to), it is dead.
752 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
754 // Delete any stores we can find to the global. We may not be able to
755 // make it completely dead though.
756 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
758 // If the global is dead now, delete it.
759 if (GV->use_empty()) {
760 GV->getParent()->getGlobalList().erase(GV);
766 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
767 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
768 GV->setConstant(true);
770 // Clean up any obviously simplifiable users now.
771 CleanupConstantGlobalUsers(GV, GV->getInitializer());
773 // If the global is dead now, just nuke it.
774 if (GV->use_empty()) {
775 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
776 "all users and delete global!\n");
777 GV->getParent()->getGlobalList().erase(GV);
783 } else if (!GS.isNotSuitableForSRA &&
784 !GV->getInitializer()->getType()->isFirstClassType()) {
785 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
786 GVI = FirstNewGV; // Don't skip the newly produced globals!
789 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
790 // Try to optimize globals based on the knowledge that only one value
791 // (besides its initializer) is ever stored to the global.
792 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
793 getAnalysis<TargetData>()))
801 bool GlobalOpt::runOnModule(Module &M) {
802 bool Changed = false;
804 // As a prepass, delete functions that are trivially dead.
805 bool LocalChange = true;
806 while (LocalChange) {
808 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
810 F->removeDeadConstantUsers();
811 if (F->use_empty() && (F->hasInternalLinkage() || F->hasWeakLinkage())) {
812 M.getFunctionList().erase(F);
817 Changed |= LocalChange;
821 while (LocalChange) {
823 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
824 GlobalVariable *GV = GVI++;
825 if (!GV->isConstant() && GV->hasInternalLinkage() &&
826 GV->hasInitializer())
827 LocalChange |= ProcessInternalGlobal(GV, GVI);
829 Changed |= LocalChange;