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/Analysis/MemoryBuiltins.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Support/CallSite.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
42 STATISTIC(NumMarked , "Number of globals marked constant");
43 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
44 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
45 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46 STATISTIC(NumDeleted , "Number of globals deleted");
47 STATISTIC(NumFnDeleted , "Number of functions deleted");
48 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
49 STATISTIC(NumLocalized , "Number of globals localized");
50 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
51 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
52 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
53 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
54 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
58 struct GlobalOpt : public ModulePass {
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 static char ID; // Pass identification, replacement for typeid
62 GlobalOpt() : ModulePass(&ID) {}
64 bool runOnModule(Module &M);
67 GlobalVariable *FindGlobalCtors(Module &M);
68 bool OptimizeFunctions(Module &M);
69 bool OptimizeGlobalVars(Module &M);
70 bool OptimizeGlobalAliases(Module &M);
71 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
72 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
76 char GlobalOpt::ID = 0;
77 static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
79 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
83 /// GlobalStatus - As we analyze each global, keep track of some information
84 /// about it. If we find out that the address of the global is taken, none of
85 /// this info will be accurate.
87 /// isLoaded - True if the global is ever loaded. If the global isn't ever
88 /// loaded it can be deleted.
91 /// StoredType - Keep track of what stores to the global look like.
94 /// NotStored - There is no store to this global. It can thus be marked
98 /// isInitializerStored - This global is stored to, but the only thing
99 /// stored is the constant it was initialized with. This is only tracked
100 /// for scalar globals.
103 /// isStoredOnce - This global is stored to, but only its initializer and
104 /// one other value is ever stored to it. If this global isStoredOnce, we
105 /// track the value stored to it in StoredOnceValue below. This is only
106 /// tracked for scalar globals.
109 /// isStored - This global is stored to by multiple values or something else
110 /// that we cannot track.
114 /// StoredOnceValue - If only one value (besides the initializer constant) is
115 /// ever stored to this global, keep track of what value it is.
116 Value *StoredOnceValue;
118 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
119 /// null/false. When the first accessing function is noticed, it is recorded.
120 /// When a second different accessing function is noticed,
121 /// HasMultipleAccessingFunctions is set to true.
122 const Function *AccessingFunction;
123 bool HasMultipleAccessingFunctions;
125 /// HasNonInstructionUser - Set to true if this global has a user that is not
126 /// an instruction (e.g. a constant expr or GV initializer).
127 bool HasNonInstructionUser;
129 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
132 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
133 AccessingFunction(0), HasMultipleAccessingFunctions(false),
134 HasNonInstructionUser(false), HasPHIUser(false) {}
139 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
140 // by constants itself. Note that constants cannot be cyclic, so this test is
141 // pretty easy to implement recursively.
143 static bool SafeToDestroyConstant(const Constant *C) {
144 if (isa<GlobalValue>(C)) return false;
146 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
147 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
148 if (!SafeToDestroyConstant(CU)) return false;
155 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
156 /// structure. If the global has its address taken, return true to indicate we
157 /// can't do anything with it.
159 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
160 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
161 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
162 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
163 GS.HasNonInstructionUser = true;
165 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
167 } else if (const Instruction *I = dyn_cast<Instruction>(*UI)) {
168 if (!GS.HasMultipleAccessingFunctions) {
169 const Function *F = I->getParent()->getParent();
170 if (GS.AccessingFunction == 0)
171 GS.AccessingFunction = F;
172 else if (GS.AccessingFunction != F)
173 GS.HasMultipleAccessingFunctions = true;
175 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
177 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
178 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
179 // Don't allow a store OF the address, only stores TO the address.
180 if (SI->getOperand(0) == V) return true;
182 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
184 // If this is a direct store to the global (i.e., the global is a scalar
185 // value, not an aggregate), keep more specific information about
187 if (GS.StoredType != GlobalStatus::isStored) {
188 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
189 Value *StoredVal = SI->getOperand(0);
190 if (StoredVal == GV->getInitializer()) {
191 if (GS.StoredType < GlobalStatus::isInitializerStored)
192 GS.StoredType = GlobalStatus::isInitializerStored;
193 } else if (isa<LoadInst>(StoredVal) &&
194 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
195 if (GS.StoredType < GlobalStatus::isInitializerStored)
196 GS.StoredType = GlobalStatus::isInitializerStored;
197 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
198 GS.StoredType = GlobalStatus::isStoredOnce;
199 GS.StoredOnceValue = StoredVal;
200 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
201 GS.StoredOnceValue == StoredVal) {
204 GS.StoredType = GlobalStatus::isStored;
207 GS.StoredType = GlobalStatus::isStored;
210 } else if (isa<GetElementPtrInst>(I)) {
211 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
212 } else if (isa<SelectInst>(I)) {
213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
214 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
215 // PHI nodes we can check just like select or GEP instructions, but we
216 // have to be careful about infinite recursion.
217 if (PHIUsers.insert(PN)) // Not already visited.
218 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
219 GS.HasPHIUser = true;
220 } else if (isa<CmpInst>(I)) {
221 } else if (isa<MemTransferInst>(I)) {
222 if (I->getOperand(1) == V)
223 GS.StoredType = GlobalStatus::isStored;
224 if (I->getOperand(2) == V)
226 } else if (isa<MemSetInst>(I)) {
227 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
228 GS.StoredType = GlobalStatus::isStored;
230 return true; // Any other non-load instruction might take address!
232 } else if (const Constant *C = dyn_cast<Constant>(*UI)) {
233 GS.HasNonInstructionUser = true;
234 // We might have a dead and dangling constant hanging off of here.
235 if (!SafeToDestroyConstant(C))
238 GS.HasNonInstructionUser = true;
239 // Otherwise must be some other user.
246 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
247 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
249 unsigned IdxV = CI->getZExtValue();
251 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
252 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
253 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
254 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
255 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
256 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
257 } else if (isa<ConstantAggregateZero>(Agg)) {
258 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
259 if (IdxV < STy->getNumElements())
260 return Constant::getNullValue(STy->getElementType(IdxV));
261 } else if (const SequentialType *STy =
262 dyn_cast<SequentialType>(Agg->getType())) {
263 return Constant::getNullValue(STy->getElementType());
265 } else if (isa<UndefValue>(Agg)) {
266 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
267 if (IdxV < STy->getNumElements())
268 return UndefValue::get(STy->getElementType(IdxV));
269 } else if (const SequentialType *STy =
270 dyn_cast<SequentialType>(Agg->getType())) {
271 return UndefValue::get(STy->getElementType());
278 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
279 /// users of the global, cleaning up the obvious ones. This is largely just a
280 /// quick scan over the use list to clean up the easy and obvious cruft. This
281 /// returns true if it made a change.
282 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
283 bool Changed = false;
284 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
287 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
289 // Replace the load with the initializer.
290 LI->replaceAllUsesWith(Init);
291 LI->eraseFromParent();
294 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
295 // Store must be unreachable or storing Init into the global.
296 SI->eraseFromParent();
298 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
299 if (CE->getOpcode() == Instruction::GetElementPtr) {
300 Constant *SubInit = 0;
302 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
303 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
304 } else if (CE->getOpcode() == Instruction::BitCast &&
305 CE->getType()->isPointerTy()) {
306 // Pointer cast, delete any stores and memsets to the global.
307 Changed |= CleanupConstantGlobalUsers(CE, 0);
310 if (CE->use_empty()) {
311 CE->destroyConstant();
314 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
315 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
316 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
317 // and will invalidate our notion of what Init is.
318 Constant *SubInit = 0;
319 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
321 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
322 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
323 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
325 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
327 if (GEP->use_empty()) {
328 GEP->eraseFromParent();
331 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
332 if (MI->getRawDest() == V) {
333 MI->eraseFromParent();
337 } else if (Constant *C = dyn_cast<Constant>(U)) {
338 // If we have a chain of dead constantexprs or other things dangling from
339 // us, and if they are all dead, nuke them without remorse.
340 if (SafeToDestroyConstant(C)) {
341 C->destroyConstant();
342 // This could have invalidated UI, start over from scratch.
343 CleanupConstantGlobalUsers(V, Init);
351 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
352 /// user of a derived expression from a global that we want to SROA.
353 static bool isSafeSROAElementUse(Value *V) {
354 // We might have a dead and dangling constant hanging off of here.
355 if (Constant *C = dyn_cast<Constant>(V))
356 return SafeToDestroyConstant(C);
358 Instruction *I = dyn_cast<Instruction>(V);
359 if (!I) return false;
362 if (isa<LoadInst>(I)) return true;
364 // Stores *to* the pointer are ok.
365 if (StoreInst *SI = dyn_cast<StoreInst>(I))
366 return SI->getOperand(0) != V;
368 // Otherwise, it must be a GEP.
369 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
370 if (GEPI == 0) return false;
372 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
373 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
376 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
378 if (!isSafeSROAElementUse(*I))
384 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
385 /// Look at it and its uses and decide whether it is safe to SROA this global.
387 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
388 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
389 if (!isa<GetElementPtrInst>(U) &&
390 (!isa<ConstantExpr>(U) ||
391 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
394 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
395 // don't like < 3 operand CE's, and we don't like non-constant integer
396 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
398 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
399 !cast<Constant>(U->getOperand(1))->isNullValue() ||
400 !isa<ConstantInt>(U->getOperand(2)))
403 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
404 ++GEPI; // Skip over the pointer index.
406 // If this is a use of an array allocation, do a bit more checking for sanity.
407 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
408 uint64_t NumElements = AT->getNumElements();
409 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
411 // Check to make sure that index falls within the array. If not,
412 // something funny is going on, so we won't do the optimization.
414 if (Idx->getZExtValue() >= NumElements)
417 // We cannot scalar repl this level of the array unless any array
418 // sub-indices are in-range constants. In particular, consider:
419 // A[0][i]. We cannot know that the user isn't doing invalid things like
420 // allowing i to index an out-of-range subscript that accesses A[1].
422 // Scalar replacing *just* the outer index of the array is probably not
423 // going to be a win anyway, so just give up.
424 for (++GEPI; // Skip array index.
427 uint64_t NumElements;
428 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
429 NumElements = SubArrayTy->getNumElements();
430 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
431 NumElements = SubVectorTy->getNumElements();
433 assert((*GEPI)->isStructTy() &&
434 "Indexed GEP type is not array, vector, or struct!");
438 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
439 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
444 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
445 if (!isSafeSROAElementUse(*I))
450 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
451 /// is safe for us to perform this transformation.
453 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
454 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
456 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
463 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
464 /// variable. This opens the door for other optimizations by exposing the
465 /// behavior of the program in a more fine-grained way. We have determined that
466 /// this transformation is safe already. We return the first global variable we
467 /// insert so that the caller can reprocess it.
468 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
469 // Make sure this global only has simple uses that we can SRA.
470 if (!GlobalUsersSafeToSRA(GV))
473 assert(GV->hasLocalLinkage() && !GV->isConstant());
474 Constant *Init = GV->getInitializer();
475 const Type *Ty = Init->getType();
477 std::vector<GlobalVariable*> NewGlobals;
478 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
480 // Get the alignment of the global, either explicit or target-specific.
481 unsigned StartAlignment = GV->getAlignment();
482 if (StartAlignment == 0)
483 StartAlignment = TD.getABITypeAlignment(GV->getType());
485 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
486 NewGlobals.reserve(STy->getNumElements());
487 const StructLayout &Layout = *TD.getStructLayout(STy);
488 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489 Constant *In = getAggregateConstantElement(Init,
490 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
491 assert(In && "Couldn't get element of initializer?");
492 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
493 GlobalVariable::InternalLinkage,
494 In, GV->getName()+"."+Twine(i),
496 GV->getType()->getAddressSpace());
497 Globals.insert(GV, NGV);
498 NewGlobals.push_back(NGV);
500 // Calculate the known alignment of the field. If the original aggregate
501 // had 256 byte alignment for example, something might depend on that:
502 // propagate info to each field.
503 uint64_t FieldOffset = Layout.getElementOffset(i);
504 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
505 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
506 NGV->setAlignment(NewAlign);
508 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
509 unsigned NumElements = 0;
510 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
511 NumElements = ATy->getNumElements();
513 NumElements = cast<VectorType>(STy)->getNumElements();
515 if (NumElements > 16 && GV->hasNUsesOrMore(16))
516 return 0; // It's not worth it.
517 NewGlobals.reserve(NumElements);
519 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
520 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
521 for (unsigned i = 0, e = NumElements; i != e; ++i) {
522 Constant *In = getAggregateConstantElement(Init,
523 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
524 assert(In && "Couldn't get element of initializer?");
526 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
527 GlobalVariable::InternalLinkage,
528 In, GV->getName()+"."+Twine(i),
530 GV->getType()->getAddressSpace());
531 Globals.insert(GV, NGV);
532 NewGlobals.push_back(NGV);
534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538 if (NewAlign > EltAlign)
539 NGV->setAlignment(NewAlign);
543 if (NewGlobals.empty())
546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
550 // Loop over all of the uses of the global, replacing the constantexpr geps,
551 // with smaller constantexpr geps or direct references.
552 while (!GV->use_empty()) {
553 User *GEP = GV->use_back();
554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
558 // Ignore the 1th operand, which has to be zero or else the program is quite
559 // broken (undefined). Get the 2nd operand, which is the structure or array
561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
564 Value *NewPtr = NewGlobals[Val];
566 // Form a shorter GEP if needed.
567 if (GEP->getNumOperands() > 3) {
568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
569 SmallVector<Constant*, 8> Idxs;
570 Idxs.push_back(NullInt);
571 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
572 Idxs.push_back(CE->getOperand(i));
573 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
574 &Idxs[0], Idxs.size());
576 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
577 SmallVector<Value*, 8> Idxs;
578 Idxs.push_back(NullInt);
579 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
580 Idxs.push_back(GEPI->getOperand(i));
581 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
582 GEPI->getName()+"."+Twine(Val),GEPI);
585 GEP->replaceAllUsesWith(NewPtr);
587 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
588 GEPI->eraseFromParent();
590 cast<ConstantExpr>(GEP)->destroyConstant();
593 // Delete the old global, now that it is dead.
597 // Loop over the new globals array deleting any globals that are obviously
598 // dead. This can arise due to scalarization of a structure or an array that
599 // has elements that are dead.
600 unsigned FirstGlobal = 0;
601 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
602 if (NewGlobals[i]->use_empty()) {
603 Globals.erase(NewGlobals[i]);
604 if (FirstGlobal == i) ++FirstGlobal;
607 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
610 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
611 /// value will trap if the value is dynamically null. PHIs keeps track of any
612 /// phi nodes we've seen to avoid reprocessing them.
613 static bool AllUsesOfValueWillTrapIfNull(Value *V,
614 SmallPtrSet<PHINode*, 8> &PHIs) {
615 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
616 if (isa<LoadInst>(*UI)) {
618 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
619 if (SI->getOperand(0) == V) {
620 //cerr << "NONTRAPPING USE: " << **UI;
621 return false; // Storing the value.
623 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
624 if (CI->getCalledValue() != V) {
625 //cerr << "NONTRAPPING USE: " << **UI;
626 return false; // Not calling the ptr
628 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
629 if (II->getCalledValue() != V) {
630 //cerr << "NONTRAPPING USE: " << **UI;
631 return false; // Not calling the ptr
633 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
634 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
635 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
636 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
637 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
638 // If we've already seen this phi node, ignore it, it has already been
640 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
642 } else if (isa<ICmpInst>(*UI) &&
643 isa<ConstantPointerNull>(UI->getOperand(1))) {
644 // Ignore icmp X, null
646 //cerr << "NONTRAPPING USE: " << **UI;
652 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
653 /// from GV will trap if the loaded value is null. Note that this also permits
654 /// comparisons of the loaded value against null, as a special case.
655 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
656 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
657 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
658 SmallPtrSet<PHINode*, 8> PHIs;
659 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
661 } else if (isa<StoreInst>(*UI)) {
662 // Ignore stores to the global.
664 // We don't know or understand this user, bail out.
665 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
672 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
673 bool Changed = false;
674 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
675 Instruction *I = cast<Instruction>(*UI++);
676 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
677 LI->setOperand(0, NewV);
679 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
680 if (SI->getOperand(1) == V) {
681 SI->setOperand(1, NewV);
684 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
685 if (I->getOperand(0) == V) {
686 // Calling through the pointer! Turn into a direct call, but be careful
687 // that the pointer is not also being passed as an argument.
688 I->setOperand(0, NewV);
690 bool PassedAsArg = false;
691 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
692 if (I->getOperand(i) == V) {
694 I->setOperand(i, NewV);
698 // Being passed as an argument also. Be careful to not invalidate UI!
702 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
703 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
704 ConstantExpr::getCast(CI->getOpcode(),
705 NewV, CI->getType()));
706 if (CI->use_empty()) {
708 CI->eraseFromParent();
710 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
711 // Should handle GEP here.
712 SmallVector<Constant*, 8> Idxs;
713 Idxs.reserve(GEPI->getNumOperands()-1);
714 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
716 if (Constant *C = dyn_cast<Constant>(*i))
720 if (Idxs.size() == GEPI->getNumOperands()-1)
721 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
722 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
724 if (GEPI->use_empty()) {
726 GEPI->eraseFromParent();
735 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
736 /// value stored into it. If there are uses of the loaded value that would trap
737 /// if the loaded value is dynamically null, then we know that they cannot be
738 /// reachable with a null optimize away the load.
739 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
740 bool Changed = false;
742 // Keep track of whether we are able to remove all the uses of the global
743 // other than the store that defines it.
744 bool AllNonStoreUsesGone = true;
746 // Replace all uses of loads with uses of uses of the stored value.
747 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
748 User *GlobalUser = *GUI++;
749 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
750 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
751 // If we were able to delete all uses of the loads
752 if (LI->use_empty()) {
753 LI->eraseFromParent();
756 AllNonStoreUsesGone = false;
758 } else if (isa<StoreInst>(GlobalUser)) {
759 // Ignore the store that stores "LV" to the global.
760 assert(GlobalUser->getOperand(1) == GV &&
761 "Must be storing *to* the global");
763 AllNonStoreUsesGone = false;
765 // If we get here we could have other crazy uses that are transitively
767 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
768 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
773 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
777 // If we nuked all of the loads, then none of the stores are needed either,
778 // nor is the global.
779 if (AllNonStoreUsesGone) {
780 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
781 CleanupConstantGlobalUsers(GV, 0);
782 if (GV->use_empty()) {
783 GV->eraseFromParent();
791 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
792 /// instructions that are foldable.
793 static void ConstantPropUsersOf(Value *V) {
794 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
795 if (Instruction *I = dyn_cast<Instruction>(*UI++))
796 if (Constant *NewC = ConstantFoldInstruction(I)) {
797 I->replaceAllUsesWith(NewC);
799 // Advance UI to the next non-I use to avoid invalidating it!
800 // Instructions could multiply use V.
801 while (UI != E && *UI == I)
803 I->eraseFromParent();
807 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
808 /// variable, and transforms the program as if it always contained the result of
809 /// the specified malloc. Because it is always the result of the specified
810 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
811 /// malloc into a global, and any loads of GV as uses of the new global.
812 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
815 ConstantInt *NElements,
817 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
819 const Type *GlobalType;
820 if (NElements->getZExtValue() == 1)
821 GlobalType = AllocTy;
823 // If we have an array allocation, the global variable is of an array.
824 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
826 // Create the new global variable. The contents of the malloc'd memory is
827 // undefined, so initialize with an undef value.
828 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
830 GlobalValue::InternalLinkage,
831 UndefValue::get(GlobalType),
832 GV->getName()+".body",
834 GV->isThreadLocal());
836 // If there are bitcast users of the malloc (which is typical, usually we have
837 // a malloc + bitcast) then replace them with uses of the new global. Update
838 // other users to use the global as well.
839 BitCastInst *TheBC = 0;
840 while (!CI->use_empty()) {
841 Instruction *User = cast<Instruction>(CI->use_back());
842 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
843 if (BCI->getType() == NewGV->getType()) {
844 BCI->replaceAllUsesWith(NewGV);
845 BCI->eraseFromParent();
847 BCI->setOperand(0, NewGV);
851 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
852 User->replaceUsesOfWith(CI, TheBC);
856 Constant *RepValue = NewGV;
857 if (NewGV->getType() != GV->getType()->getElementType())
858 RepValue = ConstantExpr::getBitCast(RepValue,
859 GV->getType()->getElementType());
861 // If there is a comparison against null, we will insert a global bool to
862 // keep track of whether the global was initialized yet or not.
863 GlobalVariable *InitBool =
864 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
865 GlobalValue::InternalLinkage,
866 ConstantInt::getFalse(GV->getContext()),
867 GV->getName()+".init", GV->isThreadLocal());
868 bool InitBoolUsed = false;
870 // Loop over all uses of GV, processing them in turn.
871 while (!GV->use_empty()) {
872 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
873 // The global is initialized when the store to it occurs.
874 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
875 SI->eraseFromParent();
879 LoadInst *LI = cast<LoadInst>(GV->use_back());
880 while (!LI->use_empty()) {
881 Use &LoadUse = LI->use_begin().getUse();
882 if (!isa<ICmpInst>(LoadUse.getUser())) {
887 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
888 // Replace the cmp X, 0 with a use of the bool value.
889 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
891 switch (ICI->getPredicate()) {
892 default: llvm_unreachable("Unknown ICmp Predicate!");
893 case ICmpInst::ICMP_ULT:
894 case ICmpInst::ICMP_SLT: // X < null -> always false
895 LV = ConstantInt::getFalse(GV->getContext());
897 case ICmpInst::ICMP_ULE:
898 case ICmpInst::ICMP_SLE:
899 case ICmpInst::ICMP_EQ:
900 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
902 case ICmpInst::ICMP_NE:
903 case ICmpInst::ICMP_UGE:
904 case ICmpInst::ICMP_SGE:
905 case ICmpInst::ICMP_UGT:
906 case ICmpInst::ICMP_SGT:
909 ICI->replaceAllUsesWith(LV);
910 ICI->eraseFromParent();
912 LI->eraseFromParent();
915 // If the initialization boolean was used, insert it, otherwise delete it.
917 while (!InitBool->use_empty()) // Delete initializations
918 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
921 GV->getParent()->getGlobalList().insert(GV, InitBool);
923 // Now the GV is dead, nuke it and the malloc..
924 GV->eraseFromParent();
925 CI->eraseFromParent();
927 // To further other optimizations, loop over all users of NewGV and try to
928 // constant prop them. This will promote GEP instructions with constant
929 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
930 ConstantPropUsersOf(NewGV);
931 if (RepValue != NewGV)
932 ConstantPropUsersOf(RepValue);
937 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
938 /// to make sure that there are no complex uses of V. We permit simple things
939 /// like dereferencing the pointer, but not storing through the address, unless
940 /// it is to the specified global.
941 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
943 SmallPtrSet<PHINode*, 8> &PHIs) {
944 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
945 Instruction *Inst = cast<Instruction>(*UI);
947 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
948 continue; // Fine, ignore.
951 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
952 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
953 return false; // Storing the pointer itself... bad.
954 continue; // Otherwise, storing through it, or storing into GV... fine.
957 if (isa<GetElementPtrInst>(Inst)) {
958 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
963 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
964 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
967 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
972 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
973 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
983 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
984 /// somewhere. Transform all uses of the allocation into loads from the
985 /// global and uses of the resultant pointer. Further, delete the store into
986 /// GV. This assumes that these value pass the
987 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
988 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
989 GlobalVariable *GV) {
990 while (!Alloc->use_empty()) {
991 Instruction *U = cast<Instruction>(*Alloc->use_begin());
992 Instruction *InsertPt = U;
993 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
994 // If this is the store of the allocation into the global, remove it.
995 if (SI->getOperand(1) == GV) {
996 SI->eraseFromParent();
999 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1000 // Insert the load in the corresponding predecessor, not right before the
1002 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1003 } else if (isa<BitCastInst>(U)) {
1004 // Must be bitcast between the malloc and store to initialize the global.
1005 ReplaceUsesOfMallocWithGlobal(U, GV);
1006 U->eraseFromParent();
1008 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1009 // If this is a "GEP bitcast" and the user is a store to the global, then
1010 // just process it as a bitcast.
1011 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1012 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1013 if (SI->getOperand(1) == GV) {
1014 // Must be bitcast GEP between the malloc and store to initialize
1016 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1017 GEPI->eraseFromParent();
1022 // Insert a load from the global, and use it instead of the malloc.
1023 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1024 U->replaceUsesOfWith(Alloc, NL);
1028 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1029 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1030 /// that index through the array and struct field, icmps of null, and PHIs.
1031 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1032 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1033 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1034 // We permit two users of the load: setcc comparing against the null
1035 // pointer, and a getelementptr of a specific form.
1036 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1037 const Instruction *User = cast<Instruction>(*UI);
1039 // Comparison against null is ok.
1040 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1041 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1046 // getelementptr is also ok, but only a simple form.
1047 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1048 // Must index into the array and into the struct.
1049 if (GEPI->getNumOperands() < 3)
1052 // Otherwise the GEP is ok.
1056 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1057 if (!LoadUsingPHIsPerLoad.insert(PN))
1058 // This means some phi nodes are dependent on each other.
1059 // Avoid infinite looping!
1061 if (!LoadUsingPHIs.insert(PN))
1062 // If we have already analyzed this PHI, then it is safe.
1065 // Make sure all uses of the PHI are simple enough to transform.
1066 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1067 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1073 // Otherwise we don't know what this is, not ok.
1081 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1082 /// GV are simple enough to perform HeapSRA, return true.
1083 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1084 Instruction *StoredVal) {
1085 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1086 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1087 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1089 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1090 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1091 LoadUsingPHIsPerLoad))
1093 LoadUsingPHIsPerLoad.clear();
1096 // If we reach here, we know that all uses of the loads and transitive uses
1097 // (through PHI nodes) are simple enough to transform. However, we don't know
1098 // that all inputs the to the PHI nodes are in the same equivalence sets.
1099 // Check to verify that all operands of the PHIs are either PHIS that can be
1100 // transformed, loads from GV, or MI itself.
1101 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin(),
1102 E = LoadUsingPHIs.end(); I != E; ++I) {
1103 const PHINode *PN = *I;
1104 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1105 Value *InVal = PN->getIncomingValue(op);
1107 // PHI of the stored value itself is ok.
1108 if (InVal == StoredVal) continue;
1110 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1111 // One of the PHIs in our set is (optimistically) ok.
1112 if (LoadUsingPHIs.count(InPN))
1117 // Load from GV is ok.
1118 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1119 if (LI->getOperand(0) == GV)
1124 // Anything else is rejected.
1132 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1133 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1134 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1135 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1137 if (FieldNo >= FieldVals.size())
1138 FieldVals.resize(FieldNo+1);
1140 // If we already have this value, just reuse the previously scalarized
1142 if (Value *FieldVal = FieldVals[FieldNo])
1145 // Depending on what instruction this is, we have several cases.
1147 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1148 // This is a scalarized version of the load from the global. Just create
1149 // a new Load of the scalarized global.
1150 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1151 InsertedScalarizedValues,
1153 LI->getName()+".f"+Twine(FieldNo), LI);
1154 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1155 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1157 const StructType *ST =
1158 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1161 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1162 PN->getName()+".f"+Twine(FieldNo), PN);
1163 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1165 llvm_unreachable("Unknown usable value");
1169 return FieldVals[FieldNo] = Result;
1172 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1173 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1174 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1175 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1176 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1177 // If this is a comparison against null, handle it.
1178 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1179 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1180 // If we have a setcc of the loaded pointer, we can use a setcc of any
1182 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1183 InsertedScalarizedValues, PHIsToRewrite);
1185 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1186 Constant::getNullValue(NPtr->getType()),
1188 SCI->replaceAllUsesWith(New);
1189 SCI->eraseFromParent();
1193 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1194 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1195 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1196 && "Unexpected GEPI!");
1198 // Load the pointer for this field.
1199 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1200 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1201 InsertedScalarizedValues, PHIsToRewrite);
1203 // Create the new GEP idx vector.
1204 SmallVector<Value*, 8> GEPIdx;
1205 GEPIdx.push_back(GEPI->getOperand(1));
1206 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1208 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1209 GEPIdx.begin(), GEPIdx.end(),
1210 GEPI->getName(), GEPI);
1211 GEPI->replaceAllUsesWith(NGEPI);
1212 GEPI->eraseFromParent();
1216 // Recursively transform the users of PHI nodes. This will lazily create the
1217 // PHIs that are needed for individual elements. Keep track of what PHIs we
1218 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1219 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1220 // already been seen first by another load, so its uses have already been
1222 PHINode *PN = cast<PHINode>(LoadUser);
1224 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1225 tie(InsertPos, Inserted) =
1226 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1227 if (!Inserted) return;
1229 // If this is the first time we've seen this PHI, recursively process all
1231 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1232 Instruction *User = cast<Instruction>(*UI++);
1233 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1237 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1238 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1239 /// use FieldGlobals instead. All uses of loaded values satisfy
1240 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1241 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1242 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1243 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1244 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1246 Instruction *User = cast<Instruction>(*UI++);
1247 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1250 if (Load->use_empty()) {
1251 Load->eraseFromParent();
1252 InsertedScalarizedValues.erase(Load);
1256 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1257 /// it up into multiple allocations of arrays of the fields.
1258 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1259 Value* NElems, TargetData *TD) {
1260 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1261 const Type* MAT = getMallocAllocatedType(CI);
1262 const StructType *STy = cast<StructType>(MAT);
1264 // There is guaranteed to be at least one use of the malloc (storing
1265 // it into GV). If there are other uses, change them to be uses of
1266 // the global to simplify later code. This also deletes the store
1268 ReplaceUsesOfMallocWithGlobal(CI, GV);
1270 // Okay, at this point, there are no users of the malloc. Insert N
1271 // new mallocs at the same place as CI, and N globals.
1272 std::vector<Value*> FieldGlobals;
1273 std::vector<Value*> FieldMallocs;
1275 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1276 const Type *FieldTy = STy->getElementType(FieldNo);
1277 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1279 GlobalVariable *NGV =
1280 new GlobalVariable(*GV->getParent(),
1281 PFieldTy, false, GlobalValue::InternalLinkage,
1282 Constant::getNullValue(PFieldTy),
1283 GV->getName() + ".f" + Twine(FieldNo), GV,
1284 GV->isThreadLocal());
1285 FieldGlobals.push_back(NGV);
1287 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1288 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
1289 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1290 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1291 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1292 ConstantInt::get(IntPtrTy, TypeSize),
1294 CI->getName() + ".f" + Twine(FieldNo));
1295 FieldMallocs.push_back(NMI);
1296 new StoreInst(NMI, NGV, CI);
1299 // The tricky aspect of this transformation is handling the case when malloc
1300 // fails. In the original code, malloc failing would set the result pointer
1301 // of malloc to null. In this case, some mallocs could succeed and others
1302 // could fail. As such, we emit code that looks like this:
1303 // F0 = malloc(field0)
1304 // F1 = malloc(field1)
1305 // F2 = malloc(field2)
1306 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1307 // if (F0) { free(F0); F0 = 0; }
1308 // if (F1) { free(F1); F1 = 0; }
1309 // if (F2) { free(F2); F2 = 0; }
1311 // The malloc can also fail if its argument is too large.
1312 Constant *ConstantZero = ConstantInt::get(CI->getOperand(1)->getType(), 0);
1313 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getOperand(1),
1314 ConstantZero, "isneg");
1315 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1316 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1317 Constant::getNullValue(FieldMallocs[i]->getType()),
1319 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1322 // Split the basic block at the old malloc.
1323 BasicBlock *OrigBB = CI->getParent();
1324 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1326 // Create the block to check the first condition. Put all these blocks at the
1327 // end of the function as they are unlikely to be executed.
1328 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1330 OrigBB->getParent());
1332 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1333 // branch on RunningOr.
1334 OrigBB->getTerminator()->eraseFromParent();
1335 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1337 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1338 // pointer, because some may be null while others are not.
1339 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1340 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1341 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1342 Constant::getNullValue(GVVal->getType()),
1344 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1345 OrigBB->getParent());
1346 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1347 OrigBB->getParent());
1348 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1351 // Fill in FreeBlock.
1352 CallInst::CreateFree(GVVal, BI);
1353 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1355 BranchInst::Create(NextBlock, FreeBlock);
1357 NullPtrBlock = NextBlock;
1360 BranchInst::Create(ContBB, NullPtrBlock);
1362 // CI is no longer needed, remove it.
1363 CI->eraseFromParent();
1365 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1366 /// update all uses of the load, keep track of what scalarized loads are
1367 /// inserted for a given load.
1368 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1369 InsertedScalarizedValues[GV] = FieldGlobals;
1371 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1373 // Okay, the malloc site is completely handled. All of the uses of GV are now
1374 // loads, and all uses of those loads are simple. Rewrite them to use loads
1375 // of the per-field globals instead.
1376 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1377 Instruction *User = cast<Instruction>(*UI++);
1379 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1380 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1384 // Must be a store of null.
1385 StoreInst *SI = cast<StoreInst>(User);
1386 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1387 "Unexpected heap-sra user!");
1389 // Insert a store of null into each global.
1390 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1391 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1392 Constant *Null = Constant::getNullValue(PT->getElementType());
1393 new StoreInst(Null, FieldGlobals[i], SI);
1395 // Erase the original store.
1396 SI->eraseFromParent();
1399 // While we have PHIs that are interesting to rewrite, do it.
1400 while (!PHIsToRewrite.empty()) {
1401 PHINode *PN = PHIsToRewrite.back().first;
1402 unsigned FieldNo = PHIsToRewrite.back().second;
1403 PHIsToRewrite.pop_back();
1404 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1405 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1407 // Add all the incoming values. This can materialize more phis.
1408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1409 Value *InVal = PN->getIncomingValue(i);
1410 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1412 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1416 // Drop all inter-phi links and any loads that made it this far.
1417 for (DenseMap<Value*, std::vector<Value*> >::iterator
1418 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1420 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1421 PN->dropAllReferences();
1422 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1423 LI->dropAllReferences();
1426 // Delete all the phis and loads now that inter-references are dead.
1427 for (DenseMap<Value*, std::vector<Value*> >::iterator
1428 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1430 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1431 PN->eraseFromParent();
1432 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1433 LI->eraseFromParent();
1436 // The old global is now dead, remove it.
1437 GV->eraseFromParent();
1440 return cast<GlobalVariable>(FieldGlobals[0]);
1443 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1444 /// pointer global variable with a single value stored it that is a malloc or
1446 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1448 const Type *AllocTy,
1449 Module::global_iterator &GVI,
1451 // If this is a malloc of an abstract type, don't touch it.
1452 if (!AllocTy->isSized())
1455 // We can't optimize this global unless all uses of it are *known* to be
1456 // of the malloc value, not of the null initializer value (consider a use
1457 // that compares the global's value against zero to see if the malloc has
1458 // been reached). To do this, we check to see if all uses of the global
1459 // would trap if the global were null: this proves that they must all
1460 // happen after the malloc.
1461 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1464 // We can't optimize this if the malloc itself is used in a complex way,
1465 // for example, being stored into multiple globals. This allows the
1466 // malloc to be stored into the specified global, loaded setcc'd, and
1467 // GEP'd. These are all things we could transform to using the global
1470 SmallPtrSet<PHINode*, 8> PHIs;
1471 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1475 // If we have a global that is only initialized with a fixed size malloc,
1476 // transform the program to use global memory instead of malloc'd memory.
1477 // This eliminates dynamic allocation, avoids an indirection accessing the
1478 // data, and exposes the resultant global to further GlobalOpt.
1479 // We cannot optimize the malloc if we cannot determine malloc array size.
1480 if (Value *NElems = getMallocArraySize(CI, TD, true)) {
1481 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1482 // Restrict this transformation to only working on small allocations
1483 // (2048 bytes currently), as we don't want to introduce a 16M global or
1486 NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1487 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1491 // If the allocation is an array of structures, consider transforming this
1492 // into multiple malloc'd arrays, one for each field. This is basically
1493 // SRoA for malloc'd memory.
1495 // If this is an allocation of a fixed size array of structs, analyze as a
1496 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1497 if (NElems == ConstantInt::get(CI->getOperand(1)->getType(), 1))
1498 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1499 AllocTy = AT->getElementType();
1501 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1502 // This the structure has an unreasonable number of fields, leave it
1504 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1505 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1507 // If this is a fixed size array, transform the Malloc to be an alloc of
1508 // structs. malloc [100 x struct],1 -> malloc struct, 100
1509 if (const ArrayType *AT =
1510 dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1511 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1512 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1513 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1514 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1515 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1516 AllocSize, NumElements,
1518 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1519 CI->replaceAllUsesWith(Cast);
1520 CI->eraseFromParent();
1521 CI = dyn_cast<BitCastInst>(Malloc) ?
1522 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1525 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1534 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1535 // that only one value (besides its initializer) is ever stored to the global.
1536 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1537 Module::global_iterator &GVI,
1539 // Ignore no-op GEPs and bitcasts.
1540 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1542 // If we are dealing with a pointer global that is initialized to null and
1543 // only has one (non-null) value stored into it, then we can optimize any
1544 // users of the loaded value (often calls and loads) that would trap if the
1546 if (GV->getInitializer()->getType()->isPointerTy() &&
1547 GV->getInitializer()->isNullValue()) {
1548 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1549 if (GV->getInitializer()->getType() != SOVC->getType())
1551 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1553 // Optimize away any trapping uses of the loaded value.
1554 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1556 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1557 const Type* MallocType = getMallocAllocatedType(CI);
1558 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1567 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1568 /// two values ever stored into GV are its initializer and OtherVal. See if we
1569 /// can shrink the global into a boolean and select between the two values
1570 /// whenever it is used. This exposes the values to other scalar optimizations.
1571 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1572 const Type *GVElType = GV->getType()->getElementType();
1574 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1575 // an FP value, pointer or vector, don't do this optimization because a select
1576 // between them is very expensive and unlikely to lead to later
1577 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1578 // where v1 and v2 both require constant pool loads, a big loss.
1579 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1580 GVElType->isFloatingPointTy() ||
1581 GVElType->isPointerTy() || GVElType->isVectorTy())
1584 // Walk the use list of the global seeing if all the uses are load or store.
1585 // If there is anything else, bail out.
1586 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1587 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1590 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1592 // Create the new global, initializing it to false.
1593 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1595 GlobalValue::InternalLinkage,
1596 ConstantInt::getFalse(GV->getContext()),
1598 GV->isThreadLocal());
1599 GV->getParent()->getGlobalList().insert(GV, NewGV);
1601 Constant *InitVal = GV->getInitializer();
1602 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1603 "No reason to shrink to bool!");
1605 // If initialized to zero and storing one into the global, we can use a cast
1606 // instead of a select to synthesize the desired value.
1607 bool IsOneZero = false;
1608 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1609 IsOneZero = InitVal->isNullValue() && CI->isOne();
1611 while (!GV->use_empty()) {
1612 Instruction *UI = cast<Instruction>(GV->use_back());
1613 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1614 // Change the store into a boolean store.
1615 bool StoringOther = SI->getOperand(0) == OtherVal;
1616 // Only do this if we weren't storing a loaded value.
1618 if (StoringOther || SI->getOperand(0) == InitVal)
1619 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1622 // Otherwise, we are storing a previously loaded copy. To do this,
1623 // change the copy from copying the original value to just copying the
1625 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1627 // If we're already replaced the input, StoredVal will be a cast or
1628 // select instruction. If not, it will be a load of the original
1630 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1631 assert(LI->getOperand(0) == GV && "Not a copy!");
1632 // Insert a new load, to preserve the saved value.
1633 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1635 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1636 "This is not a form that we understand!");
1637 StoreVal = StoredVal->getOperand(0);
1638 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1641 new StoreInst(StoreVal, NewGV, SI);
1643 // Change the load into a load of bool then a select.
1644 LoadInst *LI = cast<LoadInst>(UI);
1645 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1648 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1650 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1652 LI->replaceAllUsesWith(NSI);
1654 UI->eraseFromParent();
1657 GV->eraseFromParent();
1662 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1663 /// it if possible. If we make a change, return true.
1664 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1665 Module::global_iterator &GVI) {
1666 SmallPtrSet<const PHINode*, 16> PHIUsers;
1668 GV->removeDeadConstantUsers();
1670 if (GV->use_empty()) {
1671 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1672 GV->eraseFromParent();
1677 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1679 DEBUG(dbgs() << "Global: " << *GV);
1680 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1681 DEBUG(dbgs() << " StoredType = ");
1682 switch (GS.StoredType) {
1683 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1684 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
1686 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1687 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
1689 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1690 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
1691 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1692 DEBUG(dbgs() << " AccessingFunction = " << GS.AccessingFunction->getName()
1694 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
1695 << GS.HasMultipleAccessingFunctions << "\n");
1696 DEBUG(dbgs() << " HasNonInstructionUser = "
1697 << GS.HasNonInstructionUser<<"\n");
1698 DEBUG(dbgs() << "\n");
1701 // If this is a first class global and has only one accessing function
1702 // and this function is main (which we know is not recursive we can make
1703 // this global a local variable) we replace the global with a local alloca
1704 // in this function.
1706 // NOTE: It doesn't make sense to promote non single-value types since we
1707 // are just replacing static memory to stack memory.
1709 // If the global is in different address space, don't bring it to stack.
1710 if (!GS.HasMultipleAccessingFunctions &&
1711 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1712 GV->getType()->getElementType()->isSingleValueType() &&
1713 GS.AccessingFunction->getName() == "main" &&
1714 GS.AccessingFunction->hasExternalLinkage() &&
1715 GV->getType()->getAddressSpace() == 0) {
1716 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1717 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1718 ->getEntryBlock().begin());
1719 const Type* ElemTy = GV->getType()->getElementType();
1720 // FIXME: Pass Global's alignment when globals have alignment
1721 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1722 if (!isa<UndefValue>(GV->getInitializer()))
1723 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1725 GV->replaceAllUsesWith(Alloca);
1726 GV->eraseFromParent();
1731 // If the global is never loaded (but may be stored to), it is dead.
1734 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1736 // Delete any stores we can find to the global. We may not be able to
1737 // make it completely dead though.
1738 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1740 // If the global is dead now, delete it.
1741 if (GV->use_empty()) {
1742 GV->eraseFromParent();
1748 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1749 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1750 GV->setConstant(true);
1752 // Clean up any obviously simplifiable users now.
1753 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1755 // If the global is dead now, just nuke it.
1756 if (GV->use_empty()) {
1757 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1758 << "all users and delete global!\n");
1759 GV->eraseFromParent();
1765 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1766 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1767 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1768 GVI = FirstNewGV; // Don't skip the newly produced globals!
1771 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1772 // If the initial value for the global was an undef value, and if only
1773 // one other value was stored into it, we can just change the
1774 // initializer to be the stored value, then delete all stores to the
1775 // global. This allows us to mark it constant.
1776 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1777 if (isa<UndefValue>(GV->getInitializer())) {
1778 // Change the initial value here.
1779 GV->setInitializer(SOVConstant);
1781 // Clean up any obviously simplifiable users now.
1782 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1784 if (GV->use_empty()) {
1785 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1786 << "simplify all users and delete global!\n");
1787 GV->eraseFromParent();
1796 // Try to optimize globals based on the knowledge that only one value
1797 // (besides its initializer) is ever stored to the global.
1798 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1799 getAnalysisIfAvailable<TargetData>()))
1802 // Otherwise, if the global was not a boolean, we can shrink it to be a
1804 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1805 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1814 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1815 /// function, changing them to FastCC.
1816 static void ChangeCalleesToFastCall(Function *F) {
1817 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1818 CallSite User(cast<Instruction>(*UI));
1819 User.setCallingConv(CallingConv::Fast);
1823 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1824 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1825 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1828 // There can be only one.
1829 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1835 static void RemoveNestAttribute(Function *F) {
1836 F->setAttributes(StripNest(F->getAttributes()));
1837 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1838 CallSite User(cast<Instruction>(*UI));
1839 User.setAttributes(StripNest(User.getAttributes()));
1843 bool GlobalOpt::OptimizeFunctions(Module &M) {
1844 bool Changed = false;
1845 // Optimize functions.
1846 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1848 // Functions without names cannot be referenced outside this module.
1849 if (!F->hasName() && !F->isDeclaration())
1850 F->setLinkage(GlobalValue::InternalLinkage);
1851 F->removeDeadConstantUsers();
1852 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1853 F->eraseFromParent();
1856 } else if (F->hasLocalLinkage()) {
1857 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1858 !F->hasAddressTaken()) {
1859 // If this function has C calling conventions, is not a varargs
1860 // function, and is only called directly, promote it to use the Fast
1861 // calling convention.
1862 F->setCallingConv(CallingConv::Fast);
1863 ChangeCalleesToFastCall(F);
1868 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1869 !F->hasAddressTaken()) {
1870 // The function is not used by a trampoline intrinsic, so it is safe
1871 // to remove the 'nest' attribute.
1872 RemoveNestAttribute(F);
1881 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1882 bool Changed = false;
1883 TargetData *TD = getAnalysisIfAvailable<TargetData>();
1884 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1886 GlobalVariable *GV = GVI++;
1887 // Global variables without names cannot be referenced outside this module.
1888 if (!GV->hasName() && !GV->isDeclaration())
1889 GV->setLinkage(GlobalValue::InternalLinkage);
1890 // Simplify the initializer.
1891 if (GV->hasInitializer())
1892 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1893 Constant *New = ConstantFoldConstantExpression(CE, TD);
1894 if (New && New != CE)
1895 GV->setInitializer(New);
1897 // Refine the alignment value.
1898 if (TD && GV->hasDefinitiveInitializer()) {
1899 unsigned Align = TD->getPreferredAlignment(GV);
1900 if (Align > GV->getAlignment())
1901 GV->setAlignment(Align);
1903 // Do more involved optimizations if the global is internal.
1904 if (!GV->isConstant() && GV->hasLocalLinkage() &&
1905 GV->hasInitializer())
1906 Changed |= ProcessInternalGlobal(GV, GVI);
1911 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1912 /// initializers have an init priority of 65535.
1913 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1914 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1916 if (I->getName() == "llvm.global_ctors") {
1917 // Found it, verify it's an array of { int, void()* }.
1918 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1920 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1921 if (!STy || STy->getNumElements() != 2 ||
1922 !STy->getElementType(0)->isIntegerTy(32)) return 0;
1923 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1924 if (!PFTy) return 0;
1925 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1926 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1927 FTy->isVarArg() || FTy->getNumParams() != 0)
1930 // Verify that the initializer is simple enough for us to handle.
1931 if (!I->hasDefinitiveInitializer()) return 0;
1932 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1934 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1935 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
1936 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1939 // Must have a function or null ptr.
1940 if (!isa<Function>(CS->getOperand(1)))
1943 // Init priority must be standard.
1944 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1945 if (!CI || CI->getZExtValue() != 65535)
1956 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1957 /// return a list of the functions and null terminator as a vector.
1958 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1959 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1960 std::vector<Function*> Result;
1961 Result.reserve(CA->getNumOperands());
1962 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1963 ConstantStruct *CS = cast<ConstantStruct>(*i);
1964 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1969 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1970 /// specified array, returning the new global to use.
1971 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1972 const std::vector<Function*> &Ctors) {
1973 // If we made a change, reassemble the initializer list.
1974 std::vector<Constant*> CSVals;
1975 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
1976 CSVals.push_back(0);
1978 // Create the new init list.
1979 std::vector<Constant*> CAList;
1980 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1982 CSVals[1] = Ctors[i];
1984 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
1986 const PointerType *PFTy = PointerType::getUnqual(FTy);
1987 CSVals[1] = Constant::getNullValue(PFTy);
1988 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
1991 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
1994 // Create the array initializer.
1995 const Type *StructTy =
1996 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1997 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
1998 CAList.size()), CAList);
2000 // If we didn't change the number of elements, don't create a new GV.
2001 if (CA->getType() == GCL->getInitializer()->getType()) {
2002 GCL->setInitializer(CA);
2006 // Create the new global and insert it next to the existing list.
2007 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2008 GCL->getLinkage(), CA, "",
2009 GCL->isThreadLocal());
2010 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2013 // Nuke the old list, replacing any uses with the new one.
2014 if (!GCL->use_empty()) {
2016 if (V->getType() != GCL->getType())
2017 V = ConstantExpr::getBitCast(V, GCL->getType());
2018 GCL->replaceAllUsesWith(V);
2020 GCL->eraseFromParent();
2029 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
2031 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2032 Constant *R = ComputedValues[V];
2033 assert(R && "Reference to an uncomputed value!");
2037 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2038 /// enough for us to understand. In particular, if it is a cast of something,
2039 /// we punt. We basically just support direct accesses to globals and GEP's of
2040 /// globals. This should be kept up to date with CommitValueTo.
2041 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2042 // Conservatively, avoid aggregate types. This is because we don't
2043 // want to worry about them partially overlapping other stores.
2044 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2047 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2048 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2049 // external globals.
2050 return GV->hasDefinitiveInitializer();
2052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2053 // Handle a constantexpr gep.
2054 if (CE->getOpcode() == Instruction::GetElementPtr &&
2055 isa<GlobalVariable>(CE->getOperand(0)) &&
2056 cast<GEPOperator>(CE)->isInBounds()) {
2057 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2058 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2059 // external globals.
2060 if (!GV->hasDefinitiveInitializer())
2063 // The first index must be zero.
2064 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
2065 if (!CI || !CI->isZero()) return false;
2067 // The remaining indices must be compile-time known integers within the
2068 // notional bounds of the corresponding static array types.
2069 if (!CE->isGEPWithNoNotionalOverIndexing())
2072 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2077 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2078 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2079 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2080 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2081 ConstantExpr *Addr, unsigned OpNo) {
2082 // Base case of the recursion.
2083 if (OpNo == Addr->getNumOperands()) {
2084 assert(Val->getType() == Init->getType() && "Type mismatch!");
2088 std::vector<Constant*> Elts;
2089 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2091 // Break up the constant into its elements.
2092 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2093 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2094 Elts.push_back(cast<Constant>(*i));
2095 } else if (isa<ConstantAggregateZero>(Init)) {
2096 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2097 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2098 } else if (isa<UndefValue>(Init)) {
2099 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2100 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2102 llvm_unreachable("This code is out of sync with "
2103 " ConstantFoldLoadThroughGEPConstantExpr");
2106 // Replace the element that we are supposed to.
2107 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2108 unsigned Idx = CU->getZExtValue();
2109 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2110 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2112 // Return the modified struct.
2113 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2116 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2117 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
2120 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2121 NumElts = ATy->getNumElements();
2123 NumElts = cast<VectorType>(InitTy)->getNumElements();
2126 // Break up the array into elements.
2127 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2128 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2129 Elts.push_back(cast<Constant>(*i));
2130 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2131 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2132 Elts.push_back(cast<Constant>(*i));
2133 } else if (isa<ConstantAggregateZero>(Init)) {
2134 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2136 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2137 " ConstantFoldLoadThroughGEPConstantExpr");
2138 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2141 assert(CI->getZExtValue() < NumElts);
2142 Elts[CI->getZExtValue()] =
2143 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2145 if (Init->getType()->isArrayTy())
2146 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2148 return ConstantVector::get(&Elts[0], Elts.size());
2152 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2153 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2154 static void CommitValueTo(Constant *Val, Constant *Addr) {
2155 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2156 assert(GV->hasInitializer());
2157 GV->setInitializer(Val);
2161 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2162 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2163 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2166 /// ComputeLoadResult - Return the value that would be computed by a load from
2167 /// P after the stores reflected by 'memory' have been performed. If we can't
2168 /// decide, return null.
2169 static Constant *ComputeLoadResult(Constant *P,
2170 const DenseMap<Constant*, Constant*> &Memory) {
2171 // If this memory location has been recently stored, use the stored value: it
2172 // is the most up-to-date.
2173 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2174 if (I != Memory.end()) return I->second;
2177 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2178 if (GV->hasDefinitiveInitializer())
2179 return GV->getInitializer();
2183 // Handle a constantexpr getelementptr.
2184 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2185 if (CE->getOpcode() == Instruction::GetElementPtr &&
2186 isa<GlobalVariable>(CE->getOperand(0))) {
2187 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2188 if (GV->hasDefinitiveInitializer())
2189 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2192 return 0; // don't know how to evaluate.
2195 /// EvaluateFunction - Evaluate a call to function F, returning true if
2196 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2197 /// arguments for the function.
2198 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2199 const SmallVectorImpl<Constant*> &ActualArgs,
2200 std::vector<Function*> &CallStack,
2201 DenseMap<Constant*, Constant*> &MutatedMemory,
2202 std::vector<GlobalVariable*> &AllocaTmps) {
2203 // Check to see if this function is already executing (recursion). If so,
2204 // bail out. TODO: we might want to accept limited recursion.
2205 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2208 CallStack.push_back(F);
2210 /// Values - As we compute SSA register values, we store their contents here.
2211 DenseMap<Value*, Constant*> Values;
2213 // Initialize arguments to the incoming values specified.
2215 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2217 Values[AI] = ActualArgs[ArgNo];
2219 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2220 /// we can only evaluate any one basic block at most once. This set keeps
2221 /// track of what we have executed so we can detect recursive cases etc.
2222 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2224 // CurInst - The current instruction we're evaluating.
2225 BasicBlock::iterator CurInst = F->begin()->begin();
2227 // This is the main evaluation loop.
2229 Constant *InstResult = 0;
2231 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2232 if (SI->isVolatile()) return false; // no volatile accesses.
2233 Constant *Ptr = getVal(Values, SI->getOperand(1));
2234 if (!isSimpleEnoughPointerToCommit(Ptr))
2235 // If this is too complex for us to commit, reject it.
2237 Constant *Val = getVal(Values, SI->getOperand(0));
2238 MutatedMemory[Ptr] = Val;
2239 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2240 InstResult = ConstantExpr::get(BO->getOpcode(),
2241 getVal(Values, BO->getOperand(0)),
2242 getVal(Values, BO->getOperand(1)));
2243 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2244 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2245 getVal(Values, CI->getOperand(0)),
2246 getVal(Values, CI->getOperand(1)));
2247 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2248 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2249 getVal(Values, CI->getOperand(0)),
2251 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2253 ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2254 getVal(Values, SI->getOperand(1)),
2255 getVal(Values, SI->getOperand(2)));
2256 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2257 Constant *P = getVal(Values, GEP->getOperand(0));
2258 SmallVector<Constant*, 8> GEPOps;
2259 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2261 GEPOps.push_back(getVal(Values, *i));
2262 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2263 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2264 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2265 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2266 if (LI->isVolatile()) return false; // no volatile accesses.
2267 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2269 if (InstResult == 0) return false; // Could not evaluate load.
2270 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2271 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2272 const Type *Ty = AI->getType()->getElementType();
2273 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2274 GlobalValue::InternalLinkage,
2275 UndefValue::get(Ty),
2277 InstResult = AllocaTmps.back();
2278 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2280 // Debug info can safely be ignored here.
2281 if (isa<DbgInfoIntrinsic>(CI)) {
2286 // Cannot handle inline asm.
2287 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2289 // Resolve function pointers.
2290 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2291 if (!Callee) return false; // Cannot resolve.
2293 SmallVector<Constant*, 8> Formals;
2294 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2296 Formals.push_back(getVal(Values, *i));
2298 if (Callee->isDeclaration()) {
2299 // If this is a function we can constant fold, do it.
2300 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2307 if (Callee->getFunctionType()->isVarArg())
2311 // Execute the call, if successful, use the return value.
2312 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2313 MutatedMemory, AllocaTmps))
2315 InstResult = RetVal;
2317 } else if (isa<TerminatorInst>(CurInst)) {
2318 BasicBlock *NewBB = 0;
2319 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2320 if (BI->isUnconditional()) {
2321 NewBB = BI->getSuccessor(0);
2324 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2325 if (!Cond) return false; // Cannot determine.
2327 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2329 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2331 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2332 if (!Val) return false; // Cannot determine.
2333 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2334 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2335 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2336 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2337 NewBB = BA->getBasicBlock();
2339 return false; // Cannot determine.
2340 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2341 if (RI->getNumOperands())
2342 RetVal = getVal(Values, RI->getOperand(0));
2344 CallStack.pop_back(); // return from fn.
2345 return true; // We succeeded at evaluating this ctor!
2347 // invoke, unwind, unreachable.
2348 return false; // Cannot handle this terminator.
2351 // Okay, we succeeded in evaluating this control flow. See if we have
2352 // executed the new block before. If so, we have a looping function,
2353 // which we cannot evaluate in reasonable time.
2354 if (!ExecutedBlocks.insert(NewBB))
2355 return false; // looped!
2357 // Okay, we have never been in this block before. Check to see if there
2358 // are any PHI nodes. If so, evaluate them with information about where
2360 BasicBlock *OldBB = CurInst->getParent();
2361 CurInst = NewBB->begin();
2363 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2364 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2366 // Do NOT increment CurInst. We know that the terminator had no value.
2369 // Did not know how to evaluate this!
2373 if (!CurInst->use_empty())
2374 Values[CurInst] = InstResult;
2376 // Advance program counter.
2381 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2382 /// we can. Return true if we can, false otherwise.
2383 static bool EvaluateStaticConstructor(Function *F) {
2384 /// MutatedMemory - For each store we execute, we update this map. Loads
2385 /// check this to get the most up-to-date value. If evaluation is successful,
2386 /// this state is committed to the process.
2387 DenseMap<Constant*, Constant*> MutatedMemory;
2389 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2390 /// to represent its body. This vector is needed so we can delete the
2391 /// temporary globals when we are done.
2392 std::vector<GlobalVariable*> AllocaTmps;
2394 /// CallStack - This is used to detect recursion. In pathological situations
2395 /// we could hit exponential behavior, but at least there is nothing
2397 std::vector<Function*> CallStack;
2399 // Call the function.
2400 Constant *RetValDummy;
2401 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2402 SmallVector<Constant*, 0>(), CallStack,
2403 MutatedMemory, AllocaTmps);
2405 // We succeeded at evaluation: commit the result.
2406 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2407 << F->getName() << "' to " << MutatedMemory.size()
2409 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2410 E = MutatedMemory.end(); I != E; ++I)
2411 CommitValueTo(I->second, I->first);
2414 // At this point, we are done interpreting. If we created any 'alloca'
2415 // temporaries, release them now.
2416 while (!AllocaTmps.empty()) {
2417 GlobalVariable *Tmp = AllocaTmps.back();
2418 AllocaTmps.pop_back();
2420 // If there are still users of the alloca, the program is doing something
2421 // silly, e.g. storing the address of the alloca somewhere and using it
2422 // later. Since this is undefined, we'll just make it be null.
2423 if (!Tmp->use_empty())
2424 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2433 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2434 /// Return true if anything changed.
2435 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2436 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2437 bool MadeChange = false;
2438 if (Ctors.empty()) return false;
2440 // Loop over global ctors, optimizing them when we can.
2441 for (unsigned i = 0; i != Ctors.size(); ++i) {
2442 Function *F = Ctors[i];
2443 // Found a null terminator in the middle of the list, prune off the rest of
2446 if (i != Ctors.size()-1) {
2453 // We cannot simplify external ctor functions.
2454 if (F->empty()) continue;
2456 // If we can evaluate the ctor at compile time, do.
2457 if (EvaluateStaticConstructor(F)) {
2458 Ctors.erase(Ctors.begin()+i);
2461 ++NumCtorsEvaluated;
2466 if (!MadeChange) return false;
2468 GCL = InstallGlobalCtors(GCL, Ctors);
2472 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2473 bool Changed = false;
2475 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2477 Module::alias_iterator J = I++;
2478 // Aliases without names cannot be referenced outside this module.
2479 if (!J->hasName() && !J->isDeclaration())
2480 J->setLinkage(GlobalValue::InternalLinkage);
2481 // If the aliasee may change at link time, nothing can be done - bail out.
2482 if (J->mayBeOverridden())
2485 Constant *Aliasee = J->getAliasee();
2486 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2487 Target->removeDeadConstantUsers();
2488 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2490 // Make all users of the alias use the aliasee instead.
2491 if (!J->use_empty()) {
2492 J->replaceAllUsesWith(Aliasee);
2493 ++NumAliasesResolved;
2497 // If the alias is externally visible, we may still be able to simplify it.
2498 if (!J->hasLocalLinkage()) {
2499 // If the aliasee has internal linkage, give it the name and linkage
2500 // of the alias, and delete the alias. This turns:
2501 // define internal ... @f(...)
2502 // @a = alias ... @f
2504 // define ... @a(...)
2505 if (!Target->hasLocalLinkage())
2508 // Do not perform the transform if multiple aliases potentially target the
2509 // aliasee. This check also ensures that it is safe to replace the section
2510 // and other attributes of the aliasee with those of the alias.
2514 // Give the aliasee the name, linkage and other attributes of the alias.
2515 Target->takeName(J);
2516 Target->setLinkage(J->getLinkage());
2517 Target->GlobalValue::copyAttributesFrom(J);
2520 // Delete the alias.
2521 M.getAliasList().erase(J);
2522 ++NumAliasesRemoved;
2529 bool GlobalOpt::runOnModule(Module &M) {
2530 bool Changed = false;
2532 // Try to find the llvm.globalctors list.
2533 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2535 bool LocalChange = true;
2536 while (LocalChange) {
2537 LocalChange = false;
2539 // Delete functions that are trivially dead, ccc -> fastcc
2540 LocalChange |= OptimizeFunctions(M);
2542 // Optimize global_ctors list.
2544 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2546 // Optimize non-address-taken globals.
2547 LocalChange |= OptimizeGlobalVars(M);
2549 // Resolve aliases, when possible.
2550 LocalChange |= OptimizeGlobalAliases(M);
2551 Changed |= LocalChange;
2554 // TODO: Move all global ctors functions to the end of the module for code