1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Analysis/ConstantFolding.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/StringExtras.h"
37 STATISTIC(NumMarked , "Number of globals marked constant");
38 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
39 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
40 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
41 STATISTIC(NumDeleted , "Number of globals deleted");
42 STATISTIC(NumFnDeleted , "Number of functions deleted");
43 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
44 STATISTIC(NumLocalized , "Number of globals localized");
45 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
46 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
47 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
50 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.addRequired<TargetData>();
54 static char ID; // Pass identification, replacement for typeid
55 GlobalOpt() : ModulePass((intptr_t)&ID) {}
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 char GlobalOpt::ID = 0;
68 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
71 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
73 /// GlobalStatus - As we analyze each global, keep track of some information
74 /// about it. If we find out that the address of the global is taken, none of
75 /// this info will be accurate.
76 struct VISIBILITY_HIDDEN GlobalStatus {
77 /// isLoaded - True if the global is ever loaded. If the global isn't ever
78 /// loaded it can be deleted.
81 /// StoredType - Keep track of what stores to the global look like.
84 /// NotStored - There is no store to this global. It can thus be marked
88 /// isInitializerStored - This global is stored to, but the only thing
89 /// stored is the constant it was initialized with. This is only tracked
90 /// for scalar globals.
93 /// isStoredOnce - This global is stored to, but only its initializer and
94 /// one other value is ever stored to it. If this global isStoredOnce, we
95 /// track the value stored to it in StoredOnceValue below. This is only
96 /// tracked for scalar globals.
99 /// isStored - This global is stored to by multiple values or something else
100 /// that we cannot track.
104 /// StoredOnceValue - If only one value (besides the initializer constant) is
105 /// ever stored to this global, keep track of what value it is.
106 Value *StoredOnceValue;
108 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
109 /// null/false. When the first accessing function is noticed, it is recorded.
110 /// When a second different accessing function is noticed,
111 /// HasMultipleAccessingFunctions is set to true.
112 Function *AccessingFunction;
113 bool HasMultipleAccessingFunctions;
115 /// HasNonInstructionUser - Set to true if this global has a user that is not
116 /// an instruction (e.g. a constant expr or GV initializer).
117 bool HasNonInstructionUser;
119 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
122 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
123 AccessingFunction(0), HasMultipleAccessingFunctions(false),
124 HasNonInstructionUser(false), HasPHIUser(false) {}
129 /// ConstantIsDead - Return true if the specified constant is (transitively)
130 /// dead. The constant may be used by other constants (e.g. constant arrays and
131 /// constant exprs) as long as they are dead, but it cannot be used by anything
133 static bool ConstantIsDead(Constant *C) {
134 if (isa<GlobalValue>(C)) return false;
136 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
137 if (Constant *CU = dyn_cast<Constant>(*UI)) {
138 if (!ConstantIsDead(CU)) return false;
145 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
146 /// structure. If the global has its address taken, return true to indicate we
147 /// can't do anything with it.
149 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
150 std::set<PHINode*> &PHIUsers) {
151 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
153 GS.HasNonInstructionUser = true;
155 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
157 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
158 if (!GS.HasMultipleAccessingFunctions) {
159 Function *F = I->getParent()->getParent();
160 if (GS.AccessingFunction == 0)
161 GS.AccessingFunction = F;
162 else if (GS.AccessingFunction != F)
163 GS.HasMultipleAccessingFunctions = true;
165 if (isa<LoadInst>(I)) {
167 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
168 // Don't allow a store OF the address, only stores TO the address.
169 if (SI->getOperand(0) == V) return true;
171 // If this is a direct store to the global (i.e., the global is a scalar
172 // value, not an aggregate), keep more specific information about
174 if (GS.StoredType != GlobalStatus::isStored)
175 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
176 Value *StoredVal = SI->getOperand(0);
177 if (StoredVal == GV->getInitializer()) {
178 if (GS.StoredType < GlobalStatus::isInitializerStored)
179 GS.StoredType = GlobalStatus::isInitializerStored;
180 } else if (isa<LoadInst>(StoredVal) &&
181 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
183 if (GS.StoredType < GlobalStatus::isInitializerStored)
184 GS.StoredType = GlobalStatus::isInitializerStored;
185 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
186 GS.StoredType = GlobalStatus::isStoredOnce;
187 GS.StoredOnceValue = StoredVal;
188 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
189 GS.StoredOnceValue == StoredVal) {
192 GS.StoredType = GlobalStatus::isStored;
195 GS.StoredType = GlobalStatus::isStored;
197 } else if (isa<GetElementPtrInst>(I)) {
198 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
199 } else if (isa<SelectInst>(I)) {
200 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
201 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
202 // PHI nodes we can check just like select or GEP instructions, but we
203 // have to be careful about infinite recursion.
204 if (PHIUsers.insert(PN).second) // Not already visited.
205 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
206 GS.HasPHIUser = true;
207 } else if (isa<CmpInst>(I)) {
208 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
209 if (I->getOperand(1) == V)
210 GS.StoredType = GlobalStatus::isStored;
211 if (I->getOperand(2) == V)
213 } else if (isa<MemSetInst>(I)) {
214 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
215 GS.StoredType = GlobalStatus::isStored;
217 return true; // Any other non-load instruction might take address!
219 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
220 GS.HasNonInstructionUser = true;
221 // We might have a dead and dangling constant hanging off of here.
222 if (!ConstantIsDead(C))
225 GS.HasNonInstructionUser = true;
226 // Otherwise must be some other user.
233 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
234 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
236 unsigned IdxV = CI->getZExtValue();
238 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
239 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
240 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
241 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
242 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
243 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
244 } else if (isa<ConstantAggregateZero>(Agg)) {
245 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
246 if (IdxV < STy->getNumElements())
247 return Constant::getNullValue(STy->getElementType(IdxV));
248 } else if (const SequentialType *STy =
249 dyn_cast<SequentialType>(Agg->getType())) {
250 return Constant::getNullValue(STy->getElementType());
252 } else if (isa<UndefValue>(Agg)) {
253 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
254 if (IdxV < STy->getNumElements())
255 return UndefValue::get(STy->getElementType(IdxV));
256 } else if (const SequentialType *STy =
257 dyn_cast<SequentialType>(Agg->getType())) {
258 return UndefValue::get(STy->getElementType());
265 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
266 /// users of the global, cleaning up the obvious ones. This is largely just a
267 /// quick scan over the use list to clean up the easy and obvious cruft. This
268 /// returns true if it made a change.
269 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
270 bool Changed = false;
271 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
274 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
276 // Replace the load with the initializer.
277 LI->replaceAllUsesWith(Init);
278 LI->eraseFromParent();
281 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
282 // Store must be unreachable or storing Init into the global.
283 SI->eraseFromParent();
285 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
286 if (CE->getOpcode() == Instruction::GetElementPtr) {
287 Constant *SubInit = 0;
289 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
290 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
291 } else if (CE->getOpcode() == Instruction::BitCast &&
292 isa<PointerType>(CE->getType())) {
293 // Pointer cast, delete any stores and memsets to the global.
294 Changed |= CleanupConstantGlobalUsers(CE, 0);
297 if (CE->use_empty()) {
298 CE->destroyConstant();
301 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
302 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
303 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
304 // and will invalidate our notion of what Init is.
305 Constant *SubInit = 0;
306 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
308 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
309 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
310 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
312 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
314 if (GEP->use_empty()) {
315 GEP->eraseFromParent();
318 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
319 if (MI->getRawDest() == V) {
320 MI->eraseFromParent();
324 } else if (Constant *C = dyn_cast<Constant>(U)) {
325 // If we have a chain of dead constantexprs or other things dangling from
326 // us, and if they are all dead, nuke them without remorse.
327 if (ConstantIsDead(C)) {
328 C->destroyConstant();
329 // This could have invalidated UI, start over from scratch.
330 CleanupConstantGlobalUsers(V, Init);
339 /// UsersSafeToSRA - Look at all uses of the global and decide whether it is
340 /// safe for us to perform this transformation.
342 static bool UsersSafeToSRA(Value *V) {
343 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
344 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
345 if (CE->getOpcode() != Instruction::GetElementPtr)
348 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
349 // don't like < 3 operand CE's, and we don't like non-constant integer
351 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
354 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
355 if (!isa<ConstantInt>(CE->getOperand(i)))
358 if (!UsersSafeToSRA(CE)) return false;
362 if (Instruction *I = dyn_cast<Instruction>(*UI)) {
363 if (isa<LoadInst>(I)) continue;
365 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
366 // Don't allow a store OF the address, only stores TO the address.
367 if (SI->getOperand(0) == V) return false;
371 if (isa<GetElementPtrInst>(I)) {
372 if (!UsersSafeToSRA(I)) return false;
374 // If the first two indices are constants, this can be SRA'd.
375 if (isa<GlobalVariable>(I->getOperand(0))) {
376 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
377 !cast<Constant>(I->getOperand(1))->isNullValue() ||
378 !isa<ConstantInt>(I->getOperand(2)))
383 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
384 if (CE->getOpcode() != Instruction::GetElementPtr ||
385 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
386 !isa<Constant>(I->getOperand(0)) ||
387 !cast<Constant>(I->getOperand(0))->isNullValue())
393 return false; // Any other instruction is not safe.
395 if (Constant *C = dyn_cast<Constant>(*UI)) {
396 // We might have a dead and dangling constant hanging off of here.
397 if (!ConstantIsDead(C))
401 // Otherwise must be some other user.
408 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
409 /// variable. This opens the door for other optimizations by exposing the
410 /// behavior of the program in a more fine-grained way. We have determined that
411 /// this transformation is safe already. We return the first global variable we
412 /// insert so that the caller can reprocess it.
413 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
414 // Make sure this global only has simple uses that we can SRA.
415 if (!UsersSafeToSRA(GV))
418 assert(GV->hasInternalLinkage() && !GV->isConstant());
419 Constant *Init = GV->getInitializer();
420 const Type *Ty = Init->getType();
422 std::vector<GlobalVariable*> NewGlobals;
423 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
425 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
426 NewGlobals.reserve(STy->getNumElements());
427 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
428 Constant *In = getAggregateConstantElement(Init,
429 ConstantInt::get(Type::Int32Ty, i));
430 assert(In && "Couldn't get element of initializer?");
431 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
432 GlobalVariable::InternalLinkage,
433 In, GV->getName()+"."+utostr(i),
435 GV->isThreadLocal());
436 Globals.insert(GV, NGV);
437 NewGlobals.push_back(NGV);
439 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
440 unsigned NumElements = 0;
441 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
442 NumElements = ATy->getNumElements();
443 else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
444 NumElements = PTy->getNumElements();
446 assert(0 && "Unknown aggregate sequential type!");
448 if (NumElements > 16 && GV->hasNUsesOrMore(16))
449 return 0; // It's not worth it.
450 NewGlobals.reserve(NumElements);
451 for (unsigned i = 0, e = NumElements; i != e; ++i) {
452 Constant *In = getAggregateConstantElement(Init,
453 ConstantInt::get(Type::Int32Ty, i));
454 assert(In && "Couldn't get element of initializer?");
456 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
457 GlobalVariable::InternalLinkage,
458 In, GV->getName()+"."+utostr(i),
460 GV->isThreadLocal());
461 Globals.insert(GV, NGV);
462 NewGlobals.push_back(NGV);
466 if (NewGlobals.empty())
469 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
471 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
473 // Loop over all of the uses of the global, replacing the constantexpr geps,
474 // with smaller constantexpr geps or direct references.
475 while (!GV->use_empty()) {
476 User *GEP = GV->use_back();
477 assert(((isa<ConstantExpr>(GEP) &&
478 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
479 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
481 // Ignore the 1th operand, which has to be zero or else the program is quite
482 // broken (undefined). Get the 2nd operand, which is the structure or array
484 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
485 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
487 Value *NewPtr = NewGlobals[Val];
489 // Form a shorter GEP if needed.
490 if (GEP->getNumOperands() > 3)
491 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
492 SmallVector<Constant*, 8> Idxs;
493 Idxs.push_back(NullInt);
494 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
495 Idxs.push_back(CE->getOperand(i));
496 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
497 &Idxs[0], Idxs.size());
499 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
500 SmallVector<Value*, 8> Idxs;
501 Idxs.push_back(NullInt);
502 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
503 Idxs.push_back(GEPI->getOperand(i));
504 NewPtr = new GetElementPtrInst(NewPtr, Idxs.begin(), Idxs.end(),
505 GEPI->getName()+"."+utostr(Val), GEPI);
507 GEP->replaceAllUsesWith(NewPtr);
509 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
510 GEPI->eraseFromParent();
512 cast<ConstantExpr>(GEP)->destroyConstant();
515 // Delete the old global, now that it is dead.
519 // Loop over the new globals array deleting any globals that are obviously
520 // dead. This can arise due to scalarization of a structure or an array that
521 // has elements that are dead.
522 unsigned FirstGlobal = 0;
523 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
524 if (NewGlobals[i]->use_empty()) {
525 Globals.erase(NewGlobals[i]);
526 if (FirstGlobal == i) ++FirstGlobal;
529 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
532 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
533 /// value will trap if the value is dynamically null. PHIs keeps track of any
534 /// phi nodes we've seen to avoid reprocessing them.
535 static bool AllUsesOfValueWillTrapIfNull(Value *V,
536 SmallPtrSet<PHINode*, 8> &PHIs) {
537 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
538 if (isa<LoadInst>(*UI)) {
540 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
541 if (SI->getOperand(0) == V) {
542 //cerr << "NONTRAPPING USE: " << **UI;
543 return false; // Storing the value.
545 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
546 if (CI->getOperand(0) != V) {
547 //cerr << "NONTRAPPING USE: " << **UI;
548 return false; // Not calling the ptr
550 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
551 if (II->getOperand(0) != V) {
552 //cerr << "NONTRAPPING USE: " << **UI;
553 return false; // Not calling the ptr
555 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
556 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
557 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
558 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
559 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
560 // If we've already seen this phi node, ignore it, it has already been
563 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
564 } else if (isa<ICmpInst>(*UI) &&
565 isa<ConstantPointerNull>(UI->getOperand(1))) {
566 // Ignore setcc X, null
568 //cerr << "NONTRAPPING USE: " << **UI;
574 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
575 /// from GV will trap if the loaded value is null. Note that this also permits
576 /// comparisons of the loaded value against null, as a special case.
577 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
578 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
579 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
580 SmallPtrSet<PHINode*, 8> PHIs;
581 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
583 } else if (isa<StoreInst>(*UI)) {
584 // Ignore stores to the global.
586 // We don't know or understand this user, bail out.
587 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
594 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
595 bool Changed = false;
596 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
597 Instruction *I = cast<Instruction>(*UI++);
598 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
599 LI->setOperand(0, NewV);
601 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
602 if (SI->getOperand(1) == V) {
603 SI->setOperand(1, NewV);
606 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
607 if (I->getOperand(0) == V) {
608 // Calling through the pointer! Turn into a direct call, but be careful
609 // that the pointer is not also being passed as an argument.
610 I->setOperand(0, NewV);
612 bool PassedAsArg = false;
613 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
614 if (I->getOperand(i) == V) {
616 I->setOperand(i, NewV);
620 // Being passed as an argument also. Be careful to not invalidate UI!
624 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
625 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
626 ConstantExpr::getCast(CI->getOpcode(),
627 NewV, CI->getType()));
628 if (CI->use_empty()) {
630 CI->eraseFromParent();
632 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
633 // Should handle GEP here.
634 SmallVector<Constant*, 8> Idxs;
635 Idxs.reserve(GEPI->getNumOperands()-1);
636 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
637 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
641 if (Idxs.size() == GEPI->getNumOperands()-1)
642 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
643 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
645 if (GEPI->use_empty()) {
647 GEPI->eraseFromParent();
656 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
657 /// value stored into it. If there are uses of the loaded value that would trap
658 /// if the loaded value is dynamically null, then we know that they cannot be
659 /// reachable with a null optimize away the load.
660 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
661 std::vector<LoadInst*> Loads;
662 bool Changed = false;
664 // Replace all uses of loads with uses of uses of the stored value.
665 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
667 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
669 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
671 // If we get here we could have stores, selects, or phi nodes whose values
673 assert((isa<StoreInst>(*GUI) || isa<PHINode>(*GUI) ||
674 isa<SelectInst>(*GUI) || isa<ConstantExpr>(*GUI)) &&
675 "Only expect load and stores!");
679 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
683 // Delete all of the loads we can, keeping track of whether we nuked them all!
684 bool AllLoadsGone = true;
685 while (!Loads.empty()) {
686 LoadInst *L = Loads.back();
687 if (L->use_empty()) {
688 L->eraseFromParent();
691 AllLoadsGone = false;
696 // If we nuked all of the loads, then none of the stores are needed either,
697 // nor is the global.
699 DOUT << " *** GLOBAL NOW DEAD!\n";
700 CleanupConstantGlobalUsers(GV, 0);
701 if (GV->use_empty()) {
702 GV->eraseFromParent();
710 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
711 /// instructions that are foldable.
712 static void ConstantPropUsersOf(Value *V) {
713 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
714 if (Instruction *I = dyn_cast<Instruction>(*UI++))
715 if (Constant *NewC = ConstantFoldInstruction(I)) {
716 I->replaceAllUsesWith(NewC);
718 // Advance UI to the next non-I use to avoid invalidating it!
719 // Instructions could multiply use V.
720 while (UI != E && *UI == I)
722 I->eraseFromParent();
726 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
727 /// variable, and transforms the program as if it always contained the result of
728 /// the specified malloc. Because it is always the result of the specified
729 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
730 /// malloc into a global, and any loads of GV as uses of the new global.
731 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
733 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
734 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
736 if (NElements->getZExtValue() != 1) {
737 // If we have an array allocation, transform it to a single element
738 // allocation to make the code below simpler.
739 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
740 NElements->getZExtValue());
742 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
743 MI->getAlignment(), MI->getName(), MI);
745 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
746 Value *NewGEP = new GetElementPtrInst(NewMI, Indices, Indices + 2,
747 NewMI->getName()+".el0", MI);
748 MI->replaceAllUsesWith(NewGEP);
749 MI->eraseFromParent();
753 // Create the new global variable. The contents of the malloc'd memory is
754 // undefined, so initialize with an undef value.
755 Constant *Init = UndefValue::get(MI->getAllocatedType());
756 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
757 GlobalValue::InternalLinkage, Init,
758 GV->getName()+".body",
760 GV->isThreadLocal());
761 GV->getParent()->getGlobalList().insert(GV, NewGV);
763 // Anything that used the malloc now uses the global directly.
764 MI->replaceAllUsesWith(NewGV);
766 Constant *RepValue = NewGV;
767 if (NewGV->getType() != GV->getType()->getElementType())
768 RepValue = ConstantExpr::getBitCast(RepValue,
769 GV->getType()->getElementType());
771 // If there is a comparison against null, we will insert a global bool to
772 // keep track of whether the global was initialized yet or not.
773 GlobalVariable *InitBool =
774 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
775 ConstantInt::getFalse(), GV->getName()+".init",
776 (Module *)NULL, GV->isThreadLocal());
777 bool InitBoolUsed = false;
779 // Loop over all uses of GV, processing them in turn.
780 std::vector<StoreInst*> Stores;
781 while (!GV->use_empty())
782 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
783 while (!LI->use_empty()) {
784 Use &LoadUse = LI->use_begin().getUse();
785 if (!isa<ICmpInst>(LoadUse.getUser()))
788 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
789 // Replace the cmp X, 0 with a use of the bool value.
790 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
792 switch (CI->getPredicate()) {
793 default: assert(0 && "Unknown ICmp Predicate!");
794 case ICmpInst::ICMP_ULT:
795 case ICmpInst::ICMP_SLT:
796 LV = ConstantInt::getFalse(); // X < null -> always false
798 case ICmpInst::ICMP_ULE:
799 case ICmpInst::ICMP_SLE:
800 case ICmpInst::ICMP_EQ:
801 LV = BinaryOperator::createNot(LV, "notinit", CI);
803 case ICmpInst::ICMP_NE:
804 case ICmpInst::ICMP_UGE:
805 case ICmpInst::ICMP_SGE:
806 case ICmpInst::ICMP_UGT:
807 case ICmpInst::ICMP_SGT:
810 CI->replaceAllUsesWith(LV);
811 CI->eraseFromParent();
814 LI->eraseFromParent();
816 StoreInst *SI = cast<StoreInst>(GV->use_back());
817 // The global is initialized when the store to it occurs.
818 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
819 SI->eraseFromParent();
822 // If the initialization boolean was used, insert it, otherwise delete it.
824 while (!InitBool->use_empty()) // Delete initializations
825 cast<Instruction>(InitBool->use_back())->eraseFromParent();
828 GV->getParent()->getGlobalList().insert(GV, InitBool);
831 // Now the GV is dead, nuke it and the malloc.
832 GV->eraseFromParent();
833 MI->eraseFromParent();
835 // To further other optimizations, loop over all users of NewGV and try to
836 // constant prop them. This will promote GEP instructions with constant
837 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
838 ConstantPropUsersOf(NewGV);
839 if (RepValue != NewGV)
840 ConstantPropUsersOf(RepValue);
845 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
846 /// to make sure that there are no complex uses of V. We permit simple things
847 /// like dereferencing the pointer, but not storing through the address, unless
848 /// it is to the specified global.
849 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
851 SmallPtrSet<PHINode*, 8> &PHIs) {
852 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
853 if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
855 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
856 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
857 return false; // Storing the pointer itself... bad.
858 // Otherwise, storing through it, or storing into GV... fine.
859 } else if (isa<GetElementPtrInst>(*UI)) {
860 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),
863 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
864 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
867 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
875 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
876 /// somewhere. Transform all uses of the allocation into loads from the
877 /// global and uses of the resultant pointer. Further, delete the store into
878 /// GV. This assumes that these value pass the
879 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
880 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
881 GlobalVariable *GV) {
882 while (!Alloc->use_empty()) {
883 Instruction *U = cast<Instruction>(*Alloc->use_begin());
884 Instruction *InsertPt = U;
885 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
886 // If this is the store of the allocation into the global, remove it.
887 if (SI->getOperand(1) == GV) {
888 SI->eraseFromParent();
891 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
892 // Insert the load in the corresponding predecessor, not right before the
894 unsigned PredNo = Alloc->use_begin().getOperandNo()/2;
895 InsertPt = PN->getIncomingBlock(PredNo)->getTerminator();
898 // Insert a load from the global, and use it instead of the malloc.
899 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
900 U->replaceUsesOfWith(Alloc, NL);
904 /// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
905 /// GV are simple enough to perform HeapSRA, return true.
906 static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
908 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
910 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
911 // We permit two users of the load: setcc comparing against the null
912 // pointer, and a getelementptr of a specific form.
913 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
915 // Comparison against null is ok.
916 if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
917 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
922 // getelementptr is also ok, but only a simple form.
923 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
924 // Must index into the array and into the struct.
925 if (GEPI->getNumOperands() < 3)
928 // Otherwise the GEP is ok.
932 if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
933 // We have a phi of a load from the global. We can only handle this
934 // if the other PHI'd values are actually the same. In this case,
935 // the rewriter will just drop the phi entirely.
936 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
937 Value *IV = PN->getIncomingValue(i);
938 if (IV == LI) continue; // Trivial the same.
940 // If the phi'd value is from the malloc that initializes the value,
942 if (IV == MI) continue;
944 // Otherwise, we don't know what it is.
950 // Otherwise we don't know what this is, not ok.
957 /// GetHeapSROALoad - Return the load for the specified field of the HeapSROA'd
958 /// value, lazily creating it on demand.
959 static Value *GetHeapSROALoad(Instruction *Load, unsigned FieldNo,
960 const std::vector<GlobalVariable*> &FieldGlobals,
961 std::vector<Value *> &InsertedLoadsForPtr) {
962 if (InsertedLoadsForPtr.size() <= FieldNo)
963 InsertedLoadsForPtr.resize(FieldNo+1);
964 if (InsertedLoadsForPtr[FieldNo] == 0)
965 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
966 Load->getName()+".f" +
967 utostr(FieldNo), Load);
968 return InsertedLoadsForPtr[FieldNo];
971 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
972 /// the load, rewrite the derived value to use the HeapSRoA'd load.
973 static void RewriteHeapSROALoadUser(LoadInst *Load, Instruction *LoadUser,
974 const std::vector<GlobalVariable*> &FieldGlobals,
975 std::vector<Value *> &InsertedLoadsForPtr) {
976 // If this is a comparison against null, handle it.
977 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
978 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
979 // If we have a setcc of the loaded pointer, we can use a setcc of any
982 if (InsertedLoadsForPtr.empty()) {
983 NPtr = GetHeapSROALoad(Load, 0, FieldGlobals, InsertedLoadsForPtr);
985 NPtr = InsertedLoadsForPtr.back();
988 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
989 Constant::getNullValue(NPtr->getType()),
990 SCI->getName(), SCI);
991 SCI->replaceAllUsesWith(New);
992 SCI->eraseFromParent();
996 // Handle 'getelementptr Ptr, Idx, uint FieldNo ...'
997 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
998 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
999 && "Unexpected GEPI!");
1001 // Load the pointer for this field.
1002 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1003 Value *NewPtr = GetHeapSROALoad(Load, FieldNo,
1004 FieldGlobals, InsertedLoadsForPtr);
1006 // Create the new GEP idx vector.
1007 SmallVector<Value*, 8> GEPIdx;
1008 GEPIdx.push_back(GEPI->getOperand(1));
1009 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1011 Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx.begin(), GEPIdx.end(),
1012 GEPI->getName(), GEPI);
1013 GEPI->replaceAllUsesWith(NGEPI);
1014 GEPI->eraseFromParent();
1018 // Handle PHI nodes. PHI nodes must be merging in the same values, plus
1019 // potentially the original malloc. Insert phi nodes for each field, then
1020 // process uses of the PHI.
1021 PHINode *PN = cast<PHINode>(LoadUser);
1022 std::vector<Value *> PHIsForField;
1023 PHIsForField.resize(FieldGlobals.size());
1024 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1025 Value *LoadV = GetHeapSROALoad(Load, i, FieldGlobals, InsertedLoadsForPtr);
1027 PHINode *FieldPN = new PHINode(LoadV->getType(),
1028 PN->getName()+"."+utostr(i), PN);
1029 // Fill in the predecessor values.
1030 for (unsigned pred = 0, e = PN->getNumIncomingValues(); pred != e; ++pred) {
1031 // Each predecessor either uses the load or the original malloc.
1032 Value *InVal = PN->getIncomingValue(pred);
1033 BasicBlock *BB = PN->getIncomingBlock(pred);
1035 if (isa<MallocInst>(InVal)) {
1036 // Insert a reload from the global in the predecessor.
1037 NewVal = GetHeapSROALoad(BB->getTerminator(), i, FieldGlobals,
1040 NewVal = InsertedLoadsForPtr[i];
1042 FieldPN->addIncoming(NewVal, BB);
1044 PHIsForField[i] = FieldPN;
1047 // Since PHIsForField specifies a phi for every input value, the lazy inserter
1048 // will never insert a load.
1049 while (!PN->use_empty())
1050 RewriteHeapSROALoadUser(Load, PN->use_back(), FieldGlobals, PHIsForField);
1051 PN->eraseFromParent();
1054 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1055 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1056 /// use FieldGlobals instead. All uses of loaded values satisfy
1057 /// GlobalLoadUsesSimpleEnoughForHeapSRA.
1058 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1059 const std::vector<GlobalVariable*> &FieldGlobals) {
1060 std::vector<Value *> InsertedLoadsForPtr;
1061 //InsertedLoadsForPtr.resize(FieldGlobals.size());
1062 while (!Load->use_empty())
1063 RewriteHeapSROALoadUser(Load, Load->use_back(),
1064 FieldGlobals, InsertedLoadsForPtr);
1067 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1068 /// it up into multiple allocations of arrays of the fields.
1069 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
1070 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
1071 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1073 // There is guaranteed to be at least one use of the malloc (storing
1074 // it into GV). If there are other uses, change them to be uses of
1075 // the global to simplify later code. This also deletes the store
1077 ReplaceUsesOfMallocWithGlobal(MI, GV);
1079 // Okay, at this point, there are no users of the malloc. Insert N
1080 // new mallocs at the same place as MI, and N globals.
1081 std::vector<GlobalVariable*> FieldGlobals;
1082 std::vector<MallocInst*> FieldMallocs;
1084 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1085 const Type *FieldTy = STy->getElementType(FieldNo);
1086 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
1088 GlobalVariable *NGV =
1089 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1090 Constant::getNullValue(PFieldTy),
1091 GV->getName() + ".f" + utostr(FieldNo), GV,
1092 GV->isThreadLocal());
1093 FieldGlobals.push_back(NGV);
1095 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1096 MI->getName() + ".f" + utostr(FieldNo),MI);
1097 FieldMallocs.push_back(NMI);
1098 new StoreInst(NMI, NGV, MI);
1101 // The tricky aspect of this transformation is handling the case when malloc
1102 // fails. In the original code, malloc failing would set the result pointer
1103 // of malloc to null. In this case, some mallocs could succeed and others
1104 // could fail. As such, we emit code that looks like this:
1105 // F0 = malloc(field0)
1106 // F1 = malloc(field1)
1107 // F2 = malloc(field2)
1108 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1109 // if (F0) { free(F0); F0 = 0; }
1110 // if (F1) { free(F1); F1 = 0; }
1111 // if (F2) { free(F2); F2 = 0; }
1113 Value *RunningOr = 0;
1114 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1115 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
1116 Constant::getNullValue(FieldMallocs[i]->getType()),
1119 RunningOr = Cond; // First seteq
1121 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
1124 // Split the basic block at the old malloc.
1125 BasicBlock *OrigBB = MI->getParent();
1126 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1128 // Create the block to check the first condition. Put all these blocks at the
1129 // end of the function as they are unlikely to be executed.
1130 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
1131 OrigBB->getParent());
1133 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1134 // branch on RunningOr.
1135 OrigBB->getTerminator()->eraseFromParent();
1136 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
1138 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1139 // pointer, because some may be null while others are not.
1140 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1141 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1142 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1143 Constant::getNullValue(GVVal->getType()),
1144 "tmp", NullPtrBlock);
1145 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1146 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1147 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1149 // Fill in FreeBlock.
1150 new FreeInst(GVVal, FreeBlock);
1151 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1153 new BranchInst(NextBlock, FreeBlock);
1155 NullPtrBlock = NextBlock;
1158 new BranchInst(ContBB, NullPtrBlock);
1161 // MI is no longer needed, remove it.
1162 MI->eraseFromParent();
1165 // Okay, the malloc site is completely handled. All of the uses of GV are now
1166 // loads, and all uses of those loads are simple. Rewrite them to use loads
1167 // of the per-field globals instead.
1168 while (!GV->use_empty()) {
1169 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1170 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1171 LI->eraseFromParent();
1173 // Must be a store of null.
1174 StoreInst *SI = cast<StoreInst>(GV->use_back());
1175 assert(isa<Constant>(SI->getOperand(0)) &&
1176 cast<Constant>(SI->getOperand(0))->isNullValue() &&
1177 "Unexpected heap-sra user!");
1179 // Insert a store of null into each global.
1180 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1182 Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1183 new StoreInst(Null, FieldGlobals[i], SI);
1185 // Erase the original store.
1186 SI->eraseFromParent();
1190 // The old global is now dead, remove it.
1191 GV->eraseFromParent();
1194 return FieldGlobals[0];
1198 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1199 // that only one value (besides its initializer) is ever stored to the global.
1200 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1201 Module::global_iterator &GVI,
1203 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1204 StoredOnceVal = CI->getOperand(0);
1205 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
1206 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
1207 bool IsJustACast = true;
1208 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1209 if (!isa<Constant>(GEPI->getOperand(i)) ||
1210 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1211 IsJustACast = false;
1215 StoredOnceVal = GEPI->getOperand(0);
1218 // If we are dealing with a pointer global that is initialized to null and
1219 // only has one (non-null) value stored into it, then we can optimize any
1220 // users of the loaded value (often calls and loads) that would trap if the
1222 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1223 GV->getInitializer()->isNullValue()) {
1224 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1225 if (GV->getInitializer()->getType() != SOVC->getType())
1226 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1228 // Optimize away any trapping uses of the loaded value.
1229 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1231 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1232 // If this is a malloc of an abstract type, don't touch it.
1233 if (!MI->getAllocatedType()->isSized())
1236 // We can't optimize this global unless all uses of it are *known* to be
1237 // of the malloc value, not of the null initializer value (consider a use
1238 // that compares the global's value against zero to see if the malloc has
1239 // been reached). To do this, we check to see if all uses of the global
1240 // would trap if the global were null: this proves that they must all
1241 // happen after the malloc.
1242 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1245 // We can't optimize this if the malloc itself is used in a complex way,
1246 // for example, being stored into multiple globals. This allows the
1247 // malloc to be stored into the specified global, loaded setcc'd, and
1248 // GEP'd. These are all things we could transform to using the global
1251 SmallPtrSet<PHINode*, 8> PHIs;
1252 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1257 // If we have a global that is only initialized with a fixed size malloc,
1258 // transform the program to use global memory instead of malloc'd memory.
1259 // This eliminates dynamic allocation, avoids an indirection accessing the
1260 // data, and exposes the resultant global to further GlobalOpt.
1261 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1262 // Restrict this transformation to only working on small allocations
1263 // (2048 bytes currently), as we don't want to introduce a 16M global or
1265 if (NElements->getZExtValue()*
1266 TD.getABITypeSize(MI->getAllocatedType()) < 2048) {
1267 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1272 // If the allocation is an array of structures, consider transforming this
1273 // into multiple malloc'd arrays, one for each field. This is basically
1274 // SRoA for malloc'd memory.
1275 if (const StructType *AllocTy =
1276 dyn_cast<StructType>(MI->getAllocatedType())) {
1277 // This the structure has an unreasonable number of fields, leave it
1279 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1280 GlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
1281 GVI = PerformHeapAllocSRoA(GV, MI);
1291 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1292 /// two values ever stored into GV are its initializer and OtherVal. See if we
1293 /// can shrink the global into a boolean and select between the two values
1294 /// whenever it is used. This exposes the values to other scalar optimizations.
1295 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1296 const Type *GVElType = GV->getType()->getElementType();
1298 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1299 // an FP value or vector, don't do this optimization because a select between
1300 // them is very expensive and unlikely to lead to later simplification.
1301 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
1302 isa<VectorType>(GVElType))
1305 // Walk the use list of the global seeing if all the uses are load or store.
1306 // If there is anything else, bail out.
1307 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1308 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1311 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1313 // Create the new global, initializing it to false.
1314 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
1315 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
1318 GV->isThreadLocal());
1319 GV->getParent()->getGlobalList().insert(GV, NewGV);
1321 Constant *InitVal = GV->getInitializer();
1322 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1324 // If initialized to zero and storing one into the global, we can use a cast
1325 // instead of a select to synthesize the desired value.
1326 bool IsOneZero = false;
1327 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1328 IsOneZero = InitVal->isNullValue() && CI->isOne();
1330 while (!GV->use_empty()) {
1331 Instruction *UI = cast<Instruction>(GV->use_back());
1332 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1333 // Change the store into a boolean store.
1334 bool StoringOther = SI->getOperand(0) == OtherVal;
1335 // Only do this if we weren't storing a loaded value.
1337 if (StoringOther || SI->getOperand(0) == InitVal)
1338 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
1340 // Otherwise, we are storing a previously loaded copy. To do this,
1341 // change the copy from copying the original value to just copying the
1343 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1345 // If we're already replaced the input, StoredVal will be a cast or
1346 // select instruction. If not, it will be a load of the original
1348 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1349 assert(LI->getOperand(0) == GV && "Not a copy!");
1350 // Insert a new load, to preserve the saved value.
1351 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1353 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1354 "This is not a form that we understand!");
1355 StoreVal = StoredVal->getOperand(0);
1356 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1359 new StoreInst(StoreVal, NewGV, SI);
1361 // Change the load into a load of bool then a select.
1362 LoadInst *LI = cast<LoadInst>(UI);
1363 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1366 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1368 NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1370 LI->replaceAllUsesWith(NSI);
1372 UI->eraseFromParent();
1375 GV->eraseFromParent();
1380 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1381 /// it if possible. If we make a change, return true.
1382 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1383 Module::global_iterator &GVI) {
1384 std::set<PHINode*> PHIUsers;
1386 GV->removeDeadConstantUsers();
1388 if (GV->use_empty()) {
1389 DOUT << "GLOBAL DEAD: " << *GV;
1390 GV->eraseFromParent();
1395 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1397 cerr << "Global: " << *GV;
1398 cerr << " isLoaded = " << GS.isLoaded << "\n";
1399 cerr << " StoredType = ";
1400 switch (GS.StoredType) {
1401 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1402 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1403 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1404 case GlobalStatus::isStored: cerr << "stored\n"; break;
1406 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1407 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1408 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1409 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1411 cerr << " HasMultipleAccessingFunctions = "
1412 << GS.HasMultipleAccessingFunctions << "\n";
1413 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1417 // If this is a first class global and has only one accessing function
1418 // and this function is main (which we know is not recursive we can make
1419 // this global a local variable) we replace the global with a local alloca
1420 // in this function.
1422 // NOTE: It doesn't make sense to promote non first class types since we
1423 // are just replacing static memory to stack memory.
1424 if (!GS.HasMultipleAccessingFunctions &&
1425 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1426 GV->getType()->getElementType()->isFirstClassType() &&
1427 GS.AccessingFunction->getName() == "main" &&
1428 GS.AccessingFunction->hasExternalLinkage()) {
1429 DOUT << "LOCALIZING GLOBAL: " << *GV;
1430 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1431 const Type* ElemTy = GV->getType()->getElementType();
1432 // FIXME: Pass Global's alignment when globals have alignment
1433 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1434 if (!isa<UndefValue>(GV->getInitializer()))
1435 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1437 GV->replaceAllUsesWith(Alloca);
1438 GV->eraseFromParent();
1443 // If the global is never loaded (but may be stored to), it is dead.
1446 DOUT << "GLOBAL NEVER LOADED: " << *GV;
1448 // Delete any stores we can find to the global. We may not be able to
1449 // make it completely dead though.
1450 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1452 // If the global is dead now, delete it.
1453 if (GV->use_empty()) {
1454 GV->eraseFromParent();
1460 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1461 DOUT << "MARKING CONSTANT: " << *GV;
1462 GV->setConstant(true);
1464 // Clean up any obviously simplifiable users now.
1465 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1467 // If the global is dead now, just nuke it.
1468 if (GV->use_empty()) {
1469 DOUT << " *** Marking constant allowed us to simplify "
1470 << "all users and delete global!\n";
1471 GV->eraseFromParent();
1477 } else if (!GV->getInitializer()->getType()->isFirstClassType()) {
1478 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1479 GVI = FirstNewGV; // Don't skip the newly produced globals!
1482 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1483 // If the initial value for the global was an undef value, and if only
1484 // one other value was stored into it, we can just change the
1485 // initializer to be an undef value, then delete all stores to the
1486 // global. This allows us to mark it constant.
1487 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1488 if (isa<UndefValue>(GV->getInitializer())) {
1489 // Change the initial value here.
1490 GV->setInitializer(SOVConstant);
1492 // Clean up any obviously simplifiable users now.
1493 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1495 if (GV->use_empty()) {
1496 DOUT << " *** Substituting initializer allowed us to "
1497 << "simplify all users and delete global!\n";
1498 GV->eraseFromParent();
1507 // Try to optimize globals based on the knowledge that only one value
1508 // (besides its initializer) is ever stored to the global.
1509 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1510 getAnalysis<TargetData>()))
1513 // Otherwise, if the global was not a boolean, we can shrink it to be a
1515 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1516 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1525 /// OnlyCalledDirectly - Return true if the specified function is only called
1526 /// directly. In other words, its address is never taken.
1527 static bool OnlyCalledDirectly(Function *F) {
1528 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1529 Instruction *User = dyn_cast<Instruction>(*UI);
1530 if (!User) return false;
1531 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1533 // See if the function address is passed as an argument.
1534 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1535 if (User->getOperand(i) == F) return false;
1540 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1541 /// function, changing them to FastCC.
1542 static void ChangeCalleesToFastCall(Function *F) {
1543 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1544 Instruction *User = cast<Instruction>(*UI);
1545 if (CallInst *CI = dyn_cast<CallInst>(User))
1546 CI->setCallingConv(CallingConv::Fast);
1548 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1552 bool GlobalOpt::OptimizeFunctions(Module &M) {
1553 bool Changed = false;
1554 // Optimize functions.
1555 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1557 F->removeDeadConstantUsers();
1558 if (F->use_empty() && (F->hasInternalLinkage() ||
1559 F->hasLinkOnceLinkage())) {
1560 M.getFunctionList().erase(F);
1563 } else if (F->hasInternalLinkage() &&
1564 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1565 OnlyCalledDirectly(F)) {
1566 // If this function has C calling conventions, is not a varargs
1567 // function, and is only called directly, promote it to use the Fast
1568 // calling convention.
1569 F->setCallingConv(CallingConv::Fast);
1570 ChangeCalleesToFastCall(F);
1578 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1579 bool Changed = false;
1580 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1582 GlobalVariable *GV = GVI++;
1583 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1584 GV->hasInitializer())
1585 Changed |= ProcessInternalGlobal(GV, GVI);
1590 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1591 /// initializers have an init priority of 65535.
1592 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1593 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1595 if (I->getName() == "llvm.global_ctors") {
1596 // Found it, verify it's an array of { int, void()* }.
1597 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1599 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1600 if (!STy || STy->getNumElements() != 2 ||
1601 STy->getElementType(0) != Type::Int32Ty) return 0;
1602 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1603 if (!PFTy) return 0;
1604 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1605 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1606 FTy->getNumParams() != 0)
1609 // Verify that the initializer is simple enough for us to handle.
1610 if (!I->hasInitializer()) return 0;
1611 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1613 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1614 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1615 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1618 // Must have a function or null ptr.
1619 if (!isa<Function>(CS->getOperand(1)))
1622 // Init priority must be standard.
1623 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1624 if (!CI || CI->getZExtValue() != 65535)
1635 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1636 /// return a list of the functions and null terminator as a vector.
1637 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1638 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1639 std::vector<Function*> Result;
1640 Result.reserve(CA->getNumOperands());
1641 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1642 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1643 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1648 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1649 /// specified array, returning the new global to use.
1650 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1651 const std::vector<Function*> &Ctors) {
1652 // If we made a change, reassemble the initializer list.
1653 std::vector<Constant*> CSVals;
1654 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
1655 CSVals.push_back(0);
1657 // Create the new init list.
1658 std::vector<Constant*> CAList;
1659 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1661 CSVals[1] = Ctors[i];
1663 const Type *FTy = FunctionType::get(Type::VoidTy,
1664 std::vector<const Type*>(), false);
1665 const PointerType *PFTy = PointerType::getUnqual(FTy);
1666 CSVals[1] = Constant::getNullValue(PFTy);
1667 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
1669 CAList.push_back(ConstantStruct::get(CSVals));
1672 // Create the array initializer.
1673 const Type *StructTy =
1674 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1675 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1678 // If we didn't change the number of elements, don't create a new GV.
1679 if (CA->getType() == GCL->getInitializer()->getType()) {
1680 GCL->setInitializer(CA);
1684 // Create the new global and insert it next to the existing list.
1685 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1686 GCL->getLinkage(), CA, "",
1688 GCL->isThreadLocal());
1689 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1692 // Nuke the old list, replacing any uses with the new one.
1693 if (!GCL->use_empty()) {
1695 if (V->getType() != GCL->getType())
1696 V = ConstantExpr::getBitCast(V, GCL->getType());
1697 GCL->replaceAllUsesWith(V);
1699 GCL->eraseFromParent();
1708 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1710 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1711 Constant *R = ComputedValues[V];
1712 assert(R && "Reference to an uncomputed value!");
1716 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1717 /// enough for us to understand. In particular, if it is a cast of something,
1718 /// we punt. We basically just support direct accesses to globals and GEP's of
1719 /// globals. This should be kept up to date with CommitValueTo.
1720 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1721 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1722 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1723 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1724 return !GV->isDeclaration(); // reject external globals.
1726 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1727 // Handle a constantexpr gep.
1728 if (CE->getOpcode() == Instruction::GetElementPtr &&
1729 isa<GlobalVariable>(CE->getOperand(0))) {
1730 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1731 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1732 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1733 return GV->hasInitializer() &&
1734 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1739 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1740 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1741 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1742 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1743 ConstantExpr *Addr, unsigned OpNo) {
1744 // Base case of the recursion.
1745 if (OpNo == Addr->getNumOperands()) {
1746 assert(Val->getType() == Init->getType() && "Type mismatch!");
1750 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1751 std::vector<Constant*> Elts;
1753 // Break up the constant into its elements.
1754 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1755 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1756 Elts.push_back(CS->getOperand(i));
1757 } else if (isa<ConstantAggregateZero>(Init)) {
1758 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1759 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1760 } else if (isa<UndefValue>(Init)) {
1761 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1762 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1764 assert(0 && "This code is out of sync with "
1765 " ConstantFoldLoadThroughGEPConstantExpr");
1768 // Replace the element that we are supposed to.
1769 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1770 unsigned Idx = CU->getZExtValue();
1771 assert(Idx < STy->getNumElements() && "Struct index out of range!");
1772 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1774 // Return the modified struct.
1775 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
1777 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1778 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1780 // Break up the array into elements.
1781 std::vector<Constant*> Elts;
1782 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1783 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1784 Elts.push_back(CA->getOperand(i));
1785 } else if (isa<ConstantAggregateZero>(Init)) {
1786 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1787 Elts.assign(ATy->getNumElements(), Elt);
1788 } else if (isa<UndefValue>(Init)) {
1789 Constant *Elt = UndefValue::get(ATy->getElementType());
1790 Elts.assign(ATy->getNumElements(), Elt);
1792 assert(0 && "This code is out of sync with "
1793 " ConstantFoldLoadThroughGEPConstantExpr");
1796 assert(CI->getZExtValue() < ATy->getNumElements());
1797 Elts[CI->getZExtValue()] =
1798 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
1799 return ConstantArray::get(ATy, Elts);
1803 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1804 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1805 static void CommitValueTo(Constant *Val, Constant *Addr) {
1806 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1807 assert(GV->hasInitializer());
1808 GV->setInitializer(Val);
1812 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1813 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1815 Constant *Init = GV->getInitializer();
1816 Init = EvaluateStoreInto(Init, Val, CE, 2);
1817 GV->setInitializer(Init);
1820 /// ComputeLoadResult - Return the value that would be computed by a load from
1821 /// P after the stores reflected by 'memory' have been performed. If we can't
1822 /// decide, return null.
1823 static Constant *ComputeLoadResult(Constant *P,
1824 const std::map<Constant*, Constant*> &Memory) {
1825 // If this memory location has been recently stored, use the stored value: it
1826 // is the most up-to-date.
1827 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1828 if (I != Memory.end()) return I->second;
1831 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1832 if (GV->hasInitializer())
1833 return GV->getInitializer();
1837 // Handle a constantexpr getelementptr.
1838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1839 if (CE->getOpcode() == Instruction::GetElementPtr &&
1840 isa<GlobalVariable>(CE->getOperand(0))) {
1841 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1842 if (GV->hasInitializer())
1843 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1846 return 0; // don't know how to evaluate.
1849 /// EvaluateFunction - Evaluate a call to function F, returning true if
1850 /// successful, false if we can't evaluate it. ActualArgs contains the formal
1851 /// arguments for the function.
1852 static bool EvaluateFunction(Function *F, Constant *&RetVal,
1853 const std::vector<Constant*> &ActualArgs,
1854 std::vector<Function*> &CallStack,
1855 std::map<Constant*, Constant*> &MutatedMemory,
1856 std::vector<GlobalVariable*> &AllocaTmps) {
1857 // Check to see if this function is already executing (recursion). If so,
1858 // bail out. TODO: we might want to accept limited recursion.
1859 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1862 CallStack.push_back(F);
1864 /// Values - As we compute SSA register values, we store their contents here.
1865 std::map<Value*, Constant*> Values;
1867 // Initialize arguments to the incoming values specified.
1869 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1871 Values[AI] = ActualArgs[ArgNo];
1873 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1874 /// we can only evaluate any one basic block at most once. This set keeps
1875 /// track of what we have executed so we can detect recursive cases etc.
1876 std::set<BasicBlock*> ExecutedBlocks;
1878 // CurInst - The current instruction we're evaluating.
1879 BasicBlock::iterator CurInst = F->begin()->begin();
1881 // This is the main evaluation loop.
1883 Constant *InstResult = 0;
1885 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1886 if (SI->isVolatile()) return false; // no volatile accesses.
1887 Constant *Ptr = getVal(Values, SI->getOperand(1));
1888 if (!isSimpleEnoughPointerToCommit(Ptr))
1889 // If this is too complex for us to commit, reject it.
1891 Constant *Val = getVal(Values, SI->getOperand(0));
1892 MutatedMemory[Ptr] = Val;
1893 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1894 InstResult = ConstantExpr::get(BO->getOpcode(),
1895 getVal(Values, BO->getOperand(0)),
1896 getVal(Values, BO->getOperand(1)));
1897 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1898 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1899 getVal(Values, CI->getOperand(0)),
1900 getVal(Values, CI->getOperand(1)));
1901 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1902 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1903 getVal(Values, CI->getOperand(0)),
1905 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1906 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1907 getVal(Values, SI->getOperand(1)),
1908 getVal(Values, SI->getOperand(2)));
1909 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1910 Constant *P = getVal(Values, GEP->getOperand(0));
1911 SmallVector<Constant*, 8> GEPOps;
1912 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1913 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1914 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
1915 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1916 if (LI->isVolatile()) return false; // no volatile accesses.
1917 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1919 if (InstResult == 0) return false; // Could not evaluate load.
1920 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
1921 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
1922 const Type *Ty = AI->getType()->getElementType();
1923 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1924 GlobalValue::InternalLinkage,
1925 UndefValue::get(Ty),
1927 InstResult = AllocaTmps.back();
1928 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1929 // Cannot handle inline asm.
1930 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1932 // Resolve function pointers.
1933 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1934 if (!Callee) return false; // Cannot resolve.
1936 std::vector<Constant*> Formals;
1937 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1938 Formals.push_back(getVal(Values, CI->getOperand(i)));
1940 if (Callee->isDeclaration()) {
1941 // If this is a function we can constant fold, do it.
1942 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1949 if (Callee->getFunctionType()->isVarArg())
1954 // Execute the call, if successful, use the return value.
1955 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1956 MutatedMemory, AllocaTmps))
1958 InstResult = RetVal;
1960 } else if (isa<TerminatorInst>(CurInst)) {
1961 BasicBlock *NewBB = 0;
1962 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1963 if (BI->isUnconditional()) {
1964 NewBB = BI->getSuccessor(0);
1967 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
1968 if (!Cond) return false; // Cannot determine.
1970 NewBB = BI->getSuccessor(!Cond->getZExtValue());
1972 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1974 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1975 if (!Val) return false; // Cannot determine.
1976 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1977 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1978 if (RI->getNumOperands())
1979 RetVal = getVal(Values, RI->getOperand(0));
1981 CallStack.pop_back(); // return from fn.
1982 return true; // We succeeded at evaluating this ctor!
1984 // invoke, unwind, unreachable.
1985 return false; // Cannot handle this terminator.
1988 // Okay, we succeeded in evaluating this control flow. See if we have
1989 // executed the new block before. If so, we have a looping function,
1990 // which we cannot evaluate in reasonable time.
1991 if (!ExecutedBlocks.insert(NewBB).second)
1992 return false; // looped!
1994 // Okay, we have never been in this block before. Check to see if there
1995 // are any PHI nodes. If so, evaluate them with information about where
1997 BasicBlock *OldBB = CurInst->getParent();
1998 CurInst = NewBB->begin();
2000 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2001 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2003 // Do NOT increment CurInst. We know that the terminator had no value.
2006 // Did not know how to evaluate this!
2010 if (!CurInst->use_empty())
2011 Values[CurInst] = InstResult;
2013 // Advance program counter.
2018 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2019 /// we can. Return true if we can, false otherwise.
2020 static bool EvaluateStaticConstructor(Function *F) {
2021 /// MutatedMemory - For each store we execute, we update this map. Loads
2022 /// check this to get the most up-to-date value. If evaluation is successful,
2023 /// this state is committed to the process.
2024 std::map<Constant*, Constant*> MutatedMemory;
2026 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2027 /// to represent its body. This vector is needed so we can delete the
2028 /// temporary globals when we are done.
2029 std::vector<GlobalVariable*> AllocaTmps;
2031 /// CallStack - This is used to detect recursion. In pathological situations
2032 /// we could hit exponential behavior, but at least there is nothing
2034 std::vector<Function*> CallStack;
2036 // Call the function.
2037 Constant *RetValDummy;
2038 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2039 CallStack, MutatedMemory, AllocaTmps);
2041 // We succeeded at evaluation: commit the result.
2042 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2043 << F->getName() << "' to " << MutatedMemory.size()
2045 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2046 E = MutatedMemory.end(); I != E; ++I)
2047 CommitValueTo(I->second, I->first);
2050 // At this point, we are done interpreting. If we created any 'alloca'
2051 // temporaries, release them now.
2052 while (!AllocaTmps.empty()) {
2053 GlobalVariable *Tmp = AllocaTmps.back();
2054 AllocaTmps.pop_back();
2056 // If there are still users of the alloca, the program is doing something
2057 // silly, e.g. storing the address of the alloca somewhere and using it
2058 // later. Since this is undefined, we'll just make it be null.
2059 if (!Tmp->use_empty())
2060 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2069 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2070 /// Return true if anything changed.
2071 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2072 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2073 bool MadeChange = false;
2074 if (Ctors.empty()) return false;
2076 // Loop over global ctors, optimizing them when we can.
2077 for (unsigned i = 0; i != Ctors.size(); ++i) {
2078 Function *F = Ctors[i];
2079 // Found a null terminator in the middle of the list, prune off the rest of
2082 if (i != Ctors.size()-1) {
2089 // We cannot simplify external ctor functions.
2090 if (F->empty()) continue;
2092 // If we can evaluate the ctor at compile time, do.
2093 if (EvaluateStaticConstructor(F)) {
2094 Ctors.erase(Ctors.begin()+i);
2097 ++NumCtorsEvaluated;
2102 if (!MadeChange) return false;
2104 GCL = InstallGlobalCtors(GCL, Ctors);
2109 bool GlobalOpt::runOnModule(Module &M) {
2110 bool Changed = false;
2112 // Try to find the llvm.globalctors list.
2113 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2115 bool LocalChange = true;
2116 while (LocalChange) {
2117 LocalChange = false;
2119 // Delete functions that are trivially dead, ccc -> fastcc
2120 LocalChange |= OptimizeFunctions(M);
2122 // Optimize global_ctors list.
2124 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2126 // Optimize non-address-taken globals.
2127 LocalChange |= OptimizeGlobalVars(M);
2128 Changed |= LocalChange;
2131 // TODO: Move all global ctors functions to the end of the module for code