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;
148 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
149 if (!SafeToDestroyConstant(CU)) return false;
156 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
157 /// structure. If the global has its address taken, return true to indicate we
158 /// can't do anything with it.
160 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
161 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
162 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
165 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
166 GS.HasNonInstructionUser = true;
167 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
168 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
169 if (!GS.HasMultipleAccessingFunctions) {
170 const Function *F = I->getParent()->getParent();
171 if (GS.AccessingFunction == 0)
172 GS.AccessingFunction = F;
173 else if (GS.AccessingFunction != F)
174 GS.HasMultipleAccessingFunctions = true;
176 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
178 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
179 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
180 // Don't allow a store OF the address, only stores TO the address.
181 if (SI->getOperand(0) == V) return true;
183 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
185 // If this is a direct store to the global (i.e., the global is a scalar
186 // value, not an aggregate), keep more specific information about
188 if (GS.StoredType != GlobalStatus::isStored) {
189 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
190 SI->getOperand(1))) {
191 Value *StoredVal = SI->getOperand(0);
192 if (StoredVal == GV->getInitializer()) {
193 if (GS.StoredType < GlobalStatus::isInitializerStored)
194 GS.StoredType = GlobalStatus::isInitializerStored;
195 } else if (isa<LoadInst>(StoredVal) &&
196 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
197 if (GS.StoredType < GlobalStatus::isInitializerStored)
198 GS.StoredType = GlobalStatus::isInitializerStored;
199 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
200 GS.StoredType = GlobalStatus::isStoredOnce;
201 GS.StoredOnceValue = StoredVal;
202 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
203 GS.StoredOnceValue == StoredVal) {
206 GS.StoredType = GlobalStatus::isStored;
209 GS.StoredType = GlobalStatus::isStored;
212 } else if (isa<GetElementPtrInst>(I)) {
213 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
214 } else if (isa<SelectInst>(I)) {
215 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
216 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
217 // PHI nodes we can check just like select or GEP instructions, but we
218 // have to be careful about infinite recursion.
219 if (PHIUsers.insert(PN)) // Not already visited.
220 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
221 GS.HasPHIUser = true;
222 } else if (isa<CmpInst>(I)) {
223 // Nothing to analyse.
224 } else if (isa<MemTransferInst>(I)) {
225 const MemTransferInst *MTI = cast<MemTransferInst>(I);
226 if (MTI->getArgOperand(0) == V)
227 GS.StoredType = GlobalStatus::isStored;
228 if (MTI->getArgOperand(1) == V)
230 } else if (isa<MemSetInst>(I)) {
231 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
232 "Memset only takes one pointer!");
233 GS.StoredType = GlobalStatus::isStored;
235 return true; // Any other non-load instruction might take address!
237 } else if (const Constant *C = dyn_cast<Constant>(U)) {
238 GS.HasNonInstructionUser = true;
239 // We might have a dead and dangling constant hanging off of here.
240 if (!SafeToDestroyConstant(C))
243 GS.HasNonInstructionUser = true;
244 // Otherwise must be some other user.
252 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
253 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
255 unsigned IdxV = CI->getZExtValue();
257 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
258 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
259 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
260 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
261 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
262 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
263 } else if (isa<ConstantAggregateZero>(Agg)) {
264 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
265 if (IdxV < STy->getNumElements())
266 return Constant::getNullValue(STy->getElementType(IdxV));
267 } else if (const SequentialType *STy =
268 dyn_cast<SequentialType>(Agg->getType())) {
269 return Constant::getNullValue(STy->getElementType());
271 } else if (isa<UndefValue>(Agg)) {
272 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
273 if (IdxV < STy->getNumElements())
274 return UndefValue::get(STy->getElementType(IdxV));
275 } else if (const SequentialType *STy =
276 dyn_cast<SequentialType>(Agg->getType())) {
277 return UndefValue::get(STy->getElementType());
284 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
285 /// users of the global, cleaning up the obvious ones. This is largely just a
286 /// quick scan over the use list to clean up the easy and obvious cruft. This
287 /// returns true if it made a change.
288 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
289 bool Changed = false;
290 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
293 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
295 // Replace the load with the initializer.
296 LI->replaceAllUsesWith(Init);
297 LI->eraseFromParent();
300 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
301 // Store must be unreachable or storing Init into the global.
302 SI->eraseFromParent();
304 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
305 if (CE->getOpcode() == Instruction::GetElementPtr) {
306 Constant *SubInit = 0;
308 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
309 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
310 } else if (CE->getOpcode() == Instruction::BitCast &&
311 CE->getType()->isPointerTy()) {
312 // Pointer cast, delete any stores and memsets to the global.
313 Changed |= CleanupConstantGlobalUsers(CE, 0);
316 if (CE->use_empty()) {
317 CE->destroyConstant();
320 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
321 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
322 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
323 // and will invalidate our notion of what Init is.
324 Constant *SubInit = 0;
325 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
327 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
328 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
329 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
331 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
333 if (GEP->use_empty()) {
334 GEP->eraseFromParent();
337 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
338 if (MI->getRawDest() == V) {
339 MI->eraseFromParent();
343 } else if (Constant *C = dyn_cast<Constant>(U)) {
344 // If we have a chain of dead constantexprs or other things dangling from
345 // us, and if they are all dead, nuke them without remorse.
346 if (SafeToDestroyConstant(C)) {
347 C->destroyConstant();
348 // This could have invalidated UI, start over from scratch.
349 CleanupConstantGlobalUsers(V, Init);
357 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
358 /// user of a derived expression from a global that we want to SROA.
359 static bool isSafeSROAElementUse(Value *V) {
360 // We might have a dead and dangling constant hanging off of here.
361 if (Constant *C = dyn_cast<Constant>(V))
362 return SafeToDestroyConstant(C);
364 Instruction *I = dyn_cast<Instruction>(V);
365 if (!I) return false;
368 if (isa<LoadInst>(I)) return true;
370 // Stores *to* the pointer are ok.
371 if (StoreInst *SI = dyn_cast<StoreInst>(I))
372 return SI->getOperand(0) != V;
374 // Otherwise, it must be a GEP.
375 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
376 if (GEPI == 0) return false;
378 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
379 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
382 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
384 if (!isSafeSROAElementUse(*I))
390 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
391 /// Look at it and its uses and decide whether it is safe to SROA this global.
393 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
394 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
395 if (!isa<GetElementPtrInst>(U) &&
396 (!isa<ConstantExpr>(U) ||
397 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
400 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
401 // don't like < 3 operand CE's, and we don't like non-constant integer
402 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
404 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
405 !cast<Constant>(U->getOperand(1))->isNullValue() ||
406 !isa<ConstantInt>(U->getOperand(2)))
409 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
410 ++GEPI; // Skip over the pointer index.
412 // If this is a use of an array allocation, do a bit more checking for sanity.
413 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
414 uint64_t NumElements = AT->getNumElements();
415 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
417 // Check to make sure that index falls within the array. If not,
418 // something funny is going on, so we won't do the optimization.
420 if (Idx->getZExtValue() >= NumElements)
423 // We cannot scalar repl this level of the array unless any array
424 // sub-indices are in-range constants. In particular, consider:
425 // A[0][i]. We cannot know that the user isn't doing invalid things like
426 // allowing i to index an out-of-range subscript that accesses A[1].
428 // Scalar replacing *just* the outer index of the array is probably not
429 // going to be a win anyway, so just give up.
430 for (++GEPI; // Skip array index.
433 uint64_t NumElements;
434 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
435 NumElements = SubArrayTy->getNumElements();
436 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
437 NumElements = SubVectorTy->getNumElements();
439 assert((*GEPI)->isStructTy() &&
440 "Indexed GEP type is not array, vector, or struct!");
444 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
445 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
450 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
451 if (!isSafeSROAElementUse(*I))
456 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
457 /// is safe for us to perform this transformation.
459 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
460 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
462 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
469 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
470 /// variable. This opens the door for other optimizations by exposing the
471 /// behavior of the program in a more fine-grained way. We have determined that
472 /// this transformation is safe already. We return the first global variable we
473 /// insert so that the caller can reprocess it.
474 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
475 // Make sure this global only has simple uses that we can SRA.
476 if (!GlobalUsersSafeToSRA(GV))
479 assert(GV->hasLocalLinkage() && !GV->isConstant());
480 Constant *Init = GV->getInitializer();
481 const Type *Ty = Init->getType();
483 std::vector<GlobalVariable*> NewGlobals;
484 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
486 // Get the alignment of the global, either explicit or target-specific.
487 unsigned StartAlignment = GV->getAlignment();
488 if (StartAlignment == 0)
489 StartAlignment = TD.getABITypeAlignment(GV->getType());
491 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
492 NewGlobals.reserve(STy->getNumElements());
493 const StructLayout &Layout = *TD.getStructLayout(STy);
494 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
495 Constant *In = getAggregateConstantElement(Init,
496 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
497 assert(In && "Couldn't get element of initializer?");
498 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
499 GlobalVariable::InternalLinkage,
500 In, GV->getName()+"."+Twine(i),
502 GV->getType()->getAddressSpace());
503 Globals.insert(GV, NGV);
504 NewGlobals.push_back(NGV);
506 // Calculate the known alignment of the field. If the original aggregate
507 // had 256 byte alignment for example, something might depend on that:
508 // propagate info to each field.
509 uint64_t FieldOffset = Layout.getElementOffset(i);
510 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
511 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
512 NGV->setAlignment(NewAlign);
514 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
515 unsigned NumElements = 0;
516 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
517 NumElements = ATy->getNumElements();
519 NumElements = cast<VectorType>(STy)->getNumElements();
521 if (NumElements > 16 && GV->hasNUsesOrMore(16))
522 return 0; // It's not worth it.
523 NewGlobals.reserve(NumElements);
525 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
526 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
527 for (unsigned i = 0, e = NumElements; i != e; ++i) {
528 Constant *In = getAggregateConstantElement(Init,
529 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
530 assert(In && "Couldn't get element of initializer?");
532 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
533 GlobalVariable::InternalLinkage,
534 In, GV->getName()+"."+Twine(i),
536 GV->getType()->getAddressSpace());
537 Globals.insert(GV, NGV);
538 NewGlobals.push_back(NGV);
540 // Calculate the known alignment of the field. If the original aggregate
541 // had 256 byte alignment for example, something might depend on that:
542 // propagate info to each field.
543 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
544 if (NewAlign > EltAlign)
545 NGV->setAlignment(NewAlign);
549 if (NewGlobals.empty())
552 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
554 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
556 // Loop over all of the uses of the global, replacing the constantexpr geps,
557 // with smaller constantexpr geps or direct references.
558 while (!GV->use_empty()) {
559 User *GEP = GV->use_back();
560 assert(((isa<ConstantExpr>(GEP) &&
561 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
562 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
564 // Ignore the 1th operand, which has to be zero or else the program is quite
565 // broken (undefined). Get the 2nd operand, which is the structure or array
567 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
568 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
570 Value *NewPtr = NewGlobals[Val];
572 // Form a shorter GEP if needed.
573 if (GEP->getNumOperands() > 3) {
574 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
575 SmallVector<Constant*, 8> Idxs;
576 Idxs.push_back(NullInt);
577 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
578 Idxs.push_back(CE->getOperand(i));
579 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
580 &Idxs[0], Idxs.size());
582 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
583 SmallVector<Value*, 8> Idxs;
584 Idxs.push_back(NullInt);
585 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
586 Idxs.push_back(GEPI->getOperand(i));
587 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
588 GEPI->getName()+"."+Twine(Val),GEPI);
591 GEP->replaceAllUsesWith(NewPtr);
593 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
594 GEPI->eraseFromParent();
596 cast<ConstantExpr>(GEP)->destroyConstant();
599 // Delete the old global, now that it is dead.
603 // Loop over the new globals array deleting any globals that are obviously
604 // dead. This can arise due to scalarization of a structure or an array that
605 // has elements that are dead.
606 unsigned FirstGlobal = 0;
607 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
608 if (NewGlobals[i]->use_empty()) {
609 Globals.erase(NewGlobals[i]);
610 if (FirstGlobal == i) ++FirstGlobal;
613 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
616 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
617 /// value will trap if the value is dynamically null. PHIs keeps track of any
618 /// phi nodes we've seen to avoid reprocessing them.
619 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
620 SmallPtrSet<const PHINode*, 8> &PHIs) {
621 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
625 if (isa<LoadInst>(U)) {
627 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
628 if (SI->getOperand(0) == V) {
629 //cerr << "NONTRAPPING USE: " << *U;
630 return false; // Storing the value.
632 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
633 if (CI->getCalledValue() != V) {
634 //cerr << "NONTRAPPING USE: " << *U;
635 return false; // Not calling the ptr
637 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
638 if (II->getCalledValue() != V) {
639 //cerr << "NONTRAPPING USE: " << *U;
640 return false; // Not calling the ptr
642 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
643 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
644 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
645 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
646 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
647 // If we've already seen this phi node, ignore it, it has already been
649 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
651 } else if (isa<ICmpInst>(U) &&
652 isa<ConstantPointerNull>(UI->getOperand(1))) {
653 // Ignore icmp X, null
655 //cerr << "NONTRAPPING USE: " << *U;
662 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
663 /// from GV will trap if the loaded value is null. Note that this also permits
664 /// comparisons of the loaded value against null, as a special case.
665 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
666 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
670 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
671 SmallPtrSet<const PHINode*, 8> PHIs;
672 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
674 } else if (isa<StoreInst>(U)) {
675 // Ignore stores to the global.
677 // We don't know or understand this user, bail out.
678 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
685 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
686 bool Changed = false;
687 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
688 Instruction *I = cast<Instruction>(*UI++);
689 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
690 LI->setOperand(0, NewV);
692 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
693 if (SI->getOperand(1) == V) {
694 SI->setOperand(1, NewV);
697 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
699 if (CS.getCalledValue() == V) {
700 // Calling through the pointer! Turn into a direct call, but be careful
701 // that the pointer is not also being passed as an argument.
702 CS.setCalledFunction(NewV);
704 bool PassedAsArg = false;
705 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
706 if (CS.getArgument(i) == V) {
708 CS.setArgument(i, NewV);
712 // Being passed as an argument also. Be careful to not invalidate UI!
716 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
717 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
718 ConstantExpr::getCast(CI->getOpcode(),
719 NewV, CI->getType()));
720 if (CI->use_empty()) {
722 CI->eraseFromParent();
724 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
725 // Should handle GEP here.
726 SmallVector<Constant*, 8> Idxs;
727 Idxs.reserve(GEPI->getNumOperands()-1);
728 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
730 if (Constant *C = dyn_cast<Constant>(*i))
734 if (Idxs.size() == GEPI->getNumOperands()-1)
735 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
736 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
738 if (GEPI->use_empty()) {
740 GEPI->eraseFromParent();
749 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
750 /// value stored into it. If there are uses of the loaded value that would trap
751 /// if the loaded value is dynamically null, then we know that they cannot be
752 /// reachable with a null optimize away the load.
753 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
754 bool Changed = false;
756 // Keep track of whether we are able to remove all the uses of the global
757 // other than the store that defines it.
758 bool AllNonStoreUsesGone = true;
760 // Replace all uses of loads with uses of uses of the stored value.
761 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
762 User *GlobalUser = *GUI++;
763 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
764 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
765 // If we were able to delete all uses of the loads
766 if (LI->use_empty()) {
767 LI->eraseFromParent();
770 AllNonStoreUsesGone = false;
772 } else if (isa<StoreInst>(GlobalUser)) {
773 // Ignore the store that stores "LV" to the global.
774 assert(GlobalUser->getOperand(1) == GV &&
775 "Must be storing *to* the global");
777 AllNonStoreUsesGone = false;
779 // If we get here we could have other crazy uses that are transitively
781 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
782 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
787 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
791 // If we nuked all of the loads, then none of the stores are needed either,
792 // nor is the global.
793 if (AllNonStoreUsesGone) {
794 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
795 CleanupConstantGlobalUsers(GV, 0);
796 if (GV->use_empty()) {
797 GV->eraseFromParent();
805 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
806 /// instructions that are foldable.
807 static void ConstantPropUsersOf(Value *V) {
808 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
809 if (Instruction *I = dyn_cast<Instruction>(*UI++))
810 if (Constant *NewC = ConstantFoldInstruction(I)) {
811 I->replaceAllUsesWith(NewC);
813 // Advance UI to the next non-I use to avoid invalidating it!
814 // Instructions could multiply use V.
815 while (UI != E && *UI == I)
817 I->eraseFromParent();
821 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
822 /// variable, and transforms the program as if it always contained the result of
823 /// the specified malloc. Because it is always the result of the specified
824 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
825 /// malloc into a global, and any loads of GV as uses of the new global.
826 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
829 ConstantInt *NElements,
831 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
833 const Type *GlobalType;
834 if (NElements->getZExtValue() == 1)
835 GlobalType = AllocTy;
837 // If we have an array allocation, the global variable is of an array.
838 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
840 // Create the new global variable. The contents of the malloc'd memory is
841 // undefined, so initialize with an undef value.
842 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
844 GlobalValue::InternalLinkage,
845 UndefValue::get(GlobalType),
846 GV->getName()+".body",
848 GV->isThreadLocal());
850 // If there are bitcast users of the malloc (which is typical, usually we have
851 // a malloc + bitcast) then replace them with uses of the new global. Update
852 // other users to use the global as well.
853 BitCastInst *TheBC = 0;
854 while (!CI->use_empty()) {
855 Instruction *User = cast<Instruction>(CI->use_back());
856 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
857 if (BCI->getType() == NewGV->getType()) {
858 BCI->replaceAllUsesWith(NewGV);
859 BCI->eraseFromParent();
861 BCI->setOperand(0, NewGV);
865 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
866 User->replaceUsesOfWith(CI, TheBC);
870 Constant *RepValue = NewGV;
871 if (NewGV->getType() != GV->getType()->getElementType())
872 RepValue = ConstantExpr::getBitCast(RepValue,
873 GV->getType()->getElementType());
875 // If there is a comparison against null, we will insert a global bool to
876 // keep track of whether the global was initialized yet or not.
877 GlobalVariable *InitBool =
878 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
879 GlobalValue::InternalLinkage,
880 ConstantInt::getFalse(GV->getContext()),
881 GV->getName()+".init", GV->isThreadLocal());
882 bool InitBoolUsed = false;
884 // Loop over all uses of GV, processing them in turn.
885 while (!GV->use_empty()) {
886 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
887 // The global is initialized when the store to it occurs.
888 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
889 SI->eraseFromParent();
893 LoadInst *LI = cast<LoadInst>(GV->use_back());
894 while (!LI->use_empty()) {
895 Use &LoadUse = LI->use_begin().getUse();
896 if (!isa<ICmpInst>(LoadUse.getUser())) {
901 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
902 // Replace the cmp X, 0 with a use of the bool value.
903 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
905 switch (ICI->getPredicate()) {
906 default: llvm_unreachable("Unknown ICmp Predicate!");
907 case ICmpInst::ICMP_ULT:
908 case ICmpInst::ICMP_SLT: // X < null -> always false
909 LV = ConstantInt::getFalse(GV->getContext());
911 case ICmpInst::ICMP_ULE:
912 case ICmpInst::ICMP_SLE:
913 case ICmpInst::ICMP_EQ:
914 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
916 case ICmpInst::ICMP_NE:
917 case ICmpInst::ICMP_UGE:
918 case ICmpInst::ICMP_SGE:
919 case ICmpInst::ICMP_UGT:
920 case ICmpInst::ICMP_SGT:
923 ICI->replaceAllUsesWith(LV);
924 ICI->eraseFromParent();
926 LI->eraseFromParent();
929 // If the initialization boolean was used, insert it, otherwise delete it.
931 while (!InitBool->use_empty()) // Delete initializations
932 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
935 GV->getParent()->getGlobalList().insert(GV, InitBool);
937 // Now the GV is dead, nuke it and the malloc..
938 GV->eraseFromParent();
939 CI->eraseFromParent();
941 // To further other optimizations, loop over all users of NewGV and try to
942 // constant prop them. This will promote GEP instructions with constant
943 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
944 ConstantPropUsersOf(NewGV);
945 if (RepValue != NewGV)
946 ConstantPropUsersOf(RepValue);
951 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
952 /// to make sure that there are no complex uses of V. We permit simple things
953 /// like dereferencing the pointer, but not storing through the address, unless
954 /// it is to the specified global.
955 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
956 const GlobalVariable *GV,
957 SmallPtrSet<const PHINode*, 8> &PHIs) {
958 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
960 const Instruction *Inst = cast<Instruction>(*UI);
962 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
963 continue; // Fine, ignore.
966 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
967 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
968 return false; // Storing the pointer itself... bad.
969 continue; // Otherwise, storing through it, or storing into GV... fine.
972 // Must index into the array and into the struct.
973 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
974 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
979 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
980 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
983 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
988 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
989 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
999 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1000 /// somewhere. Transform all uses of the allocation into loads from the
1001 /// global and uses of the resultant pointer. Further, delete the store into
1002 /// GV. This assumes that these value pass the
1003 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1004 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1005 GlobalVariable *GV) {
1006 while (!Alloc->use_empty()) {
1007 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1008 Instruction *InsertPt = U;
1009 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1010 // If this is the store of the allocation into the global, remove it.
1011 if (SI->getOperand(1) == GV) {
1012 SI->eraseFromParent();
1015 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1016 // Insert the load in the corresponding predecessor, not right before the
1018 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1019 } else if (isa<BitCastInst>(U)) {
1020 // Must be bitcast between the malloc and store to initialize the global.
1021 ReplaceUsesOfMallocWithGlobal(U, GV);
1022 U->eraseFromParent();
1024 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1025 // If this is a "GEP bitcast" and the user is a store to the global, then
1026 // just process it as a bitcast.
1027 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1028 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1029 if (SI->getOperand(1) == GV) {
1030 // Must be bitcast GEP between the malloc and store to initialize
1032 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1033 GEPI->eraseFromParent();
1038 // Insert a load from the global, and use it instead of the malloc.
1039 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1040 U->replaceUsesOfWith(Alloc, NL);
1044 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1045 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1046 /// that index through the array and struct field, icmps of null, and PHIs.
1047 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1048 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1049 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1050 // We permit two users of the load: setcc comparing against the null
1051 // pointer, and a getelementptr of a specific form.
1052 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1054 const Instruction *User = cast<Instruction>(*UI);
1056 // Comparison against null is ok.
1057 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1058 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1063 // getelementptr is also ok, but only a simple form.
1064 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1065 // Must index into the array and into the struct.
1066 if (GEPI->getNumOperands() < 3)
1069 // Otherwise the GEP is ok.
1073 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1074 if (!LoadUsingPHIsPerLoad.insert(PN))
1075 // This means some phi nodes are dependent on each other.
1076 // Avoid infinite looping!
1078 if (!LoadUsingPHIs.insert(PN))
1079 // If we have already analyzed this PHI, then it is safe.
1082 // Make sure all uses of the PHI are simple enough to transform.
1083 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1084 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1090 // Otherwise we don't know what this is, not ok.
1098 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1099 /// GV are simple enough to perform HeapSRA, return true.
1100 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1101 Instruction *StoredVal) {
1102 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1103 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1104 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1106 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1107 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1108 LoadUsingPHIsPerLoad))
1110 LoadUsingPHIsPerLoad.clear();
1113 // If we reach here, we know that all uses of the loads and transitive uses
1114 // (through PHI nodes) are simple enough to transform. However, we don't know
1115 // that all inputs the to the PHI nodes are in the same equivalence sets.
1116 // Check to verify that all operands of the PHIs are either PHIS that can be
1117 // transformed, loads from GV, or MI itself.
1118 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1119 , E = LoadUsingPHIs.end(); I != E; ++I) {
1120 const PHINode *PN = *I;
1121 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1122 Value *InVal = PN->getIncomingValue(op);
1124 // PHI of the stored value itself is ok.
1125 if (InVal == StoredVal) continue;
1127 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1128 // One of the PHIs in our set is (optimistically) ok.
1129 if (LoadUsingPHIs.count(InPN))
1134 // Load from GV is ok.
1135 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1136 if (LI->getOperand(0) == GV)
1141 // Anything else is rejected.
1149 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1150 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1151 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1152 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1154 if (FieldNo >= FieldVals.size())
1155 FieldVals.resize(FieldNo+1);
1157 // If we already have this value, just reuse the previously scalarized
1159 if (Value *FieldVal = FieldVals[FieldNo])
1162 // Depending on what instruction this is, we have several cases.
1164 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1165 // This is a scalarized version of the load from the global. Just create
1166 // a new Load of the scalarized global.
1167 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1168 InsertedScalarizedValues,
1170 LI->getName()+".f"+Twine(FieldNo), LI);
1171 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1172 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1174 const StructType *ST =
1175 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1178 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1179 PN->getName()+".f"+Twine(FieldNo), PN);
1180 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1182 llvm_unreachable("Unknown usable value");
1186 return FieldVals[FieldNo] = Result;
1189 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1190 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1191 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1192 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1193 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1194 // If this is a comparison against null, handle it.
1195 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1196 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1197 // If we have a setcc of the loaded pointer, we can use a setcc of any
1199 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1200 InsertedScalarizedValues, PHIsToRewrite);
1202 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1203 Constant::getNullValue(NPtr->getType()),
1205 SCI->replaceAllUsesWith(New);
1206 SCI->eraseFromParent();
1210 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1211 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1212 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1213 && "Unexpected GEPI!");
1215 // Load the pointer for this field.
1216 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1217 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1218 InsertedScalarizedValues, PHIsToRewrite);
1220 // Create the new GEP idx vector.
1221 SmallVector<Value*, 8> GEPIdx;
1222 GEPIdx.push_back(GEPI->getOperand(1));
1223 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1225 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1226 GEPIdx.begin(), GEPIdx.end(),
1227 GEPI->getName(), GEPI);
1228 GEPI->replaceAllUsesWith(NGEPI);
1229 GEPI->eraseFromParent();
1233 // Recursively transform the users of PHI nodes. This will lazily create the
1234 // PHIs that are needed for individual elements. Keep track of what PHIs we
1235 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1236 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1237 // already been seen first by another load, so its uses have already been
1239 PHINode *PN = cast<PHINode>(LoadUser);
1241 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1242 tie(InsertPos, Inserted) =
1243 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1244 if (!Inserted) return;
1246 // If this is the first time we've seen this PHI, recursively process all
1248 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1249 Instruction *User = cast<Instruction>(*UI++);
1250 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1254 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1255 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1256 /// use FieldGlobals instead. All uses of loaded values satisfy
1257 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1258 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1259 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1260 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1261 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1263 Instruction *User = cast<Instruction>(*UI++);
1264 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1267 if (Load->use_empty()) {
1268 Load->eraseFromParent();
1269 InsertedScalarizedValues.erase(Load);
1273 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1274 /// it up into multiple allocations of arrays of the fields.
1275 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1276 Value* NElems, TargetData *TD) {
1277 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1278 const Type* MAT = getMallocAllocatedType(CI);
1279 const StructType *STy = cast<StructType>(MAT);
1281 // There is guaranteed to be at least one use of the malloc (storing
1282 // it into GV). If there are other uses, change them to be uses of
1283 // the global to simplify later code. This also deletes the store
1285 ReplaceUsesOfMallocWithGlobal(CI, GV);
1287 // Okay, at this point, there are no users of the malloc. Insert N
1288 // new mallocs at the same place as CI, and N globals.
1289 std::vector<Value*> FieldGlobals;
1290 std::vector<Value*> FieldMallocs;
1292 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1293 const Type *FieldTy = STy->getElementType(FieldNo);
1294 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1296 GlobalVariable *NGV =
1297 new GlobalVariable(*GV->getParent(),
1298 PFieldTy, false, GlobalValue::InternalLinkage,
1299 Constant::getNullValue(PFieldTy),
1300 GV->getName() + ".f" + Twine(FieldNo), GV,
1301 GV->isThreadLocal());
1302 FieldGlobals.push_back(NGV);
1304 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1305 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
1306 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1307 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1308 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1309 ConstantInt::get(IntPtrTy, TypeSize),
1311 CI->getName() + ".f" + Twine(FieldNo));
1312 FieldMallocs.push_back(NMI);
1313 new StoreInst(NMI, NGV, CI);
1316 // The tricky aspect of this transformation is handling the case when malloc
1317 // fails. In the original code, malloc failing would set the result pointer
1318 // of malloc to null. In this case, some mallocs could succeed and others
1319 // could fail. As such, we emit code that looks like this:
1320 // F0 = malloc(field0)
1321 // F1 = malloc(field1)
1322 // F2 = malloc(field2)
1323 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1324 // if (F0) { free(F0); F0 = 0; }
1325 // if (F1) { free(F1); F1 = 0; }
1326 // if (F2) { free(F2); F2 = 0; }
1328 // The malloc can also fail if its argument is too large.
1329 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1330 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1331 ConstantZero, "isneg");
1332 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1333 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1334 Constant::getNullValue(FieldMallocs[i]->getType()),
1336 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1339 // Split the basic block at the old malloc.
1340 BasicBlock *OrigBB = CI->getParent();
1341 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1343 // Create the block to check the first condition. Put all these blocks at the
1344 // end of the function as they are unlikely to be executed.
1345 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1347 OrigBB->getParent());
1349 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1350 // branch on RunningOr.
1351 OrigBB->getTerminator()->eraseFromParent();
1352 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1354 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1355 // pointer, because some may be null while others are not.
1356 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1357 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1358 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1359 Constant::getNullValue(GVVal->getType()),
1361 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1362 OrigBB->getParent());
1363 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1364 OrigBB->getParent());
1365 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1368 // Fill in FreeBlock.
1369 CallInst::CreateFree(GVVal, BI);
1370 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1372 BranchInst::Create(NextBlock, FreeBlock);
1374 NullPtrBlock = NextBlock;
1377 BranchInst::Create(ContBB, NullPtrBlock);
1379 // CI is no longer needed, remove it.
1380 CI->eraseFromParent();
1382 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1383 /// update all uses of the load, keep track of what scalarized loads are
1384 /// inserted for a given load.
1385 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1386 InsertedScalarizedValues[GV] = FieldGlobals;
1388 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1390 // Okay, the malloc site is completely handled. All of the uses of GV are now
1391 // loads, and all uses of those loads are simple. Rewrite them to use loads
1392 // of the per-field globals instead.
1393 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1394 Instruction *User = cast<Instruction>(*UI++);
1396 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1397 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1401 // Must be a store of null.
1402 StoreInst *SI = cast<StoreInst>(User);
1403 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1404 "Unexpected heap-sra user!");
1406 // Insert a store of null into each global.
1407 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1408 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1409 Constant *Null = Constant::getNullValue(PT->getElementType());
1410 new StoreInst(Null, FieldGlobals[i], SI);
1412 // Erase the original store.
1413 SI->eraseFromParent();
1416 // While we have PHIs that are interesting to rewrite, do it.
1417 while (!PHIsToRewrite.empty()) {
1418 PHINode *PN = PHIsToRewrite.back().first;
1419 unsigned FieldNo = PHIsToRewrite.back().second;
1420 PHIsToRewrite.pop_back();
1421 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1422 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1424 // Add all the incoming values. This can materialize more phis.
1425 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1426 Value *InVal = PN->getIncomingValue(i);
1427 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1429 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1433 // Drop all inter-phi links and any loads that made it this far.
1434 for (DenseMap<Value*, std::vector<Value*> >::iterator
1435 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1437 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1438 PN->dropAllReferences();
1439 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1440 LI->dropAllReferences();
1443 // Delete all the phis and loads now that inter-references are dead.
1444 for (DenseMap<Value*, std::vector<Value*> >::iterator
1445 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1447 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1448 PN->eraseFromParent();
1449 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1450 LI->eraseFromParent();
1453 // The old global is now dead, remove it.
1454 GV->eraseFromParent();
1457 return cast<GlobalVariable>(FieldGlobals[0]);
1460 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1461 /// pointer global variable with a single value stored it that is a malloc or
1463 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1465 const Type *AllocTy,
1466 Module::global_iterator &GVI,
1471 // If this is a malloc of an abstract type, don't touch it.
1472 if (!AllocTy->isSized())
1475 // We can't optimize this global unless all uses of it are *known* to be
1476 // of the malloc value, not of the null initializer value (consider a use
1477 // that compares the global's value against zero to see if the malloc has
1478 // been reached). To do this, we check to see if all uses of the global
1479 // would trap if the global were null: this proves that they must all
1480 // happen after the malloc.
1481 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1484 // We can't optimize this if the malloc itself is used in a complex way,
1485 // for example, being stored into multiple globals. This allows the
1486 // malloc to be stored into the specified global, loaded setcc'd, and
1487 // GEP'd. These are all things we could transform to using the global
1489 SmallPtrSet<const PHINode*, 8> PHIs;
1490 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1493 // If we have a global that is only initialized with a fixed size malloc,
1494 // transform the program to use global memory instead of malloc'd memory.
1495 // This eliminates dynamic allocation, avoids an indirection accessing the
1496 // data, and exposes the resultant global to further GlobalOpt.
1497 // We cannot optimize the malloc if we cannot determine malloc array size.
1498 Value *NElems = getMallocArraySize(CI, TD, true);
1502 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1503 // Restrict this transformation to only working on small allocations
1504 // (2048 bytes currently), as we don't want to introduce a 16M global or
1506 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1507 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1511 // If the allocation is an array of structures, consider transforming this
1512 // into multiple malloc'd arrays, one for each field. This is basically
1513 // SRoA for malloc'd memory.
1515 // If this is an allocation of a fixed size array of structs, analyze as a
1516 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1517 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1518 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1519 AllocTy = AT->getElementType();
1521 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1525 // This the structure has an unreasonable number of fields, leave it
1527 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1528 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1530 // If this is a fixed size array, transform the Malloc to be an alloc of
1531 // structs. malloc [100 x struct],1 -> malloc struct, 100
1532 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1533 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1534 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1535 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1536 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1537 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1538 AllocSize, NumElements,
1540 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1541 CI->replaceAllUsesWith(Cast);
1542 CI->eraseFromParent();
1543 CI = dyn_cast<BitCastInst>(Malloc) ?
1544 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1547 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1554 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1555 // that only one value (besides its initializer) is ever stored to the global.
1556 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1557 Module::global_iterator &GVI,
1559 // Ignore no-op GEPs and bitcasts.
1560 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1562 // If we are dealing with a pointer global that is initialized to null and
1563 // only has one (non-null) value stored into it, then we can optimize any
1564 // users of the loaded value (often calls and loads) that would trap if the
1566 if (GV->getInitializer()->getType()->isPointerTy() &&
1567 GV->getInitializer()->isNullValue()) {
1568 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1569 if (GV->getInitializer()->getType() != SOVC->getType())
1571 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1573 // Optimize away any trapping uses of the loaded value.
1574 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1576 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1577 const Type* MallocType = getMallocAllocatedType(CI);
1578 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1587 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1588 /// two values ever stored into GV are its initializer and OtherVal. See if we
1589 /// can shrink the global into a boolean and select between the two values
1590 /// whenever it is used. This exposes the values to other scalar optimizations.
1591 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1592 const Type *GVElType = GV->getType()->getElementType();
1594 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1595 // an FP value, pointer or vector, don't do this optimization because a select
1596 // between them is very expensive and unlikely to lead to later
1597 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1598 // where v1 and v2 both require constant pool loads, a big loss.
1599 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1600 GVElType->isFloatingPointTy() ||
1601 GVElType->isPointerTy() || GVElType->isVectorTy())
1604 // Walk the use list of the global seeing if all the uses are load or store.
1605 // If there is anything else, bail out.
1606 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1607 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1610 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1612 // Create the new global, initializing it to false.
1613 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1615 GlobalValue::InternalLinkage,
1616 ConstantInt::getFalse(GV->getContext()),
1618 GV->isThreadLocal());
1619 GV->getParent()->getGlobalList().insert(GV, NewGV);
1621 Constant *InitVal = GV->getInitializer();
1622 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1623 "No reason to shrink to bool!");
1625 // If initialized to zero and storing one into the global, we can use a cast
1626 // instead of a select to synthesize the desired value.
1627 bool IsOneZero = false;
1628 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1629 IsOneZero = InitVal->isNullValue() && CI->isOne();
1631 while (!GV->use_empty()) {
1632 Instruction *UI = cast<Instruction>(GV->use_back());
1633 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1634 // Change the store into a boolean store.
1635 bool StoringOther = SI->getOperand(0) == OtherVal;
1636 // Only do this if we weren't storing a loaded value.
1638 if (StoringOther || SI->getOperand(0) == InitVal)
1639 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1642 // Otherwise, we are storing a previously loaded copy. To do this,
1643 // change the copy from copying the original value to just copying the
1645 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1647 // If we've already replaced the input, StoredVal will be a cast or
1648 // select instruction. If not, it will be a load of the original
1650 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1651 assert(LI->getOperand(0) == GV && "Not a copy!");
1652 // Insert a new load, to preserve the saved value.
1653 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1655 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1656 "This is not a form that we understand!");
1657 StoreVal = StoredVal->getOperand(0);
1658 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1661 new StoreInst(StoreVal, NewGV, SI);
1663 // Change the load into a load of bool then a select.
1664 LoadInst *LI = cast<LoadInst>(UI);
1665 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1668 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1670 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1672 LI->replaceAllUsesWith(NSI);
1674 UI->eraseFromParent();
1677 GV->eraseFromParent();
1682 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1683 /// it if possible. If we make a change, return true.
1684 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1685 Module::global_iterator &GVI) {
1686 SmallPtrSet<const PHINode*, 16> PHIUsers;
1688 GV->removeDeadConstantUsers();
1690 if (GV->use_empty()) {
1691 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1692 GV->eraseFromParent();
1697 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1699 DEBUG(dbgs() << "Global: " << *GV);
1700 DEBUG(dbgs() << " isLoaded = " << GS.isLoaded << "\n");
1701 DEBUG(dbgs() << " StoredType = ");
1702 switch (GS.StoredType) {
1703 case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1704 case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
1706 case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1707 case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
1709 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1710 DEBUG(dbgs() << " StoredOnceValue = " << *GS.StoredOnceValue << "\n");
1711 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1712 DEBUG(dbgs() << " AccessingFunction = "
1713 << GS.AccessingFunction->getName() << "\n");
1714 DEBUG(dbgs() << " HasMultipleAccessingFunctions = "
1715 << GS.HasMultipleAccessingFunctions << "\n");
1716 DEBUG(dbgs() << " HasNonInstructionUser = "
1717 << GS.HasNonInstructionUser<<"\n");
1718 DEBUG(dbgs() << "\n");
1721 // If this is a first class global and has only one accessing function
1722 // and this function is main (which we know is not recursive we can make
1723 // this global a local variable) we replace the global with a local alloca
1724 // in this function.
1726 // NOTE: It doesn't make sense to promote non single-value types since we
1727 // are just replacing static memory to stack memory.
1729 // If the global is in different address space, don't bring it to stack.
1730 if (!GS.HasMultipleAccessingFunctions &&
1731 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1732 GV->getType()->getElementType()->isSingleValueType() &&
1733 GS.AccessingFunction->getName() == "main" &&
1734 GS.AccessingFunction->hasExternalLinkage() &&
1735 GV->getType()->getAddressSpace() == 0) {
1736 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1737 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1738 ->getEntryBlock().begin());
1739 const Type* ElemTy = GV->getType()->getElementType();
1740 // FIXME: Pass Global's alignment when globals have alignment
1741 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1742 if (!isa<UndefValue>(GV->getInitializer()))
1743 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1745 GV->replaceAllUsesWith(Alloca);
1746 GV->eraseFromParent();
1751 // If the global is never loaded (but may be stored to), it is dead.
1754 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1756 // Delete any stores we can find to the global. We may not be able to
1757 // make it completely dead though.
1758 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1760 // If the global is dead now, delete it.
1761 if (GV->use_empty()) {
1762 GV->eraseFromParent();
1768 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1769 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1770 GV->setConstant(true);
1772 // Clean up any obviously simplifiable users now.
1773 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1775 // If the global is dead now, just nuke it.
1776 if (GV->use_empty()) {
1777 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1778 << "all users and delete global!\n");
1779 GV->eraseFromParent();
1785 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1786 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1787 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1788 GVI = FirstNewGV; // Don't skip the newly produced globals!
1791 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1792 // If the initial value for the global was an undef value, and if only
1793 // one other value was stored into it, we can just change the
1794 // initializer to be the stored value, then delete all stores to the
1795 // global. This allows us to mark it constant.
1796 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1797 if (isa<UndefValue>(GV->getInitializer())) {
1798 // Change the initial value here.
1799 GV->setInitializer(SOVConstant);
1801 // Clean up any obviously simplifiable users now.
1802 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1804 if (GV->use_empty()) {
1805 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1806 << "simplify all users and delete global!\n");
1807 GV->eraseFromParent();
1816 // Try to optimize globals based on the knowledge that only one value
1817 // (besides its initializer) is ever stored to the global.
1818 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1819 getAnalysisIfAvailable<TargetData>()))
1822 // Otherwise, if the global was not a boolean, we can shrink it to be a
1824 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1825 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1834 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1835 /// function, changing them to FastCC.
1836 static void ChangeCalleesToFastCall(Function *F) {
1837 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1838 CallSite User(cast<Instruction>(*UI));
1839 User.setCallingConv(CallingConv::Fast);
1843 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1844 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1845 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1848 // There can be only one.
1849 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1855 static void RemoveNestAttribute(Function *F) {
1856 F->setAttributes(StripNest(F->getAttributes()));
1857 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1858 CallSite User(cast<Instruction>(*UI));
1859 User.setAttributes(StripNest(User.getAttributes()));
1863 bool GlobalOpt::OptimizeFunctions(Module &M) {
1864 bool Changed = false;
1865 // Optimize functions.
1866 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1868 // Functions without names cannot be referenced outside this module.
1869 if (!F->hasName() && !F->isDeclaration())
1870 F->setLinkage(GlobalValue::InternalLinkage);
1871 F->removeDeadConstantUsers();
1872 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1873 F->eraseFromParent();
1876 } else if (F->hasLocalLinkage()) {
1877 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1878 !F->hasAddressTaken()) {
1879 // If this function has C calling conventions, is not a varargs
1880 // function, and is only called directly, promote it to use the Fast
1881 // calling convention.
1882 F->setCallingConv(CallingConv::Fast);
1883 ChangeCalleesToFastCall(F);
1888 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1889 !F->hasAddressTaken()) {
1890 // The function is not used by a trampoline intrinsic, so it is safe
1891 // to remove the 'nest' attribute.
1892 RemoveNestAttribute(F);
1901 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1902 bool Changed = false;
1903 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1905 GlobalVariable *GV = GVI++;
1906 // Global variables without names cannot be referenced outside this module.
1907 if (!GV->hasName() && !GV->isDeclaration())
1908 GV->setLinkage(GlobalValue::InternalLinkage);
1909 // Simplify the initializer.
1910 if (GV->hasInitializer())
1911 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1912 TargetData *TD = getAnalysisIfAvailable<TargetData>();
1913 Constant *New = ConstantFoldConstantExpression(CE, TD);
1914 if (New && New != CE)
1915 GV->setInitializer(New);
1917 // Do more involved optimizations if the global is internal.
1918 if (!GV->isConstant() && GV->hasLocalLinkage() &&
1919 GV->hasInitializer())
1920 Changed |= ProcessInternalGlobal(GV, GVI);
1925 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1926 /// initializers have an init priority of 65535.
1927 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1928 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1930 if (I->getName() == "llvm.global_ctors") {
1931 // Found it, verify it's an array of { int, void()* }.
1932 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1934 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1935 if (!STy || STy->getNumElements() != 2 ||
1936 !STy->getElementType(0)->isIntegerTy(32)) return 0;
1937 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1938 if (!PFTy) return 0;
1939 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1940 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1941 FTy->isVarArg() || FTy->getNumParams() != 0)
1944 // Verify that the initializer is simple enough for us to handle.
1945 if (!I->hasDefinitiveInitializer()) return 0;
1946 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1948 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1949 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
1950 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1953 // Must have a function or null ptr.
1954 if (!isa<Function>(CS->getOperand(1)))
1957 // Init priority must be standard.
1958 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1959 if (!CI || CI->getZExtValue() != 65535)
1970 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1971 /// return a list of the functions and null terminator as a vector.
1972 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1973 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1974 std::vector<Function*> Result;
1975 Result.reserve(CA->getNumOperands());
1976 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1977 ConstantStruct *CS = cast<ConstantStruct>(*i);
1978 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1983 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1984 /// specified array, returning the new global to use.
1985 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1986 const std::vector<Function*> &Ctors) {
1987 // If we made a change, reassemble the initializer list.
1988 std::vector<Constant*> CSVals;
1989 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
1990 CSVals.push_back(0);
1992 // Create the new init list.
1993 std::vector<Constant*> CAList;
1994 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1996 CSVals[1] = Ctors[i];
1998 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2000 const PointerType *PFTy = PointerType::getUnqual(FTy);
2001 CSVals[1] = Constant::getNullValue(PFTy);
2002 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2005 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
2008 // Create the array initializer.
2009 const Type *StructTy =
2010 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
2011 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2012 CAList.size()), CAList);
2014 // If we didn't change the number of elements, don't create a new GV.
2015 if (CA->getType() == GCL->getInitializer()->getType()) {
2016 GCL->setInitializer(CA);
2020 // Create the new global and insert it next to the existing list.
2021 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2022 GCL->getLinkage(), CA, "",
2023 GCL->isThreadLocal());
2024 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2027 // Nuke the old list, replacing any uses with the new one.
2028 if (!GCL->use_empty()) {
2030 if (V->getType() != GCL->getType())
2031 V = ConstantExpr::getBitCast(V, GCL->getType());
2032 GCL->replaceAllUsesWith(V);
2034 GCL->eraseFromParent();
2043 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
2045 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2046 Constant *R = ComputedValues[V];
2047 assert(R && "Reference to an uncomputed value!");
2051 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2052 /// enough for us to understand. In particular, if it is a cast of something,
2053 /// we punt. We basically just support direct accesses to globals and GEP's of
2054 /// globals. This should be kept up to date with CommitValueTo.
2055 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2056 // Conservatively, avoid aggregate types. This is because we don't
2057 // want to worry about them partially overlapping other stores.
2058 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2061 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2062 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2063 // external globals.
2064 return GV->hasDefinitiveInitializer();
2066 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2067 // Handle a constantexpr gep.
2068 if (CE->getOpcode() == Instruction::GetElementPtr &&
2069 isa<GlobalVariable>(CE->getOperand(0)) &&
2070 cast<GEPOperator>(CE)->isInBounds()) {
2071 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2072 // Do not allow weak/linkonce/dllimport/dllexport linkage or
2073 // external globals.
2074 if (!GV->hasDefinitiveInitializer())
2077 // The first index must be zero.
2078 ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
2079 if (!CI || !CI->isZero()) return false;
2081 // The remaining indices must be compile-time known integers within the
2082 // notional bounds of the corresponding static array types.
2083 if (!CE->isGEPWithNoNotionalOverIndexing())
2086 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2091 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2092 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2093 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2094 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2095 ConstantExpr *Addr, unsigned OpNo) {
2096 // Base case of the recursion.
2097 if (OpNo == Addr->getNumOperands()) {
2098 assert(Val->getType() == Init->getType() && "Type mismatch!");
2102 std::vector<Constant*> Elts;
2103 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2105 // Break up the constant into its elements.
2106 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2107 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2108 Elts.push_back(cast<Constant>(*i));
2109 } else if (isa<ConstantAggregateZero>(Init)) {
2110 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2111 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2112 } else if (isa<UndefValue>(Init)) {
2113 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2114 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2116 llvm_unreachable("This code is out of sync with "
2117 " ConstantFoldLoadThroughGEPConstantExpr");
2120 // Replace the element that we are supposed to.
2121 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2122 unsigned Idx = CU->getZExtValue();
2123 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2124 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2126 // Return the modified struct.
2127 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2130 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2131 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
2134 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2135 NumElts = ATy->getNumElements();
2137 NumElts = cast<VectorType>(InitTy)->getNumElements();
2140 // Break up the array into elements.
2141 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2142 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2143 Elts.push_back(cast<Constant>(*i));
2144 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2145 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2146 Elts.push_back(cast<Constant>(*i));
2147 } else if (isa<ConstantAggregateZero>(Init)) {
2148 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2150 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2151 " ConstantFoldLoadThroughGEPConstantExpr");
2152 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2155 assert(CI->getZExtValue() < NumElts);
2156 Elts[CI->getZExtValue()] =
2157 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2159 if (Init->getType()->isArrayTy())
2160 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2162 return ConstantVector::get(&Elts[0], Elts.size());
2166 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2167 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2168 static void CommitValueTo(Constant *Val, Constant *Addr) {
2169 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2170 assert(GV->hasInitializer());
2171 GV->setInitializer(Val);
2175 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2176 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2177 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2180 /// ComputeLoadResult - Return the value that would be computed by a load from
2181 /// P after the stores reflected by 'memory' have been performed. If we can't
2182 /// decide, return null.
2183 static Constant *ComputeLoadResult(Constant *P,
2184 const DenseMap<Constant*, Constant*> &Memory) {
2185 // If this memory location has been recently stored, use the stored value: it
2186 // is the most up-to-date.
2187 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2188 if (I != Memory.end()) return I->second;
2191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2192 if (GV->hasDefinitiveInitializer())
2193 return GV->getInitializer();
2197 // Handle a constantexpr getelementptr.
2198 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2199 if (CE->getOpcode() == Instruction::GetElementPtr &&
2200 isa<GlobalVariable>(CE->getOperand(0))) {
2201 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2202 if (GV->hasDefinitiveInitializer())
2203 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2206 return 0; // don't know how to evaluate.
2209 /// EvaluateFunction - Evaluate a call to function F, returning true if
2210 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2211 /// arguments for the function.
2212 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2213 const SmallVectorImpl<Constant*> &ActualArgs,
2214 std::vector<Function*> &CallStack,
2215 DenseMap<Constant*, Constant*> &MutatedMemory,
2216 std::vector<GlobalVariable*> &AllocaTmps) {
2217 // Check to see if this function is already executing (recursion). If so,
2218 // bail out. TODO: we might want to accept limited recursion.
2219 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2222 CallStack.push_back(F);
2224 /// Values - As we compute SSA register values, we store their contents here.
2225 DenseMap<Value*, Constant*> Values;
2227 // Initialize arguments to the incoming values specified.
2229 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2231 Values[AI] = ActualArgs[ArgNo];
2233 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2234 /// we can only evaluate any one basic block at most once. This set keeps
2235 /// track of what we have executed so we can detect recursive cases etc.
2236 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2238 // CurInst - The current instruction we're evaluating.
2239 BasicBlock::iterator CurInst = F->begin()->begin();
2241 // This is the main evaluation loop.
2243 Constant *InstResult = 0;
2245 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2246 if (SI->isVolatile()) return false; // no volatile accesses.
2247 Constant *Ptr = getVal(Values, SI->getOperand(1));
2248 if (!isSimpleEnoughPointerToCommit(Ptr))
2249 // If this is too complex for us to commit, reject it.
2251 Constant *Val = getVal(Values, SI->getOperand(0));
2252 MutatedMemory[Ptr] = Val;
2253 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2254 InstResult = ConstantExpr::get(BO->getOpcode(),
2255 getVal(Values, BO->getOperand(0)),
2256 getVal(Values, BO->getOperand(1)));
2257 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2258 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2259 getVal(Values, CI->getOperand(0)),
2260 getVal(Values, CI->getOperand(1)));
2261 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2262 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2263 getVal(Values, CI->getOperand(0)),
2265 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2266 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2267 getVal(Values, SI->getOperand(1)),
2268 getVal(Values, SI->getOperand(2)));
2269 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2270 Constant *P = getVal(Values, GEP->getOperand(0));
2271 SmallVector<Constant*, 8> GEPOps;
2272 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2274 GEPOps.push_back(getVal(Values, *i));
2275 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2276 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2277 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2278 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2279 if (LI->isVolatile()) return false; // no volatile accesses.
2280 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2282 if (InstResult == 0) return false; // Could not evaluate load.
2283 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2284 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2285 const Type *Ty = AI->getType()->getElementType();
2286 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2287 GlobalValue::InternalLinkage,
2288 UndefValue::get(Ty),
2290 InstResult = AllocaTmps.back();
2291 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2293 // Debug info can safely be ignored here.
2294 if (isa<DbgInfoIntrinsic>(CI)) {
2299 // Cannot handle inline asm.
2300 if (isa<InlineAsm>(CI->getCalledValue())) return false;
2302 // Resolve function pointers.
2303 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getCalledValue()));
2304 if (!Callee) return false; // Cannot resolve.
2306 SmallVector<Constant*, 8> Formals;
2308 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
2310 Formals.push_back(getVal(Values, *i));
2312 if (Callee->isDeclaration()) {
2313 // If this is a function we can constant fold, do it.
2314 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2321 if (Callee->getFunctionType()->isVarArg())
2325 // Execute the call, if successful, use the return value.
2326 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2327 MutatedMemory, AllocaTmps))
2329 InstResult = RetVal;
2331 } else if (isa<TerminatorInst>(CurInst)) {
2332 BasicBlock *NewBB = 0;
2333 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2334 if (BI->isUnconditional()) {
2335 NewBB = BI->getSuccessor(0);
2338 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2339 if (!Cond) return false; // Cannot determine.
2341 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2343 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2345 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2346 if (!Val) return false; // Cannot determine.
2347 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2348 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2349 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2350 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2351 NewBB = BA->getBasicBlock();
2353 return false; // Cannot determine.
2354 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2355 if (RI->getNumOperands())
2356 RetVal = getVal(Values, RI->getOperand(0));
2358 CallStack.pop_back(); // return from fn.
2359 return true; // We succeeded at evaluating this ctor!
2361 // invoke, unwind, unreachable.
2362 return false; // Cannot handle this terminator.
2365 // Okay, we succeeded in evaluating this control flow. See if we have
2366 // executed the new block before. If so, we have a looping function,
2367 // which we cannot evaluate in reasonable time.
2368 if (!ExecutedBlocks.insert(NewBB))
2369 return false; // looped!
2371 // Okay, we have never been in this block before. Check to see if there
2372 // are any PHI nodes. If so, evaluate them with information about where
2374 BasicBlock *OldBB = CurInst->getParent();
2375 CurInst = NewBB->begin();
2377 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2378 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2380 // Do NOT increment CurInst. We know that the terminator had no value.
2383 // Did not know how to evaluate this!
2387 if (!CurInst->use_empty())
2388 Values[CurInst] = InstResult;
2390 // Advance program counter.
2395 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2396 /// we can. Return true if we can, false otherwise.
2397 static bool EvaluateStaticConstructor(Function *F) {
2398 /// MutatedMemory - For each store we execute, we update this map. Loads
2399 /// check this to get the most up-to-date value. If evaluation is successful,
2400 /// this state is committed to the process.
2401 DenseMap<Constant*, Constant*> MutatedMemory;
2403 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2404 /// to represent its body. This vector is needed so we can delete the
2405 /// temporary globals when we are done.
2406 std::vector<GlobalVariable*> AllocaTmps;
2408 /// CallStack - This is used to detect recursion. In pathological situations
2409 /// we could hit exponential behavior, but at least there is nothing
2411 std::vector<Function*> CallStack;
2413 // Call the function.
2414 Constant *RetValDummy;
2415 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2416 SmallVector<Constant*, 0>(), CallStack,
2417 MutatedMemory, AllocaTmps);
2419 // We succeeded at evaluation: commit the result.
2420 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2421 << F->getName() << "' to " << MutatedMemory.size()
2423 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2424 E = MutatedMemory.end(); I != E; ++I)
2425 CommitValueTo(I->second, I->first);
2428 // At this point, we are done interpreting. If we created any 'alloca'
2429 // temporaries, release them now.
2430 while (!AllocaTmps.empty()) {
2431 GlobalVariable *Tmp = AllocaTmps.back();
2432 AllocaTmps.pop_back();
2434 // If there are still users of the alloca, the program is doing something
2435 // silly, e.g. storing the address of the alloca somewhere and using it
2436 // later. Since this is undefined, we'll just make it be null.
2437 if (!Tmp->use_empty())
2438 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2447 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2448 /// Return true if anything changed.
2449 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2450 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2451 bool MadeChange = false;
2452 if (Ctors.empty()) return false;
2454 // Loop over global ctors, optimizing them when we can.
2455 for (unsigned i = 0; i != Ctors.size(); ++i) {
2456 Function *F = Ctors[i];
2457 // Found a null terminator in the middle of the list, prune off the rest of
2460 if (i != Ctors.size()-1) {
2467 // We cannot simplify external ctor functions.
2468 if (F->empty()) continue;
2470 // If we can evaluate the ctor at compile time, do.
2471 if (EvaluateStaticConstructor(F)) {
2472 Ctors.erase(Ctors.begin()+i);
2475 ++NumCtorsEvaluated;
2480 if (!MadeChange) return false;
2482 GCL = InstallGlobalCtors(GCL, Ctors);
2486 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2487 bool Changed = false;
2489 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2491 Module::alias_iterator J = I++;
2492 // Aliases without names cannot be referenced outside this module.
2493 if (!J->hasName() && !J->isDeclaration())
2494 J->setLinkage(GlobalValue::InternalLinkage);
2495 // If the aliasee may change at link time, nothing can be done - bail out.
2496 if (J->mayBeOverridden())
2499 Constant *Aliasee = J->getAliasee();
2500 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2501 Target->removeDeadConstantUsers();
2502 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2504 // Make all users of the alias use the aliasee instead.
2505 if (!J->use_empty()) {
2506 J->replaceAllUsesWith(Aliasee);
2507 ++NumAliasesResolved;
2511 // If the alias is externally visible, we may still be able to simplify it.
2512 if (!J->hasLocalLinkage()) {
2513 // If the aliasee has internal linkage, give it the name and linkage
2514 // of the alias, and delete the alias. This turns:
2515 // define internal ... @f(...)
2516 // @a = alias ... @f
2518 // define ... @a(...)
2519 if (!Target->hasLocalLinkage())
2522 // Do not perform the transform if multiple aliases potentially target the
2523 // aliasee. This check also ensures that it is safe to replace the section
2524 // and other attributes of the aliasee with those of the alias.
2528 // Give the aliasee the name, linkage and other attributes of the alias.
2529 Target->takeName(J);
2530 Target->setLinkage(J->getLinkage());
2531 Target->GlobalValue::copyAttributesFrom(J);
2534 // Delete the alias.
2535 M.getAliasList().erase(J);
2536 ++NumAliasesRemoved;
2543 bool GlobalOpt::runOnModule(Module &M) {
2544 bool Changed = false;
2546 // Try to find the llvm.globalctors list.
2547 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2549 bool LocalChange = true;
2550 while (LocalChange) {
2551 LocalChange = false;
2553 // Delete functions that are trivially dead, ccc -> fastcc
2554 LocalChange |= OptimizeFunctions(M);
2556 // Optimize global_ctors list.
2558 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2560 // Optimize non-address-taken globals.
2561 LocalChange |= OptimizeGlobalVars(M);
2563 // Resolve aliases, when possible.
2564 LocalChange |= OptimizeGlobalAliases(M);
2565 Changed |= LocalChange;
2568 // TODO: Move all global ctors functions to the end of the module for code