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/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
36 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
37 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
39 Statistic<> NumHeapSRA ("globalopt", "Number of heap objects SRA'd");
40 Statistic<> NumSubstitute("globalopt",
41 "Number of globals with initializers stored into them");
42 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
43 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
44 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
45 Statistic<> NumLocalized("globalopt", "Number of globals localized");
46 Statistic<> NumShrunkToBool("globalopt",
47 "Number of global vars shrunk to booleans");
48 Statistic<> NumFastCallFns("globalopt",
49 "Number of functions converted to fastcc");
50 Statistic<> NumCtorsEvaluated("globalopt","Number of static ctors evaluated");
52 struct GlobalOpt : public ModulePass {
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequired<TargetData>();
57 bool runOnModule(Module &M);
60 GlobalVariable *FindGlobalCtors(Module &M);
61 bool OptimizeFunctions(Module &M);
62 bool OptimizeGlobalVars(Module &M);
63 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
64 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
67 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
70 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
72 /// GlobalStatus - As we analyze each global, keep track of some information
73 /// about it. If we find out that the address of the global is taken, none of
74 /// this info will be accurate.
76 /// isLoaded - True if the global is ever loaded. If the global isn't ever
77 /// loaded it can be deleted.
80 /// StoredType - Keep track of what stores to the global look like.
83 /// NotStored - There is no store to this global. It can thus be marked
87 /// isInitializerStored - This global is stored to, but the only thing
88 /// stored is the constant it was initialized with. This is only tracked
89 /// for scalar globals.
92 /// isStoredOnce - This global is stored to, but only its initializer and
93 /// one other value is ever stored to it. If this global isStoredOnce, we
94 /// track the value stored to it in StoredOnceValue below. This is only
95 /// tracked for scalar globals.
98 /// isStored - This global is stored to by multiple values or something else
99 /// that we cannot track.
103 /// StoredOnceValue - If only one value (besides the initializer constant) is
104 /// ever stored to this global, keep track of what value it is.
105 Value *StoredOnceValue;
107 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
108 /// null/false. When the first accessing function is noticed, it is recorded.
109 /// When a second different accessing function is noticed,
110 /// HasMultipleAccessingFunctions is set to true.
111 Function *AccessingFunction;
112 bool HasMultipleAccessingFunctions;
114 /// HasNonInstructionUser - Set to true if this global has a user that is not
115 /// an instruction (e.g. a constant expr or GV initializer).
116 bool HasNonInstructionUser;
118 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
121 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
122 /// the global exist. Such users include GEP instruction with variable
123 /// indexes, and non-gep/load/store users like constant expr casts.
124 bool isNotSuitableForSRA;
126 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
127 AccessingFunction(0), HasMultipleAccessingFunctions(false),
128 HasNonInstructionUser(false), HasPHIUser(false),
129 isNotSuitableForSRA(false) {}
134 /// ConstantIsDead - Return true if the specified constant is (transitively)
135 /// dead. The constant may be used by other constants (e.g. constant arrays and
136 /// constant exprs) as long as they are dead, but it cannot be used by anything
138 static bool ConstantIsDead(Constant *C) {
139 if (isa<GlobalValue>(C)) return false;
141 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
142 if (Constant *CU = dyn_cast<Constant>(*UI)) {
143 if (!ConstantIsDead(CU)) return false;
150 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
151 /// structure. If the global has its address taken, return true to indicate we
152 /// can't do anything with it.
154 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
155 std::set<PHINode*> &PHIUsers) {
156 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
158 GS.HasNonInstructionUser = true;
160 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
161 if (CE->getOpcode() != Instruction::GetElementPtr)
162 GS.isNotSuitableForSRA = true;
163 else if (!GS.isNotSuitableForSRA) {
164 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
165 // don't like < 3 operand CE's, and we don't like non-constant integer
167 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
168 GS.isNotSuitableForSRA = true;
170 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
171 if (!isa<ConstantInt>(CE->getOperand(i))) {
172 GS.isNotSuitableForSRA = true;
178 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
179 if (!GS.HasMultipleAccessingFunctions) {
180 Function *F = I->getParent()->getParent();
181 if (GS.AccessingFunction == 0)
182 GS.AccessingFunction = F;
183 else if (GS.AccessingFunction != F)
184 GS.HasMultipleAccessingFunctions = true;
186 if (isa<LoadInst>(I)) {
188 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
189 // Don't allow a store OF the address, only stores TO the address.
190 if (SI->getOperand(0) == V) return true;
192 // If this is a direct store to the global (i.e., the global is a scalar
193 // value, not an aggregate), keep more specific information about
195 if (GS.StoredType != GlobalStatus::isStored)
196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
197 Value *StoredVal = SI->getOperand(0);
198 if (StoredVal == GV->getInitializer()) {
199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (isa<LoadInst>(StoredVal) &&
202 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
204 if (GS.StoredType < GlobalStatus::isInitializerStored)
205 GS.StoredType = GlobalStatus::isInitializerStored;
206 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
207 GS.StoredType = GlobalStatus::isStoredOnce;
208 GS.StoredOnceValue = StoredVal;
209 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
210 GS.StoredOnceValue == StoredVal) {
213 GS.StoredType = GlobalStatus::isStored;
216 GS.StoredType = GlobalStatus::isStored;
218 } else if (isa<GetElementPtrInst>(I)) {
219 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
221 // If the first two indices are constants, this can be SRA'd.
222 if (isa<GlobalVariable>(I->getOperand(0))) {
223 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
224 !cast<Constant>(I->getOperand(1))->isNullValue() ||
225 !isa<ConstantInt>(I->getOperand(2)))
226 GS.isNotSuitableForSRA = true;
227 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
228 if (CE->getOpcode() != Instruction::GetElementPtr ||
229 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
230 !isa<Constant>(I->getOperand(0)) ||
231 !cast<Constant>(I->getOperand(0))->isNullValue())
232 GS.isNotSuitableForSRA = true;
234 GS.isNotSuitableForSRA = true;
236 } else if (isa<SelectInst>(I)) {
237 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
238 GS.isNotSuitableForSRA = true;
239 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
240 // PHI nodes we can check just like select or GEP instructions, but we
241 // have to be careful about infinite recursion.
242 if (PHIUsers.insert(PN).second) // Not already visited.
243 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
244 GS.isNotSuitableForSRA = true;
245 GS.HasPHIUser = true;
246 } else if (isa<SetCondInst>(I)) {
247 GS.isNotSuitableForSRA = true;
248 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
249 if (I->getOperand(1) == V)
250 GS.StoredType = GlobalStatus::isStored;
251 if (I->getOperand(2) == V)
253 GS.isNotSuitableForSRA = true;
254 } else if (isa<MemSetInst>(I)) {
255 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
256 GS.StoredType = GlobalStatus::isStored;
257 GS.isNotSuitableForSRA = true;
259 return true; // Any other non-load instruction might take address!
261 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
262 GS.HasNonInstructionUser = true;
263 // We might have a dead and dangling constant hanging off of here.
264 if (!ConstantIsDead(C))
267 GS.HasNonInstructionUser = true;
268 // Otherwise must be some other user.
275 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
276 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
278 unsigned IdxV = CI->getZExtValue();
280 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
281 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
282 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
283 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
284 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
285 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
286 } else if (isa<ConstantAggregateZero>(Agg)) {
287 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
288 if (IdxV < STy->getNumElements())
289 return Constant::getNullValue(STy->getElementType(IdxV));
290 } else if (const SequentialType *STy =
291 dyn_cast<SequentialType>(Agg->getType())) {
292 return Constant::getNullValue(STy->getElementType());
294 } else if (isa<UndefValue>(Agg)) {
295 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
296 if (IdxV < STy->getNumElements())
297 return UndefValue::get(STy->getElementType(IdxV));
298 } else if (const SequentialType *STy =
299 dyn_cast<SequentialType>(Agg->getType())) {
300 return UndefValue::get(STy->getElementType());
307 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
308 /// users of the global, cleaning up the obvious ones. This is largely just a
309 /// quick scan over the use list to clean up the easy and obvious cruft. This
310 /// returns true if it made a change.
311 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
312 bool Changed = false;
313 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
316 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
318 // Replace the load with the initializer.
319 LI->replaceAllUsesWith(Init);
320 LI->eraseFromParent();
323 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
324 // Store must be unreachable or storing Init into the global.
325 SI->eraseFromParent();
327 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
328 if (CE->getOpcode() == Instruction::GetElementPtr) {
329 Constant *SubInit = 0;
331 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
332 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
333 } else if (CE->getOpcode() == Instruction::Cast &&
334 isa<PointerType>(CE->getType())) {
335 // Pointer cast, delete any stores and memsets to the global.
336 Changed |= CleanupConstantGlobalUsers(CE, 0);
339 if (CE->use_empty()) {
340 CE->destroyConstant();
343 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
344 Constant *SubInit = 0;
346 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
347 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
348 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
349 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
351 if (GEP->use_empty()) {
352 GEP->eraseFromParent();
355 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
356 if (MI->getRawDest() == V) {
357 MI->eraseFromParent();
361 } else if (Constant *C = dyn_cast<Constant>(U)) {
362 // If we have a chain of dead constantexprs or other things dangling from
363 // us, and if they are all dead, nuke them without remorse.
364 if (ConstantIsDead(C)) {
365 C->destroyConstant();
366 // This could have invalidated UI, start over from scratch.
367 CleanupConstantGlobalUsers(V, Init);
375 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
376 /// variable. This opens the door for other optimizations by exposing the
377 /// behavior of the program in a more fine-grained way. We have determined that
378 /// this transformation is safe already. We return the first global variable we
379 /// insert so that the caller can reprocess it.
380 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
381 assert(GV->hasInternalLinkage() && !GV->isConstant());
382 Constant *Init = GV->getInitializer();
383 const Type *Ty = Init->getType();
385 std::vector<GlobalVariable*> NewGlobals;
386 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
388 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
389 NewGlobals.reserve(STy->getNumElements());
390 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
391 Constant *In = getAggregateConstantElement(Init,
392 ConstantInt::get(Type::UIntTy, i));
393 assert(In && "Couldn't get element of initializer?");
394 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
395 GlobalVariable::InternalLinkage,
396 In, GV->getName()+"."+utostr(i));
397 Globals.insert(GV, NGV);
398 NewGlobals.push_back(NGV);
400 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
401 unsigned NumElements = 0;
402 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
403 NumElements = ATy->getNumElements();
404 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
405 NumElements = PTy->getNumElements();
407 assert(0 && "Unknown aggregate sequential type!");
409 if (NumElements > 16 && GV->hasNUsesOrMore(16))
410 return 0; // It's not worth it.
411 NewGlobals.reserve(NumElements);
412 for (unsigned i = 0, e = NumElements; i != e; ++i) {
413 Constant *In = getAggregateConstantElement(Init,
414 ConstantInt::get(Type::UIntTy, i));
415 assert(In && "Couldn't get element of initializer?");
417 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
418 GlobalVariable::InternalLinkage,
419 In, GV->getName()+"."+utostr(i));
420 Globals.insert(GV, NGV);
421 NewGlobals.push_back(NGV);
425 if (NewGlobals.empty())
428 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
430 Constant *NullInt = Constant::getNullValue(Type::IntTy);
432 // Loop over all of the uses of the global, replacing the constantexpr geps,
433 // with smaller constantexpr geps or direct references.
434 while (!GV->use_empty()) {
435 User *GEP = GV->use_back();
436 assert(((isa<ConstantExpr>(GEP) &&
437 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
438 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
440 // Ignore the 1th operand, which has to be zero or else the program is quite
441 // broken (undefined). Get the 2nd operand, which is the structure or array
443 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
444 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
446 Value *NewPtr = NewGlobals[Val];
448 // Form a shorter GEP if needed.
449 if (GEP->getNumOperands() > 3)
450 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
451 std::vector<Constant*> Idxs;
452 Idxs.push_back(NullInt);
453 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
454 Idxs.push_back(CE->getOperand(i));
455 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
457 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
458 std::vector<Value*> Idxs;
459 Idxs.push_back(NullInt);
460 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
461 Idxs.push_back(GEPI->getOperand(i));
462 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
463 GEPI->getName()+"."+utostr(Val), GEPI);
465 GEP->replaceAllUsesWith(NewPtr);
467 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
468 GEPI->eraseFromParent();
470 cast<ConstantExpr>(GEP)->destroyConstant();
473 // Delete the old global, now that it is dead.
477 // Loop over the new globals array deleting any globals that are obviously
478 // dead. This can arise due to scalarization of a structure or an array that
479 // has elements that are dead.
480 unsigned FirstGlobal = 0;
481 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
482 if (NewGlobals[i]->use_empty()) {
483 Globals.erase(NewGlobals[i]);
484 if (FirstGlobal == i) ++FirstGlobal;
487 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
490 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
491 /// value will trap if the value is dynamically null.
492 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
493 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
494 if (isa<LoadInst>(*UI)) {
496 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
497 if (SI->getOperand(0) == V) {
498 //std::cerr << "NONTRAPPING USE: " << **UI;
499 return false; // Storing the value.
501 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
502 if (CI->getOperand(0) != V) {
503 //std::cerr << "NONTRAPPING USE: " << **UI;
504 return false; // Not calling the ptr
506 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
507 if (II->getOperand(0) != V) {
508 //std::cerr << "NONTRAPPING USE: " << **UI;
509 return false; // Not calling the ptr
511 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
512 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
513 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
514 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
515 } else if (isa<SetCondInst>(*UI) &&
516 isa<ConstantPointerNull>(UI->getOperand(1))) {
517 // Ignore setcc X, null
519 //std::cerr << "NONTRAPPING USE: " << **UI;
525 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
526 /// from GV will trap if the loaded value is null. Note that this also permits
527 /// comparisons of the loaded value against null, as a special case.
528 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
529 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
530 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
531 if (!AllUsesOfValueWillTrapIfNull(LI))
533 } else if (isa<StoreInst>(*UI)) {
534 // Ignore stores to the global.
536 // We don't know or understand this user, bail out.
537 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
544 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
545 bool Changed = false;
546 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
547 Instruction *I = cast<Instruction>(*UI++);
548 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
549 LI->setOperand(0, NewV);
551 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
552 if (SI->getOperand(1) == V) {
553 SI->setOperand(1, NewV);
556 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
557 if (I->getOperand(0) == V) {
558 // Calling through the pointer! Turn into a direct call, but be careful
559 // that the pointer is not also being passed as an argument.
560 I->setOperand(0, NewV);
562 bool PassedAsArg = false;
563 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
564 if (I->getOperand(i) == V) {
566 I->setOperand(i, NewV);
570 // Being passed as an argument also. Be careful to not invalidate UI!
574 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
575 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
576 ConstantExpr::getCast(NewV, CI->getType()));
577 if (CI->use_empty()) {
579 CI->eraseFromParent();
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);
590 if (Indices.size() == GEPI->getNumOperands()-1)
591 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
592 ConstantExpr::getGetElementPtr(NewV, Indices));
593 if (GEPI->use_empty()) {
595 GEPI->eraseFromParent();
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.
608 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
609 std::vector<LoadInst*> Loads;
610 bool Changed = false;
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();
615 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
617 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
619 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
623 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
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()) {
632 L->eraseFromParent();
635 AllLoadsGone = false;
640 // If we nuked all of the loads, then none of the stores are needed either,
641 // nor is the global.
643 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
644 CleanupConstantGlobalUsers(GV, 0);
645 if (GV->use_empty()) {
646 GV->eraseFromParent();
654 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
655 /// instructions that are foldable.
656 static 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);
662 // Advance UI to the next non-I use to avoid invalidating it!
663 // Instructions could multiply use V.
664 while (UI != E && *UI == I)
666 I->eraseFromParent();
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
674 /// malloc into a global, and any laods of GV as uses of the new global.
675 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
677 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
678 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
680 if (NElements->getZExtValue() != 1) {
681 // 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(),
684 NElements->getZExtValue());
686 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
687 MI->getAlignment(), MI->getName(), MI);
688 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);
694 MI->eraseFromParent();
698 // 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());
701 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
702 GlobalValue::InternalLinkage, Init,
703 GV->getName()+".body");
704 GV->getParent()->getGlobalList().insert(GV, NewGV);
706 // Anything that used the malloc now uses the global directly.
707 MI->replaceAllUsesWith(NewGV);
709 Constant *RepValue = NewGV;
710 if (NewGV->getType() != GV->getType()->getElementType())
711 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
713 // If there is a comparison against null, we will insert a global bool to
714 // keep track of whether the global was initialized yet or not.
715 GlobalVariable *InitBool =
716 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
717 ConstantBool::getFalse(), GV->getName()+".init");
718 bool InitBoolUsed = false;
720 // Loop over all uses of GV, processing them in turn.
721 std::vector<StoreInst*> Stores;
722 while (!GV->use_empty())
723 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
724 while (!LI->use_empty()) {
725 Use &LoadUse = LI->use_begin().getUse();
726 if (!isa<SetCondInst>(LoadUse.getUser()))
729 // Replace the setcc X, 0 with a use of the bool value.
730 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
731 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
733 switch (SCI->getOpcode()) {
734 default: assert(0 && "Unknown opcode!");
735 case Instruction::SetLT:
736 LV = ConstantBool::getFalse(); // X < null -> always false
738 case Instruction::SetEQ:
739 case Instruction::SetLE:
740 LV = BinaryOperator::createNot(LV, "notinit", SCI);
742 case Instruction::SetNE:
743 case Instruction::SetGE:
744 case Instruction::SetGT:
747 SCI->replaceAllUsesWith(LV);
748 SCI->eraseFromParent();
751 LI->eraseFromParent();
753 StoreInst *SI = cast<StoreInst>(GV->use_back());
754 // The global is initialized when the store to it occurs.
755 new StoreInst(ConstantBool::getTrue(), InitBool, SI);
756 SI->eraseFromParent();
759 // If the initialization boolean was used, insert it, otherwise delete it.
761 while (!InitBool->use_empty()) // Delete initializations
762 cast<Instruction>(InitBool->use_back())->eraseFromParent();
765 GV->getParent()->getGlobalList().insert(GV, InitBool);
768 // Now the GV is dead, nuke it and the malloc.
769 GV->eraseFromParent();
770 MI->eraseFromParent();
772 // To further other optimizations, loop over all users of NewGV and try to
773 // constant prop them. This will promote GEP instructions with constant
774 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
775 ConstantPropUsersOf(NewGV);
776 if (RepValue != NewGV)
777 ConstantPropUsersOf(RepValue);
782 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
783 /// to make sure that there are no complex uses of V. We permit simple things
784 /// like dereferencing the pointer, but not storing through the address, unless
785 /// it is to the specified global.
786 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
787 GlobalVariable *GV) {
788 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
789 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
791 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
792 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
793 return false; // Storing the pointer itself... bad.
794 // Otherwise, storing through it, or storing into GV... fine.
795 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
796 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
804 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
805 /// somewhere. Transform all uses of the allocation into loads from the
806 /// global and uses of the resultant pointer. Further, delete the store into
807 /// GV. This assumes that these value pass the
808 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
809 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
810 GlobalVariable *GV) {
811 while (!Alloc->use_empty()) {
812 Instruction *U = Alloc->use_back();
813 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
814 // If this is the store of the allocation into the global, remove it.
815 if (SI->getOperand(1) == GV) {
816 SI->eraseFromParent();
821 // Insert a load from the global, and use it instead of the malloc.
822 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
823 U->replaceUsesOfWith(Alloc, NL);
827 /// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
828 /// GV are simple enough to perform HeapSRA, return true.
829 static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
830 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
832 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
833 // We permit two users of the load: setcc comparing against the null
834 // pointer, and a getelementptr of a specific form.
835 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
837 // Comparison against null is ok.
838 if (SetCondInst *SCI = dyn_cast<SetCondInst>(*UI)) {
839 if (!isa<ConstantPointerNull>(SCI->getOperand(1)))
844 // getelementptr is also ok, but only a simple form.
845 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
846 if (!GEPI) return false;
848 // Must index into the array and into the struct.
849 if (GEPI->getNumOperands() < 3)
852 // Otherwise the GEP is ok.
859 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
860 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
861 /// use FieldGlobals instead. All uses of loaded values satisfy
862 /// GlobalLoadUsesSimpleEnoughForHeapSRA.
863 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
864 const std::vector<GlobalVariable*> &FieldGlobals) {
865 std::vector<Value *> InsertedLoadsForPtr;
866 //InsertedLoadsForPtr.resize(FieldGlobals.size());
867 while (!Ptr->use_empty()) {
868 Instruction *User = Ptr->use_back();
870 // If this is a comparison against null, handle it.
871 if (SetCondInst *SCI = dyn_cast<SetCondInst>(User)) {
872 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
873 // If we have a setcc of the loaded pointer, we can use a setcc of any
876 if (InsertedLoadsForPtr.empty()) {
877 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
878 InsertedLoadsForPtr.push_back(Ptr);
880 NPtr = InsertedLoadsForPtr.back();
883 Value *New = new SetCondInst(SCI->getOpcode(), NPtr,
884 Constant::getNullValue(NPtr->getType()),
885 SCI->getName(), SCI);
886 SCI->replaceAllUsesWith(New);
887 SCI->eraseFromParent();
891 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
892 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
893 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
894 && GEPI->getOperand(2)->getType()->isUnsigned()
895 && "Unexpected GEPI!");
897 // Load the pointer for this field.
898 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
899 if (InsertedLoadsForPtr.size() <= FieldNo)
900 InsertedLoadsForPtr.resize(FieldNo+1);
901 if (InsertedLoadsForPtr[FieldNo] == 0)
902 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
903 Ptr->getName()+".f" +
904 utostr(FieldNo), Ptr);
905 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
907 // Create the new GEP idx vector.
908 std::vector<Value*> GEPIdx;
909 GEPIdx.push_back(GEPI->getOperand(1));
910 GEPIdx.insert(GEPIdx.end(), GEPI->op_begin()+3, GEPI->op_end());
912 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx, GEPI->getName(), GEPI);
913 GEPI->replaceAllUsesWith(NGEPI);
914 GEPI->eraseFromParent();
918 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
919 /// it up into multiple allocations of arrays of the fields.
920 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
921 DEBUG(std::cerr << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI);
922 const StructType *STy = cast<StructType>(MI->getAllocatedType());
924 // There is guaranteed to be at least one use of the malloc (storing
925 // it into GV). If there are other uses, change them to be uses of
926 // the global to simplify later code. This also deletes the store
928 ReplaceUsesOfMallocWithGlobal(MI, GV);
930 // Okay, at this point, there are no users of the malloc. Insert N
931 // new mallocs at the same place as MI, and N globals.
932 std::vector<GlobalVariable*> FieldGlobals;
933 std::vector<MallocInst*> FieldMallocs;
935 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
936 const Type *FieldTy = STy->getElementType(FieldNo);
937 const Type *PFieldTy = PointerType::get(FieldTy);
939 GlobalVariable *NGV =
940 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
941 Constant::getNullValue(PFieldTy),
942 GV->getName() + ".f" + utostr(FieldNo), GV);
943 FieldGlobals.push_back(NGV);
945 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
946 MI->getName() + ".f" + utostr(FieldNo),MI);
947 FieldMallocs.push_back(NMI);
948 new StoreInst(NMI, NGV, MI);
951 // The tricky aspect of this transformation is handling the case when malloc
952 // fails. In the original code, malloc failing would set the result pointer
953 // of malloc to null. In this case, some mallocs could succeed and others
954 // could fail. As such, we emit code that looks like this:
955 // F0 = malloc(field0)
956 // F1 = malloc(field1)
957 // F2 = malloc(field2)
958 // if (F0 == 0 || F1 == 0 || F2 == 0) {
959 // if (F0) { free(F0); F0 = 0; }
960 // if (F1) { free(F1); F1 = 0; }
961 // if (F2) { free(F2); F2 = 0; }
963 Value *RunningOr = 0;
964 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
965 Value *Cond = new SetCondInst(Instruction::SetEQ, FieldMallocs[i],
966 Constant::getNullValue(FieldMallocs[i]->getType()),
969 RunningOr = Cond; // First seteq
971 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
974 // Split the basic block at the old malloc.
975 BasicBlock *OrigBB = MI->getParent();
976 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
978 // Create the block to check the first condition. Put all these blocks at the
979 // end of the function as they are unlikely to be executed.
980 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
981 OrigBB->getParent());
983 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
984 // branch on RunningOr.
985 OrigBB->getTerminator()->eraseFromParent();
986 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
988 // Within the NullPtrBlock, we need to emit a comparison and branch for each
989 // pointer, because some may be null while others are not.
990 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
991 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
992 Value *Cmp = new SetCondInst(Instruction::SetNE, GVVal,
993 Constant::getNullValue(GVVal->getType()),
994 "tmp", NullPtrBlock);
995 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
996 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
997 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
999 // Fill in FreeBlock.
1000 new FreeInst(GVVal, FreeBlock);
1001 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1003 new BranchInst(NextBlock, FreeBlock);
1005 NullPtrBlock = NextBlock;
1008 new BranchInst(ContBB, NullPtrBlock);
1011 // MI is no longer needed, remove it.
1012 MI->eraseFromParent();
1015 // Okay, the malloc site is completely handled. All of the uses of GV are now
1016 // loads, and all uses of those loads are simple. Rewrite them to use loads
1017 // of the per-field globals instead.
1018 while (!GV->use_empty()) {
1019 LoadInst *LI = cast<LoadInst>(GV->use_back());
1020 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1021 LI->eraseFromParent();
1024 // The old global is now dead, remove it.
1025 GV->eraseFromParent();
1028 return FieldGlobals[0];
1032 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1033 // that only one value (besides its initializer) is ever stored to the global.
1034 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1035 Module::global_iterator &GVI,
1037 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1038 StoredOnceVal = CI->getOperand(0);
1039 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
1040 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
1041 bool IsJustACast = true;
1042 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1043 if (!isa<Constant>(GEPI->getOperand(i)) ||
1044 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1045 IsJustACast = false;
1049 StoredOnceVal = GEPI->getOperand(0);
1052 // If we are dealing with a pointer global that is initialized to null and
1053 // only has one (non-null) value stored into it, then we can optimize any
1054 // users of the loaded value (often calls and loads) that would trap if the
1056 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1057 GV->getInitializer()->isNullValue()) {
1058 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1059 if (GV->getInitializer()->getType() != SOVC->getType())
1060 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
1062 // Optimize away any trapping uses of the loaded value.
1063 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1065 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1066 // If this is a malloc of an abstract type, don't touch it.
1067 if (!MI->getAllocatedType()->isSized())
1070 // We can't optimize this global unless all uses of it are *known* to be
1071 // of the malloc value, not of the null initializer value (consider a use
1072 // that compares the global's value against zero to see if the malloc has
1073 // been reached). To do this, we check to see if all uses of the global
1074 // would trap if the global were null: this proves that they must all
1075 // happen after the malloc.
1076 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1079 // We can't optimize this if the malloc itself is used in a complex way,
1080 // for example, being stored into multiple globals. This allows the
1081 // malloc to be stored into the specified global, loaded setcc'd, and
1082 // GEP'd. These are all things we could transform to using the global
1084 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1088 // If we have a global that is only initialized with a fixed size malloc,
1089 // transform the program to use global memory instead of malloc'd memory.
1090 // This eliminates dynamic allocation, avoids an indirection accessing the
1091 // data, and exposes the resultant global to further GlobalOpt.
1092 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1093 // Restrict this transformation to only working on small allocations
1094 // (2048 bytes currently), as we don't want to introduce a 16M global or
1096 if (NElements->getZExtValue()*
1097 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
1098 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1103 // If the allocation is an array of structures, consider transforming this
1104 // into multiple malloc'd arrays, one for each field. This is basically
1105 // SRoA for malloc'd memory.
1106 if (const StructType *AllocTy =
1107 dyn_cast<StructType>(MI->getAllocatedType())) {
1108 // This the structure has an unreasonable number of fields, leave it
1110 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1111 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1112 GVI = PerformHeapAllocSRoA(GV, MI);
1122 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
1123 /// values ever stored into GV are its initializer and OtherVal.
1124 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1125 // Create the new global, initializing it to false.
1126 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
1127 GlobalValue::InternalLinkage, ConstantBool::getFalse(),
1128 GV->getName()+".b");
1129 GV->getParent()->getGlobalList().insert(GV, NewGV);
1131 Constant *InitVal = GV->getInitializer();
1132 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
1134 // If initialized to zero and storing one into the global, we can use a cast
1135 // instead of a select to synthesize the desired value.
1136 bool IsOneZero = false;
1137 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1138 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
1140 while (!GV->use_empty()) {
1141 Instruction *UI = cast<Instruction>(GV->use_back());
1142 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1143 // Change the store into a boolean store.
1144 bool StoringOther = SI->getOperand(0) == OtherVal;
1145 // Only do this if we weren't storing a loaded value.
1147 if (StoringOther || SI->getOperand(0) == InitVal)
1148 StoreVal = ConstantBool::get(StoringOther);
1150 // Otherwise, we are storing a previously loaded copy. To do this,
1151 // change the copy from copying the original value to just copying the
1153 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1155 // If we're already replaced the input, StoredVal will be a cast or
1156 // select instruction. If not, it will be a load of the original
1158 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1159 assert(LI->getOperand(0) == GV && "Not a copy!");
1160 // Insert a new load, to preserve the saved value.
1161 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1163 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1164 "This is not a form that we understand!");
1165 StoreVal = StoredVal->getOperand(0);
1166 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1169 new StoreInst(StoreVal, NewGV, SI);
1170 } else if (!UI->use_empty()) {
1171 // Change the load into a load of bool then a select.
1172 LoadInst *LI = cast<LoadInst>(UI);
1174 std::string Name = LI->getName(); LI->setName("");
1175 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
1178 NSI = new CastInst(NLI, LI->getType(), Name, LI);
1180 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
1181 LI->replaceAllUsesWith(NSI);
1183 UI->eraseFromParent();
1186 GV->eraseFromParent();
1190 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1191 /// it if possible. If we make a change, return true.
1192 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1193 Module::global_iterator &GVI) {
1194 std::set<PHINode*> PHIUsers;
1196 GV->removeDeadConstantUsers();
1198 if (GV->use_empty()) {
1199 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
1200 GV->eraseFromParent();
1205 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1207 std::cerr << "Global: " << *GV;
1208 std::cerr << " isLoaded = " << GS.isLoaded << "\n";
1209 std::cerr << " StoredType = ";
1210 switch (GS.StoredType) {
1211 case GlobalStatus::NotStored: std::cerr << "NEVER STORED\n"; break;
1212 case GlobalStatus::isInitializerStored: std::cerr << "INIT STORED\n"; break;
1213 case GlobalStatus::isStoredOnce: std::cerr << "STORED ONCE\n"; break;
1214 case GlobalStatus::isStored: std::cerr << "stored\n"; break;
1216 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1217 std::cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1218 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1219 std::cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1221 std::cerr << " HasMultipleAccessingFunctions = "
1222 << GS.HasMultipleAccessingFunctions << "\n";
1223 std::cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1224 std::cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1228 // If this is a first class global and has only one accessing function
1229 // and this function is main (which we know is not recursive we can make
1230 // this global a local variable) we replace the global with a local alloca
1231 // in this function.
1233 // NOTE: It doesn't make sense to promote non first class types since we
1234 // are just replacing static memory to stack memory.
1235 if (!GS.HasMultipleAccessingFunctions &&
1236 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1237 GV->getType()->getElementType()->isFirstClassType() &&
1238 GS.AccessingFunction->getName() == "main" &&
1239 GS.AccessingFunction->hasExternalLinkage()) {
1240 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
1241 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1242 const Type* ElemTy = GV->getType()->getElementType();
1243 // FIXME: Pass Global's alignment when globals have alignment
1244 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1245 if (!isa<UndefValue>(GV->getInitializer()))
1246 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1248 GV->replaceAllUsesWith(Alloca);
1249 GV->eraseFromParent();
1254 // If the global is never loaded (but may be stored to), it is dead.
1257 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
1259 // Delete any stores we can find to the global. We may not be able to
1260 // make it completely dead though.
1261 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1263 // If the global is dead now, delete it.
1264 if (GV->use_empty()) {
1265 GV->eraseFromParent();
1271 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1272 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
1273 GV->setConstant(true);
1275 // Clean up any obviously simplifiable users now.
1276 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1278 // If the global is dead now, just nuke it.
1279 if (GV->use_empty()) {
1280 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
1281 "all users and delete global!\n");
1282 GV->eraseFromParent();
1288 } else if (!GS.isNotSuitableForSRA &&
1289 !GV->getInitializer()->getType()->isFirstClassType()) {
1290 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1291 GVI = FirstNewGV; // Don't skip the newly produced globals!
1294 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1295 // If the initial value for the global was an undef value, and if only
1296 // one other value was stored into it, we can just change the
1297 // initializer to be an undef value, then delete all stores to the
1298 // global. This allows us to mark it constant.
1299 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1300 if (isa<UndefValue>(GV->getInitializer())) {
1301 // Change the initial value here.
1302 GV->setInitializer(SOVConstant);
1304 // Clean up any obviously simplifiable users now.
1305 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1307 if (GV->use_empty()) {
1308 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1309 "simplify all users and delete global!\n");
1310 GV->eraseFromParent();
1319 // Try to optimize globals based on the knowledge that only one value
1320 // (besides its initializer) is ever stored to the global.
1321 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1322 getAnalysis<TargetData>()))
1325 // Otherwise, if the global was not a boolean, we can shrink it to be a
1327 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1328 if (GV->getType()->getElementType() != Type::BoolTy &&
1329 !GV->getType()->getElementType()->isFloatingPoint() &&
1331 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1332 ShrinkGlobalToBoolean(GV, SOVConstant);
1341 /// OnlyCalledDirectly - Return true if the specified function is only called
1342 /// directly. In other words, its address is never taken.
1343 static bool OnlyCalledDirectly(Function *F) {
1344 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1345 Instruction *User = dyn_cast<Instruction>(*UI);
1346 if (!User) return false;
1347 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1349 // See if the function address is passed as an argument.
1350 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1351 if (User->getOperand(i) == F) return false;
1356 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1357 /// function, changing them to FastCC.
1358 static void ChangeCalleesToFastCall(Function *F) {
1359 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1360 Instruction *User = cast<Instruction>(*UI);
1361 if (CallInst *CI = dyn_cast<CallInst>(User))
1362 CI->setCallingConv(CallingConv::Fast);
1364 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1368 bool GlobalOpt::OptimizeFunctions(Module &M) {
1369 bool Changed = false;
1370 // Optimize functions.
1371 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1373 F->removeDeadConstantUsers();
1374 if (F->use_empty() && (F->hasInternalLinkage() ||
1375 F->hasLinkOnceLinkage())) {
1376 M.getFunctionList().erase(F);
1379 } else if (F->hasInternalLinkage() &&
1380 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1381 OnlyCalledDirectly(F)) {
1382 // If this function has C calling conventions, is not a varargs
1383 // function, and is only called directly, promote it to use the Fast
1384 // calling convention.
1385 F->setCallingConv(CallingConv::Fast);
1386 ChangeCalleesToFastCall(F);
1394 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1395 bool Changed = false;
1396 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1398 GlobalVariable *GV = GVI++;
1399 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1400 GV->hasInitializer())
1401 Changed |= ProcessInternalGlobal(GV, GVI);
1406 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1407 /// initializers have an init priority of 65535.
1408 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1409 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1411 if (I->getName() == "llvm.global_ctors") {
1412 // Found it, verify it's an array of { int, void()* }.
1413 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1415 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1416 if (!STy || STy->getNumElements() != 2 ||
1417 STy->getElementType(0) != Type::IntTy) return 0;
1418 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1419 if (!PFTy) return 0;
1420 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1421 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1422 FTy->getNumParams() != 0)
1425 // Verify that the initializer is simple enough for us to handle.
1426 if (!I->hasInitializer()) return 0;
1427 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1429 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1430 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1431 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1434 // Must have a function or null ptr.
1435 if (!isa<Function>(CS->getOperand(1)))
1438 // Init priority must be standard.
1439 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1440 if (!CI || CI->getZExtValue() != 65535)
1451 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1452 /// return a list of the functions and null terminator as a vector.
1453 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1454 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1455 std::vector<Function*> Result;
1456 Result.reserve(CA->getNumOperands());
1457 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1458 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1459 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1464 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1465 /// specified array, returning the new global to use.
1466 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1467 const std::vector<Function*> &Ctors) {
1468 // If we made a change, reassemble the initializer list.
1469 std::vector<Constant*> CSVals;
1470 CSVals.push_back(ConstantInt::get(Type::IntTy, 65535));
1471 CSVals.push_back(0);
1473 // Create the new init list.
1474 std::vector<Constant*> CAList;
1475 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1477 CSVals[1] = Ctors[i];
1479 const Type *FTy = FunctionType::get(Type::VoidTy,
1480 std::vector<const Type*>(), false);
1481 const PointerType *PFTy = PointerType::get(FTy);
1482 CSVals[1] = Constant::getNullValue(PFTy);
1483 CSVals[0] = ConstantInt::get(Type::IntTy, 2147483647);
1485 CAList.push_back(ConstantStruct::get(CSVals));
1488 // Create the array initializer.
1489 const Type *StructTy =
1490 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1491 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1494 // If we didn't change the number of elements, don't create a new GV.
1495 if (CA->getType() == GCL->getInitializer()->getType()) {
1496 GCL->setInitializer(CA);
1500 // Create the new global and insert it next to the existing list.
1501 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1502 GCL->getLinkage(), CA,
1505 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1507 // Nuke the old list, replacing any uses with the new one.
1508 if (!GCL->use_empty()) {
1510 if (V->getType() != GCL->getType())
1511 V = ConstantExpr::getCast(V, GCL->getType());
1512 GCL->replaceAllUsesWith(V);
1514 GCL->eraseFromParent();
1523 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1525 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1526 Constant *R = ComputedValues[V];
1527 assert(R && "Reference to an uncomputed value!");
1531 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1532 /// enough for us to understand. In particular, if it is a cast of something,
1533 /// we punt. We basically just support direct accesses to globals and GEP's of
1534 /// globals. This should be kept up to date with CommitValueTo.
1535 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1536 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1537 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1538 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1539 return !GV->isExternal(); // reject external globals.
1541 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1542 // Handle a constantexpr gep.
1543 if (CE->getOpcode() == Instruction::GetElementPtr &&
1544 isa<GlobalVariable>(CE->getOperand(0))) {
1545 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1546 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1547 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1548 return GV->hasInitializer() &&
1549 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1554 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1555 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1556 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1557 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1558 ConstantExpr *Addr, unsigned OpNo) {
1559 // Base case of the recursion.
1560 if (OpNo == Addr->getNumOperands()) {
1561 assert(Val->getType() == Init->getType() && "Type mismatch!");
1565 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1566 std::vector<Constant*> Elts;
1568 // Break up the constant into its elements.
1569 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1570 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1571 Elts.push_back(CS->getOperand(i));
1572 } else if (isa<ConstantAggregateZero>(Init)) {
1573 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1574 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1575 } else if (isa<UndefValue>(Init)) {
1576 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1577 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1579 assert(0 && "This code is out of sync with "
1580 " ConstantFoldLoadThroughGEPConstantExpr");
1583 // Replace the element that we are supposed to.
1584 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1585 unsigned Idx = CU->getZExtValue();
1586 assert(Idx < STy->getNumElements() && "Struct index out of range!");
1587 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1589 // Return the modified struct.
1590 return ConstantStruct::get(Elts);
1592 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1593 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1595 // Break up the array into elements.
1596 std::vector<Constant*> Elts;
1597 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1598 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1599 Elts.push_back(CA->getOperand(i));
1600 } else if (isa<ConstantAggregateZero>(Init)) {
1601 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1602 Elts.assign(ATy->getNumElements(), Elt);
1603 } else if (isa<UndefValue>(Init)) {
1604 Constant *Elt = UndefValue::get(ATy->getElementType());
1605 Elts.assign(ATy->getNumElements(), Elt);
1607 assert(0 && "This code is out of sync with "
1608 " ConstantFoldLoadThroughGEPConstantExpr");
1611 assert(CI->getZExtValue() < ATy->getNumElements());
1612 Elts[CI->getZExtValue()] =
1613 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
1614 return ConstantArray::get(ATy, Elts);
1618 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1619 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1620 static void CommitValueTo(Constant *Val, Constant *Addr) {
1621 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1622 assert(GV->hasInitializer());
1623 GV->setInitializer(Val);
1627 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1628 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1630 Constant *Init = GV->getInitializer();
1631 Init = EvaluateStoreInto(Init, Val, CE, 2);
1632 GV->setInitializer(Init);
1635 /// ComputeLoadResult - Return the value that would be computed by a load from
1636 /// P after the stores reflected by 'memory' have been performed. If we can't
1637 /// decide, return null.
1638 static Constant *ComputeLoadResult(Constant *P,
1639 const std::map<Constant*, Constant*> &Memory) {
1640 // If this memory location has been recently stored, use the stored value: it
1641 // is the most up-to-date.
1642 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1643 if (I != Memory.end()) return I->second;
1646 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1647 if (GV->hasInitializer())
1648 return GV->getInitializer();
1652 // Handle a constantexpr getelementptr.
1653 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1654 if (CE->getOpcode() == Instruction::GetElementPtr &&
1655 isa<GlobalVariable>(CE->getOperand(0))) {
1656 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1657 if (GV->hasInitializer())
1658 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1661 return 0; // don't know how to evaluate.
1664 /// EvaluateFunction - Evaluate a call to function F, returning true if
1665 /// successful, false if we can't evaluate it. ActualArgs contains the formal
1666 /// arguments for the function.
1667 static bool EvaluateFunction(Function *F, Constant *&RetVal,
1668 const std::vector<Constant*> &ActualArgs,
1669 std::vector<Function*> &CallStack,
1670 std::map<Constant*, Constant*> &MutatedMemory,
1671 std::vector<GlobalVariable*> &AllocaTmps) {
1672 // Check to see if this function is already executing (recursion). If so,
1673 // bail out. TODO: we might want to accept limited recursion.
1674 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1677 CallStack.push_back(F);
1679 /// Values - As we compute SSA register values, we store their contents here.
1680 std::map<Value*, Constant*> Values;
1682 // Initialize arguments to the incoming values specified.
1684 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1686 Values[AI] = ActualArgs[ArgNo];
1688 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1689 /// we can only evaluate any one basic block at most once. This set keeps
1690 /// track of what we have executed so we can detect recursive cases etc.
1691 std::set<BasicBlock*> ExecutedBlocks;
1693 // CurInst - The current instruction we're evaluating.
1694 BasicBlock::iterator CurInst = F->begin()->begin();
1696 // This is the main evaluation loop.
1698 Constant *InstResult = 0;
1700 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1701 if (SI->isVolatile()) return false; // no volatile accesses.
1702 Constant *Ptr = getVal(Values, SI->getOperand(1));
1703 if (!isSimpleEnoughPointerToCommit(Ptr))
1704 // If this is too complex for us to commit, reject it.
1706 Constant *Val = getVal(Values, SI->getOperand(0));
1707 MutatedMemory[Ptr] = Val;
1708 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1709 InstResult = ConstantExpr::get(BO->getOpcode(),
1710 getVal(Values, BO->getOperand(0)),
1711 getVal(Values, BO->getOperand(1)));
1712 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1713 InstResult = ConstantExpr::get(SI->getOpcode(),
1714 getVal(Values, SI->getOperand(0)),
1715 getVal(Values, SI->getOperand(1)));
1716 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1717 InstResult = ConstantExpr::getCast(getVal(Values, CI->getOperand(0)),
1719 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1720 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1721 getVal(Values, SI->getOperand(1)),
1722 getVal(Values, SI->getOperand(2)));
1723 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1724 Constant *P = getVal(Values, GEP->getOperand(0));
1725 std::vector<Constant*> GEPOps;
1726 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1727 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1728 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1729 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1730 if (LI->isVolatile()) return false; // no volatile accesses.
1731 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1733 if (InstResult == 0) return false; // Could not evaluate load.
1734 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
1735 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
1736 const Type *Ty = AI->getType()->getElementType();
1737 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1738 GlobalValue::InternalLinkage,
1739 UndefValue::get(Ty),
1741 InstResult = AllocaTmps.back();
1742 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1743 // Cannot handle inline asm.
1744 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1746 // Resolve function pointers.
1747 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1748 if (!Callee) return false; // Cannot resolve.
1750 std::vector<Constant*> Formals;
1751 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1752 Formals.push_back(getVal(Values, CI->getOperand(i)));
1754 if (Callee->isExternal()) {
1755 // If this is a function we can constant fold, do it.
1756 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
1762 if (Callee->getFunctionType()->isVarArg())
1767 // Execute the call, if successful, use the return value.
1768 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1769 MutatedMemory, AllocaTmps))
1771 InstResult = RetVal;
1773 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(CurInst)) {
1774 BasicBlock *NewBB = 0;
1775 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1776 if (BI->isUnconditional()) {
1777 NewBB = BI->getSuccessor(0);
1779 ConstantBool *Cond =
1780 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
1781 if (!Cond) return false; // Cannot determine.
1782 NewBB = BI->getSuccessor(!Cond->getValue());
1784 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1786 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1787 if (!Val) return false; // Cannot determine.
1788 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1789 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1790 if (RI->getNumOperands())
1791 RetVal = getVal(Values, RI->getOperand(0));
1793 CallStack.pop_back(); // return from fn.
1794 return true; // We succeeded at evaluating this ctor!
1796 // invoke, unwind, unreachable.
1797 return false; // Cannot handle this terminator.
1800 // Okay, we succeeded in evaluating this control flow. See if we have
1801 // executed the new block before. If so, we have a looping function,
1802 // which we cannot evaluate in reasonable time.
1803 if (!ExecutedBlocks.insert(NewBB).second)
1804 return false; // looped!
1806 // Okay, we have never been in this block before. Check to see if there
1807 // are any PHI nodes. If so, evaluate them with information about where
1809 BasicBlock *OldBB = CurInst->getParent();
1810 CurInst = NewBB->begin();
1812 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1813 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1815 // Do NOT increment CurInst. We know that the terminator had no value.
1818 // Did not know how to evaluate this!
1822 if (!CurInst->use_empty())
1823 Values[CurInst] = InstResult;
1825 // Advance program counter.
1830 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1831 /// we can. Return true if we can, false otherwise.
1832 static bool EvaluateStaticConstructor(Function *F) {
1833 /// MutatedMemory - For each store we execute, we update this map. Loads
1834 /// check this to get the most up-to-date value. If evaluation is successful,
1835 /// this state is committed to the process.
1836 std::map<Constant*, Constant*> MutatedMemory;
1838 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1839 /// to represent its body. This vector is needed so we can delete the
1840 /// temporary globals when we are done.
1841 std::vector<GlobalVariable*> AllocaTmps;
1843 /// CallStack - This is used to detect recursion. In pathological situations
1844 /// we could hit exponential behavior, but at least there is nothing
1846 std::vector<Function*> CallStack;
1848 // Call the function.
1849 Constant *RetValDummy;
1850 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1851 CallStack, MutatedMemory, AllocaTmps);
1853 // We succeeded at evaluation: commit the result.
1854 DEBUG(std::cerr << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" <<
1855 F->getName() << "' to " << MutatedMemory.size() << " stores.\n");
1856 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1857 E = MutatedMemory.end(); I != E; ++I)
1858 CommitValueTo(I->second, I->first);
1861 // At this point, we are done interpreting. If we created any 'alloca'
1862 // temporaries, release them now.
1863 while (!AllocaTmps.empty()) {
1864 GlobalVariable *Tmp = AllocaTmps.back();
1865 AllocaTmps.pop_back();
1867 // If there are still users of the alloca, the program is doing something
1868 // silly, e.g. storing the address of the alloca somewhere and using it
1869 // later. Since this is undefined, we'll just make it be null.
1870 if (!Tmp->use_empty())
1871 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1880 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1881 /// Return true if anything changed.
1882 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1883 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1884 bool MadeChange = false;
1885 if (Ctors.empty()) return false;
1887 // Loop over global ctors, optimizing them when we can.
1888 for (unsigned i = 0; i != Ctors.size(); ++i) {
1889 Function *F = Ctors[i];
1890 // Found a null terminator in the middle of the list, prune off the rest of
1893 if (i != Ctors.size()-1) {
1900 // We cannot simplify external ctor functions.
1901 if (F->empty()) continue;
1903 // If we can evaluate the ctor at compile time, do.
1904 if (EvaluateStaticConstructor(F)) {
1905 Ctors.erase(Ctors.begin()+i);
1908 ++NumCtorsEvaluated;
1913 if (!MadeChange) return false;
1915 GCL = InstallGlobalCtors(GCL, Ctors);
1920 bool GlobalOpt::runOnModule(Module &M) {
1921 bool Changed = false;
1923 // Try to find the llvm.globalctors list.
1924 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
1926 bool LocalChange = true;
1927 while (LocalChange) {
1928 LocalChange = false;
1930 // Delete functions that are trivially dead, ccc -> fastcc
1931 LocalChange |= OptimizeFunctions(M);
1933 // Optimize global_ctors list.
1935 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1937 // Optimize non-address-taken globals.
1938 LocalChange |= OptimizeGlobalVars(M);
1939 Changed |= LocalChange;
1942 // TODO: Move all global ctors functions to the end of the module for code