1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms simple global variables that never have their address
11 // taken. If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Support/CallSite.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/STLExtras.h"
41 STATISTIC(NumMarked , "Number of globals marked constant");
42 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
43 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
44 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
45 STATISTIC(NumDeleted , "Number of globals deleted");
46 STATISTIC(NumFnDeleted , "Number of functions deleted");
47 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
48 STATISTIC(NumLocalized , "Number of globals localized");
49 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
50 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
51 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
52 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
53 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
54 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
57 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired<TargetData>();
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 ResolveAliases(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.
86 struct VISIBILITY_HIDDEN GlobalStatus {
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 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 /// ConstantIsDead - Return true if the specified constant is (transitively)
140 /// dead. The constant may be used by other constants (e.g. constant arrays and
141 /// constant exprs) as long as they are dead, but it cannot be used by anything
143 static bool ConstantIsDead(Constant *C) {
144 if (isa<GlobalValue>(C)) return false;
146 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
147 if (Constant *CU = dyn_cast<Constant>(*UI)) {
148 if (!ConstantIsDead(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(Value *V, GlobalStatus &GS,
160 SmallPtrSet<PHINode*, 16> &PHIUsers) {
161 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
162 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
163 GS.HasNonInstructionUser = true;
165 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
167 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
168 if (!GS.HasMultipleAccessingFunctions) {
169 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 (LoadInst *LI = dyn_cast<LoadInst>(I)) {
177 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
178 } else if (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 (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) {
196 if (GS.StoredType < GlobalStatus::isInitializerStored)
197 GS.StoredType = GlobalStatus::isInitializerStored;
198 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
199 GS.StoredType = GlobalStatus::isStoredOnce;
200 GS.StoredOnceValue = StoredVal;
201 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
202 GS.StoredOnceValue == StoredVal) {
205 GS.StoredType = GlobalStatus::isStored;
208 GS.StoredType = GlobalStatus::isStored;
211 } else if (isa<GetElementPtrInst>(I)) {
212 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
213 } else if (isa<SelectInst>(I)) {
214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
215 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
216 // PHI nodes we can check just like select or GEP instructions, but we
217 // have to be careful about infinite recursion.
218 if (PHIUsers.insert(PN)) // Not already visited.
219 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
220 GS.HasPHIUser = true;
221 } else if (isa<CmpInst>(I)) {
222 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
223 if (I->getOperand(1) == V)
224 GS.StoredType = GlobalStatus::isStored;
225 if (I->getOperand(2) == V)
227 } else if (isa<MemSetInst>(I)) {
228 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
229 GS.StoredType = GlobalStatus::isStored;
231 return true; // Any other non-load instruction might take address!
233 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
234 GS.HasNonInstructionUser = true;
235 // We might have a dead and dangling constant hanging off of here.
236 if (!ConstantIsDead(C))
239 GS.HasNonInstructionUser = true;
240 // Otherwise must be some other user.
247 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
248 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
250 unsigned IdxV = CI->getZExtValue();
252 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
253 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
254 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
255 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
256 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
257 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
258 } else if (isa<ConstantAggregateZero>(Agg)) {
259 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
260 if (IdxV < STy->getNumElements())
261 return Constant::getNullValue(STy->getElementType(IdxV));
262 } else if (const SequentialType *STy =
263 dyn_cast<SequentialType>(Agg->getType())) {
264 return Constant::getNullValue(STy->getElementType());
266 } else if (isa<UndefValue>(Agg)) {
267 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
268 if (IdxV < STy->getNumElements())
269 return UndefValue::get(STy->getElementType(IdxV));
270 } else if (const SequentialType *STy =
271 dyn_cast<SequentialType>(Agg->getType())) {
272 return UndefValue::get(STy->getElementType());
279 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
280 /// users of the global, cleaning up the obvious ones. This is largely just a
281 /// quick scan over the use list to clean up the easy and obvious cruft. This
282 /// returns true if it made a change.
283 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
284 bool Changed = false;
285 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
288 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
290 // Replace the load with the initializer.
291 LI->replaceAllUsesWith(Init);
292 LI->eraseFromParent();
295 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
296 // Store must be unreachable or storing Init into the global.
297 SI->eraseFromParent();
299 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
300 if (CE->getOpcode() == Instruction::GetElementPtr) {
301 Constant *SubInit = 0;
303 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
304 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
305 } else if (CE->getOpcode() == Instruction::BitCast &&
306 isa<PointerType>(CE->getType())) {
307 // Pointer cast, delete any stores and memsets to the global.
308 Changed |= CleanupConstantGlobalUsers(CE, 0);
311 if (CE->use_empty()) {
312 CE->destroyConstant();
315 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
316 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
317 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
318 // and will invalidate our notion of what Init is.
319 Constant *SubInit = 0;
320 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
322 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
323 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
324 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
326 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
328 if (GEP->use_empty()) {
329 GEP->eraseFromParent();
332 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
333 if (MI->getRawDest() == V) {
334 MI->eraseFromParent();
338 } else if (Constant *C = dyn_cast<Constant>(U)) {
339 // If we have a chain of dead constantexprs or other things dangling from
340 // us, and if they are all dead, nuke them without remorse.
341 if (ConstantIsDead(C)) {
342 C->destroyConstant();
343 // This could have invalidated UI, start over from scratch.
344 CleanupConstantGlobalUsers(V, Init);
352 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
353 /// user of a derived expression from a global that we want to SROA.
354 static bool isSafeSROAElementUse(Value *V) {
355 // We might have a dead and dangling constant hanging off of here.
356 if (Constant *C = dyn_cast<Constant>(V))
357 return ConstantIsDead(C);
359 Instruction *I = dyn_cast<Instruction>(V);
360 if (!I) return false;
363 if (isa<LoadInst>(I)) return true;
365 // Stores *to* the pointer are ok.
366 if (StoreInst *SI = dyn_cast<StoreInst>(I))
367 return SI->getOperand(0) != V;
369 // Otherwise, it must be a GEP.
370 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
371 if (GEPI == 0) return false;
373 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
374 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
377 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
379 if (!isSafeSROAElementUse(*I))
385 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
386 /// Look at it and its uses and decide whether it is safe to SROA this global.
388 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
389 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
390 if (!isa<GetElementPtrInst>(U) &&
391 (!isa<ConstantExpr>(U) ||
392 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
395 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
396 // don't like < 3 operand CE's, and we don't like non-constant integer
397 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
399 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
400 !cast<Constant>(U->getOperand(1))->isNullValue() ||
401 !isa<ConstantInt>(U->getOperand(2)))
404 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
405 ++GEPI; // Skip over the pointer index.
407 // If this is a use of an array allocation, do a bit more checking for sanity.
408 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
409 uint64_t NumElements = AT->getNumElements();
410 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
412 // Check to make sure that index falls within the array. If not,
413 // something funny is going on, so we won't do the optimization.
415 if (Idx->getZExtValue() >= NumElements)
418 // We cannot scalar repl this level of the array unless any array
419 // sub-indices are in-range constants. In particular, consider:
420 // A[0][i]. We cannot know that the user isn't doing invalid things like
421 // allowing i to index an out-of-range subscript that accesses A[1].
423 // Scalar replacing *just* the outer index of the array is probably not
424 // going to be a win anyway, so just give up.
425 for (++GEPI; // Skip array index.
426 GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
428 uint64_t NumElements;
429 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
430 NumElements = SubArrayTy->getNumElements();
432 NumElements = cast<VectorType>(*GEPI)->getNumElements();
434 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
435 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
440 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
441 if (!isSafeSROAElementUse(*I))
446 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
447 /// is safe for us to perform this transformation.
449 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
450 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
452 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
459 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
460 /// variable. This opens the door for other optimizations by exposing the
461 /// behavior of the program in a more fine-grained way. We have determined that
462 /// this transformation is safe already. We return the first global variable we
463 /// insert so that the caller can reprocess it.
464 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
465 // Make sure this global only has simple uses that we can SRA.
466 if (!GlobalUsersSafeToSRA(GV))
469 assert(GV->hasLocalLinkage() && !GV->isConstant());
470 Constant *Init = GV->getInitializer();
471 const Type *Ty = Init->getType();
473 std::vector<GlobalVariable*> NewGlobals;
474 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
476 // Get the alignment of the global, either explicit or target-specific.
477 unsigned StartAlignment = GV->getAlignment();
478 if (StartAlignment == 0)
479 StartAlignment = TD.getABITypeAlignment(GV->getType());
481 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
482 NewGlobals.reserve(STy->getNumElements());
483 const StructLayout &Layout = *TD.getStructLayout(STy);
484 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
485 Constant *In = getAggregateConstantElement(Init,
486 ConstantInt::get(Type::Int32Ty, i));
487 assert(In && "Couldn't get element of initializer?");
488 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
489 GlobalVariable::InternalLinkage,
490 In, GV->getName()+"."+utostr(i),
493 GV->getType()->getAddressSpace());
494 Globals.insert(GV, NGV);
495 NewGlobals.push_back(NGV);
497 // Calculate the known alignment of the field. If the original aggregate
498 // had 256 byte alignment for example, something might depend on that:
499 // propagate info to each field.
500 uint64_t FieldOffset = Layout.getElementOffset(i);
501 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
502 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
503 NGV->setAlignment(NewAlign);
505 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
506 unsigned NumElements = 0;
507 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
508 NumElements = ATy->getNumElements();
510 NumElements = cast<VectorType>(STy)->getNumElements();
512 if (NumElements > 16 && GV->hasNUsesOrMore(16))
513 return 0; // It's not worth it.
514 NewGlobals.reserve(NumElements);
516 uint64_t EltSize = TD.getTypePaddedSize(STy->getElementType());
517 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
518 for (unsigned i = 0, e = NumElements; i != e; ++i) {
519 Constant *In = getAggregateConstantElement(Init,
520 ConstantInt::get(Type::Int32Ty, i));
521 assert(In && "Couldn't get element of initializer?");
523 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
524 GlobalVariable::InternalLinkage,
525 In, GV->getName()+"."+utostr(i),
528 GV->getType()->getAddressSpace());
529 Globals.insert(GV, NGV);
530 NewGlobals.push_back(NGV);
532 // Calculate the known alignment of the field. If the original aggregate
533 // had 256 byte alignment for example, something might depend on that:
534 // propagate info to each field.
535 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
536 if (NewAlign > EltAlign)
537 NGV->setAlignment(NewAlign);
541 if (NewGlobals.empty())
544 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
546 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
548 // Loop over all of the uses of the global, replacing the constantexpr geps,
549 // with smaller constantexpr geps or direct references.
550 while (!GV->use_empty()) {
551 User *GEP = GV->use_back();
552 assert(((isa<ConstantExpr>(GEP) &&
553 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
554 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
556 // Ignore the 1th operand, which has to be zero or else the program is quite
557 // broken (undefined). Get the 2nd operand, which is the structure or array
559 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
560 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
562 Value *NewPtr = NewGlobals[Val];
564 // Form a shorter GEP if needed.
565 if (GEP->getNumOperands() > 3) {
566 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
567 SmallVector<Constant*, 8> Idxs;
568 Idxs.push_back(NullInt);
569 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
570 Idxs.push_back(CE->getOperand(i));
571 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
572 &Idxs[0], Idxs.size());
574 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
575 SmallVector<Value*, 8> Idxs;
576 Idxs.push_back(NullInt);
577 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
578 Idxs.push_back(GEPI->getOperand(i));
579 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
580 GEPI->getName()+"."+utostr(Val), GEPI);
583 GEP->replaceAllUsesWith(NewPtr);
585 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
586 GEPI->eraseFromParent();
588 cast<ConstantExpr>(GEP)->destroyConstant();
591 // Delete the old global, now that it is dead.
595 // Loop over the new globals array deleting any globals that are obviously
596 // dead. This can arise due to scalarization of a structure or an array that
597 // has elements that are dead.
598 unsigned FirstGlobal = 0;
599 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
600 if (NewGlobals[i]->use_empty()) {
601 Globals.erase(NewGlobals[i]);
602 if (FirstGlobal == i) ++FirstGlobal;
605 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
608 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
609 /// value will trap if the value is dynamically null. PHIs keeps track of any
610 /// phi nodes we've seen to avoid reprocessing them.
611 static bool AllUsesOfValueWillTrapIfNull(Value *V,
612 SmallPtrSet<PHINode*, 8> &PHIs) {
613 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
614 if (isa<LoadInst>(*UI)) {
616 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
617 if (SI->getOperand(0) == V) {
618 //cerr << "NONTRAPPING USE: " << **UI;
619 return false; // Storing the value.
621 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
622 if (CI->getOperand(0) != V) {
623 //cerr << "NONTRAPPING USE: " << **UI;
624 return false; // Not calling the ptr
626 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
627 if (II->getOperand(0) != V) {
628 //cerr << "NONTRAPPING USE: " << **UI;
629 return false; // Not calling the ptr
631 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
632 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
633 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
634 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
635 } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
636 // If we've already seen this phi node, ignore it, it has already been
639 return AllUsesOfValueWillTrapIfNull(PN, PHIs);
640 } else if (isa<ICmpInst>(*UI) &&
641 isa<ConstantPointerNull>(UI->getOperand(1))) {
642 // Ignore setcc X, null
644 //cerr << "NONTRAPPING USE: " << **UI;
650 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
651 /// from GV will trap if the loaded value is null. Note that this also permits
652 /// comparisons of the loaded value against null, as a special case.
653 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
654 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
655 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
656 SmallPtrSet<PHINode*, 8> PHIs;
657 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
659 } else if (isa<StoreInst>(*UI)) {
660 // Ignore stores to the global.
662 // We don't know or understand this user, bail out.
663 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
670 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
671 bool Changed = false;
672 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
673 Instruction *I = cast<Instruction>(*UI++);
674 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
675 LI->setOperand(0, NewV);
677 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
678 if (SI->getOperand(1) == V) {
679 SI->setOperand(1, NewV);
682 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
683 if (I->getOperand(0) == V) {
684 // Calling through the pointer! Turn into a direct call, but be careful
685 // that the pointer is not also being passed as an argument.
686 I->setOperand(0, NewV);
688 bool PassedAsArg = false;
689 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
690 if (I->getOperand(i) == V) {
692 I->setOperand(i, NewV);
696 // Being passed as an argument also. Be careful to not invalidate UI!
700 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
701 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
702 ConstantExpr::getCast(CI->getOpcode(),
703 NewV, CI->getType()));
704 if (CI->use_empty()) {
706 CI->eraseFromParent();
708 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
709 // Should handle GEP here.
710 SmallVector<Constant*, 8> Idxs;
711 Idxs.reserve(GEPI->getNumOperands()-1);
712 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
714 if (Constant *C = dyn_cast<Constant>(*i))
718 if (Idxs.size() == GEPI->getNumOperands()-1)
719 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
720 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
722 if (GEPI->use_empty()) {
724 GEPI->eraseFromParent();
733 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
734 /// value stored into it. If there are uses of the loaded value that would trap
735 /// if the loaded value is dynamically null, then we know that they cannot be
736 /// reachable with a null optimize away the load.
737 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
738 bool Changed = false;
740 // Keep track of whether we are able to remove all the uses of the global
741 // other than the store that defines it.
742 bool AllNonStoreUsesGone = true;
744 // Replace all uses of loads with uses of uses of the stored value.
745 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
746 User *GlobalUser = *GUI++;
747 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
748 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
749 // If we were able to delete all uses of the loads
750 if (LI->use_empty()) {
751 LI->eraseFromParent();
754 AllNonStoreUsesGone = false;
756 } else if (isa<StoreInst>(GlobalUser)) {
757 // Ignore the store that stores "LV" to the global.
758 assert(GlobalUser->getOperand(1) == GV &&
759 "Must be storing *to* the global");
761 AllNonStoreUsesGone = false;
763 // If we get here we could have other crazy uses that are transitively
765 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
766 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
771 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
775 // If we nuked all of the loads, then none of the stores are needed either,
776 // nor is the global.
777 if (AllNonStoreUsesGone) {
778 DOUT << " *** GLOBAL NOW DEAD!\n";
779 CleanupConstantGlobalUsers(GV, 0);
780 if (GV->use_empty()) {
781 GV->eraseFromParent();
789 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
790 /// instructions that are foldable.
791 static void ConstantPropUsersOf(Value *V) {
792 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
793 if (Instruction *I = dyn_cast<Instruction>(*UI++))
794 if (Constant *NewC = ConstantFoldInstruction(I)) {
795 I->replaceAllUsesWith(NewC);
797 // Advance UI to the next non-I use to avoid invalidating it!
798 // Instructions could multiply use V.
799 while (UI != E && *UI == I)
801 I->eraseFromParent();
805 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
806 /// variable, and transforms the program as if it always contained the result of
807 /// the specified malloc. Because it is always the result of the specified
808 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
809 /// malloc into a global, and any loads of GV as uses of the new global.
810 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
812 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
813 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
815 if (NElements->getZExtValue() != 1) {
816 // If we have an array allocation, transform it to a single element
817 // allocation to make the code below simpler.
818 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
819 NElements->getZExtValue());
821 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
822 MI->getAlignment(), MI->getName(), MI);
824 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
825 Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
826 NewMI->getName()+".el0", MI);
827 MI->replaceAllUsesWith(NewGEP);
828 MI->eraseFromParent();
832 // Create the new global variable. The contents of the malloc'd memory is
833 // undefined, so initialize with an undef value.
834 Constant *Init = UndefValue::get(MI->getAllocatedType());
835 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
836 GlobalValue::InternalLinkage, Init,
837 GV->getName()+".body",
839 GV->isThreadLocal());
840 // FIXME: This new global should have the alignment returned by malloc. Code
841 // could depend on malloc returning large alignment (on the mac, 16 bytes) but
842 // this would only guarantee some lower alignment.
843 GV->getParent()->getGlobalList().insert(GV, NewGV);
845 // Anything that used the malloc now uses the global directly.
846 MI->replaceAllUsesWith(NewGV);
848 Constant *RepValue = NewGV;
849 if (NewGV->getType() != GV->getType()->getElementType())
850 RepValue = ConstantExpr::getBitCast(RepValue,
851 GV->getType()->getElementType());
853 // If there is a comparison against null, we will insert a global bool to
854 // keep track of whether the global was initialized yet or not.
855 GlobalVariable *InitBool =
856 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
857 ConstantInt::getFalse(), GV->getName()+".init",
858 (Module *)NULL, GV->isThreadLocal());
859 bool InitBoolUsed = false;
861 // Loop over all uses of GV, processing them in turn.
862 std::vector<StoreInst*> Stores;
863 while (!GV->use_empty())
864 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
865 while (!LI->use_empty()) {
866 Use &LoadUse = LI->use_begin().getUse();
867 if (!isa<ICmpInst>(LoadUse.getUser()))
870 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
871 // Replace the cmp X, 0 with a use of the bool value.
872 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
874 switch (CI->getPredicate()) {
875 default: assert(0 && "Unknown ICmp Predicate!");
876 case ICmpInst::ICMP_ULT:
877 case ICmpInst::ICMP_SLT:
878 LV = ConstantInt::getFalse(); // X < null -> always false
880 case ICmpInst::ICMP_ULE:
881 case ICmpInst::ICMP_SLE:
882 case ICmpInst::ICMP_EQ:
883 LV = BinaryOperator::CreateNot(LV, "notinit", CI);
885 case ICmpInst::ICMP_NE:
886 case ICmpInst::ICMP_UGE:
887 case ICmpInst::ICMP_SGE:
888 case ICmpInst::ICMP_UGT:
889 case ICmpInst::ICMP_SGT:
892 CI->replaceAllUsesWith(LV);
893 CI->eraseFromParent();
896 LI->eraseFromParent();
898 StoreInst *SI = cast<StoreInst>(GV->use_back());
899 // The global is initialized when the store to it occurs.
900 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
901 SI->eraseFromParent();
904 // If the initialization boolean was used, insert it, otherwise delete it.
906 while (!InitBool->use_empty()) // Delete initializations
907 cast<Instruction>(InitBool->use_back())->eraseFromParent();
910 GV->getParent()->getGlobalList().insert(GV, InitBool);
913 // Now the GV is dead, nuke it and the malloc.
914 GV->eraseFromParent();
915 MI->eraseFromParent();
917 // To further other optimizations, loop over all users of NewGV and try to
918 // constant prop them. This will promote GEP instructions with constant
919 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
920 ConstantPropUsersOf(NewGV);
921 if (RepValue != NewGV)
922 ConstantPropUsersOf(RepValue);
927 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
928 /// to make sure that there are no complex uses of V. We permit simple things
929 /// like dereferencing the pointer, but not storing through the address, unless
930 /// it is to the specified global.
931 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
933 SmallPtrSet<PHINode*, 8> &PHIs) {
934 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
935 Instruction *Inst = dyn_cast<Instruction>(*UI);
936 if (Inst == 0) return false;
938 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
939 continue; // Fine, ignore.
942 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
943 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
944 return false; // Storing the pointer itself... bad.
945 continue; // Otherwise, storing through it, or storing into GV... fine.
948 if (isa<GetElementPtrInst>(Inst)) {
949 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
954 if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
955 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
958 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
963 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
964 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
974 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
975 /// somewhere. Transform all uses of the allocation into loads from the
976 /// global and uses of the resultant pointer. Further, delete the store into
977 /// GV. This assumes that these value pass the
978 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
979 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
980 GlobalVariable *GV) {
981 while (!Alloc->use_empty()) {
982 Instruction *U = cast<Instruction>(*Alloc->use_begin());
983 Instruction *InsertPt = U;
984 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
985 // If this is the store of the allocation into the global, remove it.
986 if (SI->getOperand(1) == GV) {
987 SI->eraseFromParent();
990 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
991 // Insert the load in the corresponding predecessor, not right before the
993 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
994 } else if (isa<BitCastInst>(U)) {
995 // Must be bitcast between the malloc and store to initialize the global.
996 ReplaceUsesOfMallocWithGlobal(U, GV);
997 U->eraseFromParent();
999 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1000 // If this is a "GEP bitcast" and the user is a store to the global, then
1001 // just process it as a bitcast.
1002 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1003 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1004 if (SI->getOperand(1) == GV) {
1005 // Must be bitcast GEP between the malloc and store to initialize
1007 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1008 GEPI->eraseFromParent();
1013 // Insert a load from the global, and use it instead of the malloc.
1014 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1015 U->replaceUsesOfWith(Alloc, NL);
1019 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1020 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1021 /// that index through the array and struct field, icmps of null, and PHIs.
1022 static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
1023 SmallPtrSet<PHINode*, 32> &LoadUsingPHIs) {
1024 // We permit two users of the load: setcc comparing against the null
1025 // pointer, and a getelementptr of a specific form.
1026 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1027 Instruction *User = cast<Instruction>(*UI);
1029 // Comparison against null is ok.
1030 if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1031 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1036 // getelementptr is also ok, but only a simple form.
1037 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1038 // Must index into the array and into the struct.
1039 if (GEPI->getNumOperands() < 3)
1042 // Otherwise the GEP is ok.
1046 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1047 // If we have already recursively analyzed this PHI, then it is safe.
1048 if (LoadUsingPHIs.insert(PN))
1051 // Make sure all uses of the PHI are simple enough to transform.
1052 if (!LoadUsesSimpleEnoughForHeapSRA(PN, LoadUsingPHIs))
1058 // Otherwise we don't know what this is, not ok.
1066 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1067 /// GV are simple enough to perform HeapSRA, return true.
1068 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
1070 SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
1071 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
1073 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1074 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs))
1077 // If we reach here, we know that all uses of the loads and transitive uses
1078 // (through PHI nodes) are simple enough to transform. However, we don't know
1079 // that all inputs the to the PHI nodes are in the same equivalence sets.
1080 // Check to verify that all operands of the PHIs are either PHIS that can be
1081 // transformed, loads from GV, or MI itself.
1082 for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
1083 E = LoadUsingPHIs.end(); I != E; ++I) {
1085 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1086 Value *InVal = PN->getIncomingValue(op);
1088 // PHI of the stored value itself is ok.
1089 if (InVal == MI) continue;
1091 if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1092 // One of the PHIs in our set is (optimistically) ok.
1093 if (LoadUsingPHIs.count(InPN))
1098 // Load from GV is ok.
1099 if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
1100 if (LI->getOperand(0) == GV)
1105 // Anything else is rejected.
1113 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1114 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1115 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1116 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1118 if (FieldNo >= FieldVals.size())
1119 FieldVals.resize(FieldNo+1);
1121 // If we already have this value, just reuse the previously scalarized
1123 if (Value *FieldVal = FieldVals[FieldNo])
1126 // Depending on what instruction this is, we have several cases.
1128 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1129 // This is a scalarized version of the load from the global. Just create
1130 // a new Load of the scalarized global.
1131 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1132 InsertedScalarizedValues,
1134 LI->getName()+".f" + utostr(FieldNo), LI);
1135 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1136 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1138 const StructType *ST =
1139 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1141 Result =PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1142 PN->getName()+".f"+utostr(FieldNo), PN);
1143 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1145 assert(0 && "Unknown usable value");
1149 return FieldVals[FieldNo] = Result;
1152 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1153 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1154 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1155 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1156 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1157 // If this is a comparison against null, handle it.
1158 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1159 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1160 // If we have a setcc of the loaded pointer, we can use a setcc of any
1162 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1163 InsertedScalarizedValues, PHIsToRewrite);
1165 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
1166 Constant::getNullValue(NPtr->getType()),
1167 SCI->getName(), SCI);
1168 SCI->replaceAllUsesWith(New);
1169 SCI->eraseFromParent();
1173 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1174 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1175 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1176 && "Unexpected GEPI!");
1178 // Load the pointer for this field.
1179 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1180 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1181 InsertedScalarizedValues, PHIsToRewrite);
1183 // Create the new GEP idx vector.
1184 SmallVector<Value*, 8> GEPIdx;
1185 GEPIdx.push_back(GEPI->getOperand(1));
1186 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1188 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1189 GEPIdx.begin(), GEPIdx.end(),
1190 GEPI->getName(), GEPI);
1191 GEPI->replaceAllUsesWith(NGEPI);
1192 GEPI->eraseFromParent();
1196 // Recursively transform the users of PHI nodes. This will lazily create the
1197 // PHIs that are needed for individual elements. Keep track of what PHIs we
1198 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1199 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1200 // already been seen first by another load, so its uses have already been
1202 PHINode *PN = cast<PHINode>(LoadUser);
1204 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1205 tie(InsertPos, Inserted) =
1206 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1207 if (!Inserted) return;
1209 // If this is the first time we've seen this PHI, recursively process all
1211 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1212 Instruction *User = cast<Instruction>(*UI++);
1213 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1217 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1218 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1219 /// use FieldGlobals instead. All uses of loaded values satisfy
1220 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1221 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1222 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1223 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1224 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1226 Instruction *User = cast<Instruction>(*UI++);
1227 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1230 if (Load->use_empty()) {
1231 Load->eraseFromParent();
1232 InsertedScalarizedValues.erase(Load);
1236 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
1237 /// it up into multiple allocations of arrays of the fields.
1238 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
1239 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
1240 const StructType *STy = cast<StructType>(MI->getAllocatedType());
1242 // There is guaranteed to be at least one use of the malloc (storing
1243 // it into GV). If there are other uses, change them to be uses of
1244 // the global to simplify later code. This also deletes the store
1246 ReplaceUsesOfMallocWithGlobal(MI, GV);
1248 // Okay, at this point, there are no users of the malloc. Insert N
1249 // new mallocs at the same place as MI, and N globals.
1250 std::vector<Value*> FieldGlobals;
1251 std::vector<MallocInst*> FieldMallocs;
1253 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1254 const Type *FieldTy = STy->getElementType(FieldNo);
1255 const Type *PFieldTy = PointerType::getUnqual(FieldTy);
1257 GlobalVariable *NGV =
1258 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
1259 Constant::getNullValue(PFieldTy),
1260 GV->getName() + ".f" + utostr(FieldNo), GV,
1261 GV->isThreadLocal());
1262 FieldGlobals.push_back(NGV);
1264 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
1265 MI->getName() + ".f" + utostr(FieldNo),MI);
1266 FieldMallocs.push_back(NMI);
1267 new StoreInst(NMI, NGV, MI);
1270 // The tricky aspect of this transformation is handling the case when malloc
1271 // fails. In the original code, malloc failing would set the result pointer
1272 // of malloc to null. In this case, some mallocs could succeed and others
1273 // could fail. As such, we emit code that looks like this:
1274 // F0 = malloc(field0)
1275 // F1 = malloc(field1)
1276 // F2 = malloc(field2)
1277 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1278 // if (F0) { free(F0); F0 = 0; }
1279 // if (F1) { free(F1); F1 = 0; }
1280 // if (F2) { free(F2); F2 = 0; }
1282 Value *RunningOr = 0;
1283 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1284 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
1285 Constant::getNullValue(FieldMallocs[i]->getType()),
1288 RunningOr = Cond; // First seteq
1290 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
1293 // Split the basic block at the old malloc.
1294 BasicBlock *OrigBB = MI->getParent();
1295 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
1297 // Create the block to check the first condition. Put all these blocks at the
1298 // end of the function as they are unlikely to be executed.
1299 BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
1300 OrigBB->getParent());
1302 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1303 // branch on RunningOr.
1304 OrigBB->getTerminator()->eraseFromParent();
1305 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1307 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1308 // pointer, because some may be null while others are not.
1309 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1310 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1311 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1312 Constant::getNullValue(GVVal->getType()),
1313 "tmp", NullPtrBlock);
1314 BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
1315 BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
1316 BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1318 // Fill in FreeBlock.
1319 new FreeInst(GVVal, FreeBlock);
1320 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1322 BranchInst::Create(NextBlock, FreeBlock);
1324 NullPtrBlock = NextBlock;
1327 BranchInst::Create(ContBB, NullPtrBlock);
1329 // MI is no longer needed, remove it.
1330 MI->eraseFromParent();
1332 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1333 /// update all uses of the load, keep track of what scalarized loads are
1334 /// inserted for a given load.
1335 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1336 InsertedScalarizedValues[GV] = FieldGlobals;
1338 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1340 // Okay, the malloc site is completely handled. All of the uses of GV are now
1341 // loads, and all uses of those loads are simple. Rewrite them to use loads
1342 // of the per-field globals instead.
1343 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1344 Instruction *User = cast<Instruction>(*UI++);
1346 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1347 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1351 // Must be a store of null.
1352 StoreInst *SI = cast<StoreInst>(User);
1353 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1354 "Unexpected heap-sra user!");
1356 // Insert a store of null into each global.
1357 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1358 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1359 Constant *Null = Constant::getNullValue(PT->getElementType());
1360 new StoreInst(Null, FieldGlobals[i], SI);
1362 // Erase the original store.
1363 SI->eraseFromParent();
1366 // While we have PHIs that are interesting to rewrite, do it.
1367 while (!PHIsToRewrite.empty()) {
1368 PHINode *PN = PHIsToRewrite.back().first;
1369 unsigned FieldNo = PHIsToRewrite.back().second;
1370 PHIsToRewrite.pop_back();
1371 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1372 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1374 // Add all the incoming values. This can materialize more phis.
1375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1376 Value *InVal = PN->getIncomingValue(i);
1377 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1379 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1383 // Drop all inter-phi links and any loads that made it this far.
1384 for (DenseMap<Value*, std::vector<Value*> >::iterator
1385 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1387 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1388 PN->dropAllReferences();
1389 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1390 LI->dropAllReferences();
1393 // Delete all the phis and loads now that inter-references are dead.
1394 for (DenseMap<Value*, std::vector<Value*> >::iterator
1395 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1397 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1398 PN->eraseFromParent();
1399 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1400 LI->eraseFromParent();
1403 // The old global is now dead, remove it.
1404 GV->eraseFromParent();
1407 return cast<GlobalVariable>(FieldGlobals[0]);
1410 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1411 /// pointer global variable with a single value stored it that is a malloc or
1413 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1415 Module::global_iterator &GVI,
1417 // If this is a malloc of an abstract type, don't touch it.
1418 if (!MI->getAllocatedType()->isSized())
1421 // We can't optimize this global unless all uses of it are *known* to be
1422 // of the malloc value, not of the null initializer value (consider a use
1423 // that compares the global's value against zero to see if the malloc has
1424 // been reached). To do this, we check to see if all uses of the global
1425 // would trap if the global were null: this proves that they must all
1426 // happen after the malloc.
1427 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1430 // We can't optimize this if the malloc itself is used in a complex way,
1431 // for example, being stored into multiple globals. This allows the
1432 // malloc to be stored into the specified global, loaded setcc'd, and
1433 // GEP'd. These are all things we could transform to using the global
1436 SmallPtrSet<PHINode*, 8> PHIs;
1437 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
1442 // If we have a global that is only initialized with a fixed size malloc,
1443 // transform the program to use global memory instead of malloc'd memory.
1444 // This eliminates dynamic allocation, avoids an indirection accessing the
1445 // data, and exposes the resultant global to further GlobalOpt.
1446 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1447 // Restrict this transformation to only working on small allocations
1448 // (2048 bytes currently), as we don't want to introduce a 16M global or
1450 if (NElements->getZExtValue()*
1451 TD.getTypePaddedSize(MI->getAllocatedType()) < 2048) {
1452 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1457 // If the allocation is an array of structures, consider transforming this
1458 // into multiple malloc'd arrays, one for each field. This is basically
1459 // SRoA for malloc'd memory.
1460 const Type *AllocTy = MI->getAllocatedType();
1462 // If this is an allocation of a fixed size array of structs, analyze as a
1463 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1464 if (!MI->isArrayAllocation())
1465 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1466 AllocTy = AT->getElementType();
1468 if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1469 // This the structure has an unreasonable number of fields, leave it
1471 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1472 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
1474 // If this is a fixed size array, transform the Malloc to be an alloc of
1475 // structs. malloc [100 x struct],1 -> malloc struct, 100
1476 if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
1478 new MallocInst(AllocSTy,
1479 ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
1481 NewMI->takeName(MI);
1482 Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
1483 MI->replaceAllUsesWith(Cast);
1484 MI->eraseFromParent();
1488 GVI = PerformHeapAllocSRoA(GV, MI);
1496 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1497 // that only one value (besides its initializer) is ever stored to the global.
1498 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1499 Module::global_iterator &GVI,
1501 // Ignore no-op GEPs and bitcasts.
1502 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1504 // If we are dealing with a pointer global that is initialized to null and
1505 // only has one (non-null) value stored into it, then we can optimize any
1506 // users of the loaded value (often calls and loads) that would trap if the
1508 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1509 GV->getInitializer()->isNullValue()) {
1510 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1511 if (GV->getInitializer()->getType() != SOVC->getType())
1512 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1514 // Optimize away any trapping uses of the loaded value.
1515 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1517 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1518 if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD))
1526 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1527 /// two values ever stored into GV are its initializer and OtherVal. See if we
1528 /// can shrink the global into a boolean and select between the two values
1529 /// whenever it is used. This exposes the values to other scalar optimizations.
1530 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1531 const Type *GVElType = GV->getType()->getElementType();
1533 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1534 // an FP value or vector, don't do this optimization because a select between
1535 // them is very expensive and unlikely to lead to later simplification.
1536 if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
1537 isa<VectorType>(GVElType))
1540 // Walk the use list of the global seeing if all the uses are load or store.
1541 // If there is anything else, bail out.
1542 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1543 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1546 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1548 // Create the new global, initializing it to false.
1549 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
1550 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
1553 GV->isThreadLocal());
1554 GV->getParent()->getGlobalList().insert(GV, NewGV);
1556 Constant *InitVal = GV->getInitializer();
1557 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1559 // If initialized to zero and storing one into the global, we can use a cast
1560 // instead of a select to synthesize the desired value.
1561 bool IsOneZero = false;
1562 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1563 IsOneZero = InitVal->isNullValue() && CI->isOne();
1565 while (!GV->use_empty()) {
1566 Instruction *UI = cast<Instruction>(GV->use_back());
1567 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1568 // Change the store into a boolean store.
1569 bool StoringOther = SI->getOperand(0) == OtherVal;
1570 // Only do this if we weren't storing a loaded value.
1572 if (StoringOther || SI->getOperand(0) == InitVal)
1573 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
1575 // Otherwise, we are storing a previously loaded copy. To do this,
1576 // change the copy from copying the original value to just copying the
1578 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1580 // If we're already replaced the input, StoredVal will be a cast or
1581 // select instruction. If not, it will be a load of the original
1583 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1584 assert(LI->getOperand(0) == GV && "Not a copy!");
1585 // Insert a new load, to preserve the saved value.
1586 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1588 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1589 "This is not a form that we understand!");
1590 StoreVal = StoredVal->getOperand(0);
1591 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1594 new StoreInst(StoreVal, NewGV, SI);
1596 // Change the load into a load of bool then a select.
1597 LoadInst *LI = cast<LoadInst>(UI);
1598 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1601 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1603 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1605 LI->replaceAllUsesWith(NSI);
1607 UI->eraseFromParent();
1610 GV->eraseFromParent();
1615 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1616 /// it if possible. If we make a change, return true.
1617 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1618 Module::global_iterator &GVI) {
1619 SmallPtrSet<PHINode*, 16> PHIUsers;
1621 GV->removeDeadConstantUsers();
1623 if (GV->use_empty()) {
1624 DOUT << "GLOBAL DEAD: " << *GV;
1625 GV->eraseFromParent();
1630 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1632 cerr << "Global: " << *GV;
1633 cerr << " isLoaded = " << GS.isLoaded << "\n";
1634 cerr << " StoredType = ";
1635 switch (GS.StoredType) {
1636 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1637 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1638 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1639 case GlobalStatus::isStored: cerr << "stored\n"; break;
1641 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1642 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1643 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1644 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1646 cerr << " HasMultipleAccessingFunctions = "
1647 << GS.HasMultipleAccessingFunctions << "\n";
1648 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1652 // If this is a first class global and has only one accessing function
1653 // and this function is main (which we know is not recursive we can make
1654 // this global a local variable) we replace the global with a local alloca
1655 // in this function.
1657 // NOTE: It doesn't make sense to promote non single-value types since we
1658 // are just replacing static memory to stack memory.
1659 if (!GS.HasMultipleAccessingFunctions &&
1660 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1661 GV->getType()->getElementType()->isSingleValueType() &&
1662 GS.AccessingFunction->getName() == "main" &&
1663 GS.AccessingFunction->hasExternalLinkage()) {
1664 DOUT << "LOCALIZING GLOBAL: " << *GV;
1665 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1666 const Type* ElemTy = GV->getType()->getElementType();
1667 // FIXME: Pass Global's alignment when globals have alignment
1668 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1669 if (!isa<UndefValue>(GV->getInitializer()))
1670 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1672 GV->replaceAllUsesWith(Alloca);
1673 GV->eraseFromParent();
1678 // If the global is never loaded (but may be stored to), it is dead.
1681 DOUT << "GLOBAL NEVER LOADED: " << *GV;
1683 // Delete any stores we can find to the global. We may not be able to
1684 // make it completely dead though.
1685 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1687 // If the global is dead now, delete it.
1688 if (GV->use_empty()) {
1689 GV->eraseFromParent();
1695 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1696 DOUT << "MARKING CONSTANT: " << *GV;
1697 GV->setConstant(true);
1699 // Clean up any obviously simplifiable users now.
1700 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1702 // If the global is dead now, just nuke it.
1703 if (GV->use_empty()) {
1704 DOUT << " *** Marking constant allowed us to simplify "
1705 << "all users and delete global!\n";
1706 GV->eraseFromParent();
1712 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1713 if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
1714 getAnalysis<TargetData>())) {
1715 GVI = FirstNewGV; // Don't skip the newly produced globals!
1718 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1719 // If the initial value for the global was an undef value, and if only
1720 // one other value was stored into it, we can just change the
1721 // initializer to be the stored value, then delete all stores to the
1722 // global. This allows us to mark it constant.
1723 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1724 if (isa<UndefValue>(GV->getInitializer())) {
1725 // Change the initial value here.
1726 GV->setInitializer(SOVConstant);
1728 // Clean up any obviously simplifiable users now.
1729 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1731 if (GV->use_empty()) {
1732 DOUT << " *** Substituting initializer allowed us to "
1733 << "simplify all users and delete global!\n";
1734 GV->eraseFromParent();
1743 // Try to optimize globals based on the knowledge that only one value
1744 // (besides its initializer) is ever stored to the global.
1745 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1746 getAnalysis<TargetData>()))
1749 // Otherwise, if the global was not a boolean, we can shrink it to be a
1751 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1752 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1761 /// OnlyCalledDirectly - Return true if the specified function is only called
1762 /// directly. In other words, its address is never taken.
1763 static bool OnlyCalledDirectly(Function *F) {
1764 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1765 Instruction *User = dyn_cast<Instruction>(*UI);
1766 if (!User) return false;
1767 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1769 // See if the function address is passed as an argument.
1770 for (User::op_iterator i = User->op_begin() + 1, e = User->op_end();
1772 if (*i == F) return false;
1777 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1778 /// function, changing them to FastCC.
1779 static void ChangeCalleesToFastCall(Function *F) {
1780 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1781 CallSite User(cast<Instruction>(*UI));
1782 User.setCallingConv(CallingConv::Fast);
1786 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1787 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1788 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1791 // There can be only one.
1792 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1798 static void RemoveNestAttribute(Function *F) {
1799 F->setAttributes(StripNest(F->getAttributes()));
1800 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1801 CallSite User(cast<Instruction>(*UI));
1802 User.setAttributes(StripNest(User.getAttributes()));
1806 bool GlobalOpt::OptimizeFunctions(Module &M) {
1807 bool Changed = false;
1808 // Optimize functions.
1809 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1811 F->removeDeadConstantUsers();
1812 if (F->use_empty() && (F->hasLocalLinkage() ||
1813 F->hasLinkOnceLinkage())) {
1814 M.getFunctionList().erase(F);
1817 } else if (F->hasLocalLinkage()) {
1818 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1819 OnlyCalledDirectly(F)) {
1820 // If this function has C calling conventions, is not a varargs
1821 // function, and is only called directly, promote it to use the Fast
1822 // calling convention.
1823 F->setCallingConv(CallingConv::Fast);
1824 ChangeCalleesToFastCall(F);
1829 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1830 OnlyCalledDirectly(F)) {
1831 // The function is not used by a trampoline intrinsic, so it is safe
1832 // to remove the 'nest' attribute.
1833 RemoveNestAttribute(F);
1842 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1843 bool Changed = false;
1844 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1846 GlobalVariable *GV = GVI++;
1847 if (!GV->isConstant() && GV->hasLocalLinkage() &&
1848 GV->hasInitializer())
1849 Changed |= ProcessInternalGlobal(GV, GVI);
1854 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1855 /// initializers have an init priority of 65535.
1856 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1857 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1859 if (I->getName() == "llvm.global_ctors") {
1860 // Found it, verify it's an array of { int, void()* }.
1861 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1863 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1864 if (!STy || STy->getNumElements() != 2 ||
1865 STy->getElementType(0) != Type::Int32Ty) return 0;
1866 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1867 if (!PFTy) return 0;
1868 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1869 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1870 FTy->getNumParams() != 0)
1873 // Verify that the initializer is simple enough for us to handle.
1874 if (!I->hasInitializer()) return 0;
1875 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1877 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1878 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
1879 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1882 // Must have a function or null ptr.
1883 if (!isa<Function>(CS->getOperand(1)))
1886 // Init priority must be standard.
1887 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1888 if (!CI || CI->getZExtValue() != 65535)
1899 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1900 /// return a list of the functions and null terminator as a vector.
1901 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1902 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1903 std::vector<Function*> Result;
1904 Result.reserve(CA->getNumOperands());
1905 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1906 ConstantStruct *CS = cast<ConstantStruct>(*i);
1907 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1912 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1913 /// specified array, returning the new global to use.
1914 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1915 const std::vector<Function*> &Ctors) {
1916 // If we made a change, reassemble the initializer list.
1917 std::vector<Constant*> CSVals;
1918 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
1919 CSVals.push_back(0);
1921 // Create the new init list.
1922 std::vector<Constant*> CAList;
1923 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1925 CSVals[1] = Ctors[i];
1927 const Type *FTy = FunctionType::get(Type::VoidTy,
1928 std::vector<const Type*>(), false);
1929 const PointerType *PFTy = PointerType::getUnqual(FTy);
1930 CSVals[1] = Constant::getNullValue(PFTy);
1931 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
1933 CAList.push_back(ConstantStruct::get(CSVals));
1936 // Create the array initializer.
1937 const Type *StructTy =
1938 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1939 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1942 // If we didn't change the number of elements, don't create a new GV.
1943 if (CA->getType() == GCL->getInitializer()->getType()) {
1944 GCL->setInitializer(CA);
1948 // Create the new global and insert it next to the existing list.
1949 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1950 GCL->getLinkage(), CA, "",
1952 GCL->isThreadLocal());
1953 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1956 // Nuke the old list, replacing any uses with the new one.
1957 if (!GCL->use_empty()) {
1959 if (V->getType() != GCL->getType())
1960 V = ConstantExpr::getBitCast(V, GCL->getType());
1961 GCL->replaceAllUsesWith(V);
1963 GCL->eraseFromParent();
1972 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
1974 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1975 Constant *R = ComputedValues[V];
1976 assert(R && "Reference to an uncomputed value!");
1980 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1981 /// enough for us to understand. In particular, if it is a cast of something,
1982 /// we punt. We basically just support direct accesses to globals and GEP's of
1983 /// globals. This should be kept up to date with CommitValueTo.
1984 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1985 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1986 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
1987 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1988 return !GV->isDeclaration(); // reject external globals.
1990 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1991 // Handle a constantexpr gep.
1992 if (CE->getOpcode() == Instruction::GetElementPtr &&
1993 isa<GlobalVariable>(CE->getOperand(0))) {
1994 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1995 if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
1996 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1997 return GV->hasInitializer() &&
1998 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2003 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2004 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2005 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2006 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2007 ConstantExpr *Addr, unsigned OpNo) {
2008 // Base case of the recursion.
2009 if (OpNo == Addr->getNumOperands()) {
2010 assert(Val->getType() == Init->getType() && "Type mismatch!");
2014 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2015 std::vector<Constant*> Elts;
2017 // Break up the constant into its elements.
2018 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2019 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2020 Elts.push_back(cast<Constant>(*i));
2021 } else if (isa<ConstantAggregateZero>(Init)) {
2022 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2023 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2024 } else if (isa<UndefValue>(Init)) {
2025 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2026 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2028 assert(0 && "This code is out of sync with "
2029 " ConstantFoldLoadThroughGEPConstantExpr");
2032 // Replace the element that we are supposed to.
2033 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2034 unsigned Idx = CU->getZExtValue();
2035 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2036 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2038 // Return the modified struct.
2039 return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
2041 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2042 const ArrayType *ATy = cast<ArrayType>(Init->getType());
2044 // Break up the array into elements.
2045 std::vector<Constant*> Elts;
2046 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2047 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2048 Elts.push_back(cast<Constant>(*i));
2049 } else if (isa<ConstantAggregateZero>(Init)) {
2050 Constant *Elt = Constant::getNullValue(ATy->getElementType());
2051 Elts.assign(ATy->getNumElements(), Elt);
2052 } else if (isa<UndefValue>(Init)) {
2053 Constant *Elt = UndefValue::get(ATy->getElementType());
2054 Elts.assign(ATy->getNumElements(), Elt);
2056 assert(0 && "This code is out of sync with "
2057 " ConstantFoldLoadThroughGEPConstantExpr");
2060 assert(CI->getZExtValue() < ATy->getNumElements());
2061 Elts[CI->getZExtValue()] =
2062 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2063 return ConstantArray::get(ATy, Elts);
2067 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2068 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2069 static void CommitValueTo(Constant *Val, Constant *Addr) {
2070 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2071 assert(GV->hasInitializer());
2072 GV->setInitializer(Val);
2076 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2077 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2079 Constant *Init = GV->getInitializer();
2080 Init = EvaluateStoreInto(Init, Val, CE, 2);
2081 GV->setInitializer(Init);
2084 /// ComputeLoadResult - Return the value that would be computed by a load from
2085 /// P after the stores reflected by 'memory' have been performed. If we can't
2086 /// decide, return null.
2087 static Constant *ComputeLoadResult(Constant *P,
2088 const DenseMap<Constant*, Constant*> &Memory) {
2089 // If this memory location has been recently stored, use the stored value: it
2090 // is the most up-to-date.
2091 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2092 if (I != Memory.end()) return I->second;
2095 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2096 if (GV->hasInitializer())
2097 return GV->getInitializer();
2101 // Handle a constantexpr getelementptr.
2102 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2103 if (CE->getOpcode() == Instruction::GetElementPtr &&
2104 isa<GlobalVariable>(CE->getOperand(0))) {
2105 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2106 if (GV->hasInitializer())
2107 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2110 return 0; // don't know how to evaluate.
2113 /// EvaluateFunction - Evaluate a call to function F, returning true if
2114 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2115 /// arguments for the function.
2116 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2117 const std::vector<Constant*> &ActualArgs,
2118 std::vector<Function*> &CallStack,
2119 DenseMap<Constant*, Constant*> &MutatedMemory,
2120 std::vector<GlobalVariable*> &AllocaTmps) {
2121 // Check to see if this function is already executing (recursion). If so,
2122 // bail out. TODO: we might want to accept limited recursion.
2123 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2126 CallStack.push_back(F);
2128 /// Values - As we compute SSA register values, we store their contents here.
2129 DenseMap<Value*, Constant*> Values;
2131 // Initialize arguments to the incoming values specified.
2133 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2135 Values[AI] = ActualArgs[ArgNo];
2137 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2138 /// we can only evaluate any one basic block at most once. This set keeps
2139 /// track of what we have executed so we can detect recursive cases etc.
2140 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2142 // CurInst - The current instruction we're evaluating.
2143 BasicBlock::iterator CurInst = F->begin()->begin();
2145 // This is the main evaluation loop.
2147 Constant *InstResult = 0;
2149 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2150 if (SI->isVolatile()) return false; // no volatile accesses.
2151 Constant *Ptr = getVal(Values, SI->getOperand(1));
2152 if (!isSimpleEnoughPointerToCommit(Ptr))
2153 // If this is too complex for us to commit, reject it.
2155 Constant *Val = getVal(Values, SI->getOperand(0));
2156 MutatedMemory[Ptr] = Val;
2157 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2158 InstResult = ConstantExpr::get(BO->getOpcode(),
2159 getVal(Values, BO->getOperand(0)),
2160 getVal(Values, BO->getOperand(1)));
2161 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2162 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2163 getVal(Values, CI->getOperand(0)),
2164 getVal(Values, CI->getOperand(1)));
2165 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2166 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2167 getVal(Values, CI->getOperand(0)),
2169 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2170 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2171 getVal(Values, SI->getOperand(1)),
2172 getVal(Values, SI->getOperand(2)));
2173 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2174 Constant *P = getVal(Values, GEP->getOperand(0));
2175 SmallVector<Constant*, 8> GEPOps;
2176 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2178 GEPOps.push_back(getVal(Values, *i));
2179 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2180 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2181 if (LI->isVolatile()) return false; // no volatile accesses.
2182 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2184 if (InstResult == 0) return false; // Could not evaluate load.
2185 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2186 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2187 const Type *Ty = AI->getType()->getElementType();
2188 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2189 GlobalValue::InternalLinkage,
2190 UndefValue::get(Ty),
2192 InstResult = AllocaTmps.back();
2193 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2194 // Cannot handle inline asm.
2195 if (isa<InlineAsm>(CI->getOperand(0))) return false;
2197 // Resolve function pointers.
2198 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2199 if (!Callee) return false; // Cannot resolve.
2201 std::vector<Constant*> Formals;
2202 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2204 Formals.push_back(getVal(Values, *i));
2206 if (Callee->isDeclaration()) {
2207 // If this is a function we can constant fold, do it.
2208 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
2215 if (Callee->getFunctionType()->isVarArg())
2220 // Execute the call, if successful, use the return value.
2221 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2222 MutatedMemory, AllocaTmps))
2224 InstResult = RetVal;
2226 } else if (isa<TerminatorInst>(CurInst)) {
2227 BasicBlock *NewBB = 0;
2228 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2229 if (BI->isUnconditional()) {
2230 NewBB = BI->getSuccessor(0);
2233 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2234 if (!Cond) return false; // Cannot determine.
2236 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2238 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2240 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2241 if (!Val) return false; // Cannot determine.
2242 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2243 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2244 if (RI->getNumOperands())
2245 RetVal = getVal(Values, RI->getOperand(0));
2247 CallStack.pop_back(); // return from fn.
2248 return true; // We succeeded at evaluating this ctor!
2250 // invoke, unwind, unreachable.
2251 return false; // Cannot handle this terminator.
2254 // Okay, we succeeded in evaluating this control flow. See if we have
2255 // executed the new block before. If so, we have a looping function,
2256 // which we cannot evaluate in reasonable time.
2257 if (!ExecutedBlocks.insert(NewBB))
2258 return false; // looped!
2260 // Okay, we have never been in this block before. Check to see if there
2261 // are any PHI nodes. If so, evaluate them with information about where
2263 BasicBlock *OldBB = CurInst->getParent();
2264 CurInst = NewBB->begin();
2266 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2267 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2269 // Do NOT increment CurInst. We know that the terminator had no value.
2272 // Did not know how to evaluate this!
2276 if (!CurInst->use_empty())
2277 Values[CurInst] = InstResult;
2279 // Advance program counter.
2284 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2285 /// we can. Return true if we can, false otherwise.
2286 static bool EvaluateStaticConstructor(Function *F) {
2287 /// MutatedMemory - For each store we execute, we update this map. Loads
2288 /// check this to get the most up-to-date value. If evaluation is successful,
2289 /// this state is committed to the process.
2290 DenseMap<Constant*, Constant*> MutatedMemory;
2292 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2293 /// to represent its body. This vector is needed so we can delete the
2294 /// temporary globals when we are done.
2295 std::vector<GlobalVariable*> AllocaTmps;
2297 /// CallStack - This is used to detect recursion. In pathological situations
2298 /// we could hit exponential behavior, but at least there is nothing
2300 std::vector<Function*> CallStack;
2302 // Call the function.
2303 Constant *RetValDummy;
2304 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
2305 CallStack, MutatedMemory, AllocaTmps);
2307 // We succeeded at evaluation: commit the result.
2308 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2309 << F->getName() << "' to " << MutatedMemory.size()
2311 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2312 E = MutatedMemory.end(); I != E; ++I)
2313 CommitValueTo(I->second, I->first);
2316 // At this point, we are done interpreting. If we created any 'alloca'
2317 // temporaries, release them now.
2318 while (!AllocaTmps.empty()) {
2319 GlobalVariable *Tmp = AllocaTmps.back();
2320 AllocaTmps.pop_back();
2322 // If there are still users of the alloca, the program is doing something
2323 // silly, e.g. storing the address of the alloca somewhere and using it
2324 // later. Since this is undefined, we'll just make it be null.
2325 if (!Tmp->use_empty())
2326 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2335 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2336 /// Return true if anything changed.
2337 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2338 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2339 bool MadeChange = false;
2340 if (Ctors.empty()) return false;
2342 // Loop over global ctors, optimizing them when we can.
2343 for (unsigned i = 0; i != Ctors.size(); ++i) {
2344 Function *F = Ctors[i];
2345 // Found a null terminator in the middle of the list, prune off the rest of
2348 if (i != Ctors.size()-1) {
2355 // We cannot simplify external ctor functions.
2356 if (F->empty()) continue;
2358 // If we can evaluate the ctor at compile time, do.
2359 if (EvaluateStaticConstructor(F)) {
2360 Ctors.erase(Ctors.begin()+i);
2363 ++NumCtorsEvaluated;
2368 if (!MadeChange) return false;
2370 GCL = InstallGlobalCtors(GCL, Ctors);
2374 bool GlobalOpt::ResolveAliases(Module &M) {
2375 bool Changed = false;
2377 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2379 Module::alias_iterator J = I++;
2380 // If the aliasee may change at link time, nothing can be done - bail out.
2381 if (J->mayBeOverridden())
2384 Constant *Aliasee = J->getAliasee();
2385 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2386 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2388 // Make all users of the alias use the aliasee instead.
2389 if (!J->use_empty()) {
2390 J->replaceAllUsesWith(Aliasee);
2391 ++NumAliasesResolved;
2395 // If the aliasee has internal linkage, give it the name and linkage
2396 // of the alias, and delete the alias. This turns:
2397 // define internal ... @f(...)
2398 // @a = alias ... @f
2400 // define ... @a(...)
2401 if (!Target->hasInternalLinkage())
2404 // The transform is only useful if the alias does not have internal linkage.
2405 if (J->hasInternalLinkage())
2408 // Do not perform the transform if multiple aliases potentially target the
2409 // aliasee. This check also ensures that it is safe to replace the section
2410 // and other attributes of the aliasee with those of the alias.
2414 // Give the aliasee the name, linkage and other attributes of the alias.
2415 Target->takeName(J);
2416 Target->setLinkage(J->getLinkage());
2417 Target->GlobalValue::copyAttributesFrom(J);
2419 // Delete the alias.
2420 M.getAliasList().erase(J);
2421 ++NumAliasesRemoved;
2428 bool GlobalOpt::runOnModule(Module &M) {
2429 bool Changed = false;
2431 // Try to find the llvm.globalctors list.
2432 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2434 bool LocalChange = true;
2435 while (LocalChange) {
2436 LocalChange = false;
2438 // Delete functions that are trivially dead, ccc -> fastcc
2439 LocalChange |= OptimizeFunctions(M);
2441 // Optimize global_ctors list.
2443 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2445 // Optimize non-address-taken globals.
2446 LocalChange |= OptimizeGlobalVars(M);
2448 // Resolve aliases, when possible.
2449 LocalChange |= ResolveAliases(M);
2450 Changed |= LocalChange;
2453 // TODO: Move all global ctors functions to the end of the module for code