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/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/ConstantFolding.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/ValueHandle.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Transforms/Utils/GlobalStatus.h"
43 #include "llvm/Transforms/Utils/ModuleUtils.h"
47 STATISTIC(NumMarked , "Number of globals marked constant");
48 STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
49 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
50 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
51 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
52 STATISTIC(NumDeleted , "Number of globals deleted");
53 STATISTIC(NumFnDeleted , "Number of functions deleted");
54 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
55 STATISTIC(NumLocalized , "Number of globals localized");
56 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
57 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
58 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
59 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
60 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
61 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
62 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
65 struct GlobalOpt : public ModulePass {
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<TargetLibraryInfo>();
69 static char ID; // Pass identification, replacement for typeid
70 GlobalOpt() : ModulePass(ID) {
71 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
74 bool runOnModule(Module &M);
77 GlobalVariable *FindGlobalCtors(Module &M);
78 bool OptimizeFunctions(Module &M);
79 bool OptimizeGlobalVars(Module &M);
80 bool OptimizeGlobalAliases(Module &M);
81 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
82 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
83 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
84 const GlobalStatus &GS);
85 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
88 TargetLibraryInfo *TLI;
92 char GlobalOpt::ID = 0;
93 INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
94 "Global Variable Optimizer", false, false)
95 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
96 INITIALIZE_PASS_END(GlobalOpt, "globalopt",
97 "Global Variable Optimizer", false, false)
99 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
101 /// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
102 /// as a root? If so, we might not really want to eliminate the stores to it.
103 static bool isLeakCheckerRoot(GlobalVariable *GV) {
104 // A global variable is a root if it is a pointer, or could plausibly contain
105 // a pointer. There are two challenges; one is that we could have a struct
106 // the has an inner member which is a pointer. We recurse through the type to
107 // detect these (up to a point). The other is that we may actually be a union
108 // of a pointer and another type, and so our LLVM type is an integer which
109 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
110 // potentially contained here.
112 if (GV->hasPrivateLinkage())
115 SmallVector<Type *, 4> Types;
116 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
120 Type *Ty = Types.pop_back_val();
121 switch (Ty->getTypeID()) {
123 case Type::PointerTyID: return true;
124 case Type::ArrayTyID:
125 case Type::VectorTyID: {
126 SequentialType *STy = cast<SequentialType>(Ty);
127 Types.push_back(STy->getElementType());
130 case Type::StructTyID: {
131 StructType *STy = cast<StructType>(Ty);
132 if (STy->isOpaque()) return true;
133 for (StructType::element_iterator I = STy->element_begin(),
134 E = STy->element_end(); I != E; ++I) {
136 if (isa<PointerType>(InnerTy)) return true;
137 if (isa<CompositeType>(InnerTy))
138 Types.push_back(InnerTy);
143 if (--Limit == 0) return true;
144 } while (!Types.empty());
148 /// Given a value that is stored to a global but never read, determine whether
149 /// it's safe to remove the store and the chain of computation that feeds the
151 static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
153 if (isa<Constant>(V))
157 if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
160 if (isAllocationFn(V, TLI))
163 Instruction *I = cast<Instruction>(V);
164 if (I->mayHaveSideEffects())
166 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
167 if (!GEP->hasAllConstantIndices())
169 } else if (I->getNumOperands() != 1) {
173 V = I->getOperand(0);
177 /// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
178 /// of the global and clean up any that obviously don't assign the global a
179 /// value that isn't dynamically allocated.
181 static bool CleanupPointerRootUsers(GlobalVariable *GV,
182 const TargetLibraryInfo *TLI) {
183 // A brief explanation of leak checkers. The goal is to find bugs where
184 // pointers are forgotten, causing an accumulating growth in memory
185 // usage over time. The common strategy for leak checkers is to whitelist the
186 // memory pointed to by globals at exit. This is popular because it also
187 // solves another problem where the main thread of a C++ program may shut down
188 // before other threads that are still expecting to use those globals. To
189 // handle that case, we expect the program may create a singleton and never
192 bool Changed = false;
194 // If Dead[n].first is the only use of a malloc result, we can delete its
195 // chain of computation and the store to the global in Dead[n].second.
196 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
198 // Constants can't be pointers to dynamically allocated memory.
199 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
202 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
203 Value *V = SI->getValueOperand();
204 if (isa<Constant>(V)) {
206 SI->eraseFromParent();
207 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
209 Dead.push_back(std::make_pair(I, SI));
211 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
212 if (isa<Constant>(MSI->getValue())) {
214 MSI->eraseFromParent();
215 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
217 Dead.push_back(std::make_pair(I, MSI));
219 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
220 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
221 if (MemSrc && MemSrc->isConstant()) {
223 MTI->eraseFromParent();
224 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
226 Dead.push_back(std::make_pair(I, MTI));
228 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
229 if (CE->use_empty()) {
230 CE->destroyConstant();
233 } else if (Constant *C = dyn_cast<Constant>(U)) {
234 if (isSafeToDestroyConstant(C)) {
235 C->destroyConstant();
236 // This could have invalidated UI, start over from scratch.
238 CleanupPointerRootUsers(GV, TLI);
244 for (int i = 0, e = Dead.size(); i != e; ++i) {
245 if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
246 Dead[i].second->eraseFromParent();
247 Instruction *I = Dead[i].first;
249 if (isAllocationFn(I, TLI))
251 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
254 I->eraseFromParent();
257 I->eraseFromParent();
264 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
265 /// users of the global, cleaning up the obvious ones. This is largely just a
266 /// quick scan over the use list to clean up the easy and obvious cruft. This
267 /// returns true if it made a change.
268 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
269 DataLayout *TD, TargetLibraryInfo *TLI) {
270 bool Changed = false;
271 // Note that we need to use a weak value handle for the worklist items. When
272 // we delete a constant array, we may also be holding pointer to one of its
273 // elements (or an element of one of its elements if we're dealing with an
274 // array of arrays) in the worklist.
275 SmallVector<WeakVH, 8> WorkList(V->use_begin(), V->use_end());
276 while (!WorkList.empty()) {
277 Value *UV = WorkList.pop_back_val();
281 User *U = cast<User>(UV);
283 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
285 // Replace the load with the initializer.
286 LI->replaceAllUsesWith(Init);
287 LI->eraseFromParent();
290 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
291 // Store must be unreachable or storing Init into the global.
292 SI->eraseFromParent();
294 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
295 if (CE->getOpcode() == Instruction::GetElementPtr) {
296 Constant *SubInit = 0;
298 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
299 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
300 } else if ((CE->getOpcode() == Instruction::BitCast &&
301 CE->getType()->isPointerTy()) ||
302 CE->getOpcode() == Instruction::AddrSpaceCast) {
303 // Pointer cast, delete any stores and memsets to the global.
304 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
307 if (CE->use_empty()) {
308 CE->destroyConstant();
311 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
312 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
313 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
314 // and will invalidate our notion of what Init is.
315 Constant *SubInit = 0;
316 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
318 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
319 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
320 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
322 // If the initializer is an all-null value and we have an inbounds GEP,
323 // we already know what the result of any load from that GEP is.
324 // TODO: Handle splats.
325 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
326 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
328 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
330 if (GEP->use_empty()) {
331 GEP->eraseFromParent();
334 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
335 if (MI->getRawDest() == V) {
336 MI->eraseFromParent();
340 } else if (Constant *C = dyn_cast<Constant>(U)) {
341 // If we have a chain of dead constantexprs or other things dangling from
342 // us, and if they are all dead, nuke them without remorse.
343 if (isSafeToDestroyConstant(C)) {
344 C->destroyConstant();
345 CleanupConstantGlobalUsers(V, Init, TD, TLI);
353 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
354 /// user of a derived expression from a global that we want to SROA.
355 static bool isSafeSROAElementUse(Value *V) {
356 // We might have a dead and dangling constant hanging off of here.
357 if (Constant *C = dyn_cast<Constant>(V))
358 return isSafeToDestroyConstant(C);
360 Instruction *I = dyn_cast<Instruction>(V);
361 if (!I) return false;
364 if (isa<LoadInst>(I)) return true;
366 // Stores *to* the pointer are ok.
367 if (StoreInst *SI = dyn_cast<StoreInst>(I))
368 return SI->getOperand(0) != V;
370 // Otherwise, it must be a GEP.
371 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
372 if (GEPI == 0) return false;
374 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
375 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
378 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
380 if (!isSafeSROAElementUse(*I))
386 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
387 /// Look at it and its uses and decide whether it is safe to SROA this global.
389 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
390 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
391 if (!isa<GetElementPtrInst>(U) &&
392 (!isa<ConstantExpr>(U) ||
393 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
396 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
397 // don't like < 3 operand CE's, and we don't like non-constant integer
398 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
400 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
401 !cast<Constant>(U->getOperand(1))->isNullValue() ||
402 !isa<ConstantInt>(U->getOperand(2)))
405 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
406 ++GEPI; // Skip over the pointer index.
408 // If this is a use of an array allocation, do a bit more checking for sanity.
409 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
410 uint64_t NumElements = AT->getNumElements();
411 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
413 // Check to make sure that index falls within the array. If not,
414 // something funny is going on, so we won't do the optimization.
416 if (Idx->getZExtValue() >= NumElements)
419 // We cannot scalar repl this level of the array unless any array
420 // sub-indices are in-range constants. In particular, consider:
421 // A[0][i]. We cannot know that the user isn't doing invalid things like
422 // allowing i to index an out-of-range subscript that accesses A[1].
424 // Scalar replacing *just* the outer index of the array is probably not
425 // going to be a win anyway, so just give up.
426 for (++GEPI; // Skip array index.
429 uint64_t NumElements;
430 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
431 NumElements = SubArrayTy->getNumElements();
432 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
433 NumElements = SubVectorTy->getNumElements();
435 assert((*GEPI)->isStructTy() &&
436 "Indexed GEP type is not array, vector, or struct!");
440 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
441 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
446 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
447 if (!isSafeSROAElementUse(*I))
452 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
453 /// is safe for us to perform this transformation.
455 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
456 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
458 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
465 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
466 /// variable. This opens the door for other optimizations by exposing the
467 /// behavior of the program in a more fine-grained way. We have determined that
468 /// this transformation is safe already. We return the first global variable we
469 /// insert so that the caller can reprocess it.
470 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
471 // Make sure this global only has simple uses that we can SRA.
472 if (!GlobalUsersSafeToSRA(GV))
475 assert(GV->hasLocalLinkage() && !GV->isConstant());
476 Constant *Init = GV->getInitializer();
477 Type *Ty = Init->getType();
479 std::vector<GlobalVariable*> NewGlobals;
480 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
482 // Get the alignment of the global, either explicit or target-specific.
483 unsigned StartAlignment = GV->getAlignment();
484 if (StartAlignment == 0)
485 StartAlignment = TD.getABITypeAlignment(GV->getType());
487 if (StructType *STy = dyn_cast<StructType>(Ty)) {
488 NewGlobals.reserve(STy->getNumElements());
489 const StructLayout &Layout = *TD.getStructLayout(STy);
490 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
491 Constant *In = Init->getAggregateElement(i);
492 assert(In && "Couldn't get element of initializer?");
493 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
494 GlobalVariable::InternalLinkage,
495 In, GV->getName()+"."+Twine(i),
496 GV->getThreadLocalMode(),
497 GV->getType()->getAddressSpace());
498 Globals.insert(GV, NGV);
499 NewGlobals.push_back(NGV);
501 // Calculate the known alignment of the field. If the original aggregate
502 // had 256 byte alignment for example, something might depend on that:
503 // propagate info to each field.
504 uint64_t FieldOffset = Layout.getElementOffset(i);
505 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
506 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
507 NGV->setAlignment(NewAlign);
509 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
510 unsigned NumElements = 0;
511 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
512 NumElements = ATy->getNumElements();
514 NumElements = cast<VectorType>(STy)->getNumElements();
516 if (NumElements > 16 && GV->hasNUsesOrMore(16))
517 return 0; // It's not worth it.
518 NewGlobals.reserve(NumElements);
520 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
521 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
522 for (unsigned i = 0, e = NumElements; i != e; ++i) {
523 Constant *In = Init->getAggregateElement(i);
524 assert(In && "Couldn't get element of initializer?");
526 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
527 GlobalVariable::InternalLinkage,
528 In, GV->getName()+"."+Twine(i),
529 GV->getThreadLocalMode(),
530 GV->getType()->getAddressSpace());
531 Globals.insert(GV, NGV);
532 NewGlobals.push_back(NGV);
534 // Calculate the known alignment of the field. If the original aggregate
535 // had 256 byte alignment for example, something might depend on that:
536 // propagate info to each field.
537 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538 if (NewAlign > EltAlign)
539 NGV->setAlignment(NewAlign);
543 if (NewGlobals.empty())
546 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
548 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
550 // Loop over all of the uses of the global, replacing the constantexpr geps,
551 // with smaller constantexpr geps or direct references.
552 while (!GV->use_empty()) {
553 User *GEP = GV->use_back();
554 assert(((isa<ConstantExpr>(GEP) &&
555 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
558 // Ignore the 1th operand, which has to be zero or else the program is quite
559 // broken (undefined). Get the 2nd operand, which is the structure or array
561 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
562 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
564 Value *NewPtr = NewGlobals[Val];
566 // Form a shorter GEP if needed.
567 if (GEP->getNumOperands() > 3) {
568 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
569 SmallVector<Constant*, 8> Idxs;
570 Idxs.push_back(NullInt);
571 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
572 Idxs.push_back(CE->getOperand(i));
573 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
575 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
576 SmallVector<Value*, 8> Idxs;
577 Idxs.push_back(NullInt);
578 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
579 Idxs.push_back(GEPI->getOperand(i));
580 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
581 GEPI->getName()+"."+Twine(Val),GEPI);
584 GEP->replaceAllUsesWith(NewPtr);
586 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
587 GEPI->eraseFromParent();
589 cast<ConstantExpr>(GEP)->destroyConstant();
592 // Delete the old global, now that it is dead.
596 // Loop over the new globals array deleting any globals that are obviously
597 // dead. This can arise due to scalarization of a structure or an array that
598 // has elements that are dead.
599 unsigned FirstGlobal = 0;
600 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
601 if (NewGlobals[i]->use_empty()) {
602 Globals.erase(NewGlobals[i]);
603 if (FirstGlobal == i) ++FirstGlobal;
606 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
609 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
610 /// value will trap if the value is dynamically null. PHIs keeps track of any
611 /// phi nodes we've seen to avoid reprocessing them.
612 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
613 SmallPtrSet<const PHINode*, 8> &PHIs) {
614 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
618 if (isa<LoadInst>(U)) {
620 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
621 if (SI->getOperand(0) == V) {
622 //cerr << "NONTRAPPING USE: " << *U;
623 return false; // Storing the value.
625 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
626 if (CI->getCalledValue() != V) {
627 //cerr << "NONTRAPPING USE: " << *U;
628 return false; // Not calling the ptr
630 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
631 if (II->getCalledValue() != V) {
632 //cerr << "NONTRAPPING USE: " << *U;
633 return false; // Not calling the ptr
635 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
636 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
637 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
638 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
639 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
640 // If we've already seen this phi node, ignore it, it has already been
642 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
644 } else if (isa<ICmpInst>(U) &&
645 isa<ConstantPointerNull>(UI->getOperand(1))) {
646 // Ignore icmp X, null
648 //cerr << "NONTRAPPING USE: " << *U;
655 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
656 /// from GV will trap if the loaded value is null. Note that this also permits
657 /// comparisons of the loaded value against null, as a special case.
658 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
659 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
663 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
664 SmallPtrSet<const PHINode*, 8> PHIs;
665 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
667 } else if (isa<StoreInst>(U)) {
668 // Ignore stores to the global.
670 // We don't know or understand this user, bail out.
671 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
678 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
679 bool Changed = false;
680 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
681 Instruction *I = cast<Instruction>(*UI++);
682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
683 LI->setOperand(0, NewV);
685 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
686 if (SI->getOperand(1) == V) {
687 SI->setOperand(1, NewV);
690 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
692 if (CS.getCalledValue() == V) {
693 // Calling through the pointer! Turn into a direct call, but be careful
694 // that the pointer is not also being passed as an argument.
695 CS.setCalledFunction(NewV);
697 bool PassedAsArg = false;
698 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
699 if (CS.getArgument(i) == V) {
701 CS.setArgument(i, NewV);
705 // Being passed as an argument also. Be careful to not invalidate UI!
709 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
710 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
711 ConstantExpr::getCast(CI->getOpcode(),
712 NewV, CI->getType()));
713 if (CI->use_empty()) {
715 CI->eraseFromParent();
717 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
718 // Should handle GEP here.
719 SmallVector<Constant*, 8> Idxs;
720 Idxs.reserve(GEPI->getNumOperands()-1);
721 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
723 if (Constant *C = dyn_cast<Constant>(*i))
727 if (Idxs.size() == GEPI->getNumOperands()-1)
728 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
729 ConstantExpr::getGetElementPtr(NewV, Idxs));
730 if (GEPI->use_empty()) {
732 GEPI->eraseFromParent();
741 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
742 /// value stored into it. If there are uses of the loaded value that would trap
743 /// if the loaded value is dynamically null, then we know that they cannot be
744 /// reachable with a null optimize away the load.
745 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
747 TargetLibraryInfo *TLI) {
748 bool Changed = false;
750 // Keep track of whether we are able to remove all the uses of the global
751 // other than the store that defines it.
752 bool AllNonStoreUsesGone = true;
754 // Replace all uses of loads with uses of uses of the stored value.
755 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
756 User *GlobalUser = *GUI++;
757 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
758 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
759 // If we were able to delete all uses of the loads
760 if (LI->use_empty()) {
761 LI->eraseFromParent();
764 AllNonStoreUsesGone = false;
766 } else if (isa<StoreInst>(GlobalUser)) {
767 // Ignore the store that stores "LV" to the global.
768 assert(GlobalUser->getOperand(1) == GV &&
769 "Must be storing *to* the global");
771 AllNonStoreUsesGone = false;
773 // If we get here we could have other crazy uses that are transitively
775 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
776 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
777 isa<BitCastInst>(GlobalUser) ||
778 isa<GetElementPtrInst>(GlobalUser)) &&
779 "Only expect load and stores!");
784 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
788 // If we nuked all of the loads, then none of the stores are needed either,
789 // nor is the global.
790 if (AllNonStoreUsesGone) {
791 if (isLeakCheckerRoot(GV)) {
792 Changed |= CleanupPointerRootUsers(GV, TLI);
795 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
797 if (GV->use_empty()) {
798 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
800 GV->eraseFromParent();
807 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
808 /// instructions that are foldable.
809 static void ConstantPropUsersOf(Value *V,
810 DataLayout *TD, TargetLibraryInfo *TLI) {
811 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
812 if (Instruction *I = dyn_cast<Instruction>(*UI++))
813 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
814 I->replaceAllUsesWith(NewC);
816 // Advance UI to the next non-I use to avoid invalidating it!
817 // Instructions could multiply use V.
818 while (UI != E && *UI == I)
820 I->eraseFromParent();
824 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
825 /// variable, and transforms the program as if it always contained the result of
826 /// the specified malloc. Because it is always the result of the specified
827 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
828 /// malloc into a global, and any loads of GV as uses of the new global.
829 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
832 ConstantInt *NElements,
834 TargetLibraryInfo *TLI) {
835 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
838 if (NElements->getZExtValue() == 1)
839 GlobalType = AllocTy;
841 // If we have an array allocation, the global variable is of an array.
842 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
844 // Create the new global variable. The contents of the malloc'd memory is
845 // undefined, so initialize with an undef value.
846 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
848 GlobalValue::InternalLinkage,
849 UndefValue::get(GlobalType),
850 GV->getName()+".body",
852 GV->getThreadLocalMode());
854 // If there are bitcast users of the malloc (which is typical, usually we have
855 // a malloc + bitcast) then replace them with uses of the new global. Update
856 // other users to use the global as well.
857 BitCastInst *TheBC = 0;
858 while (!CI->use_empty()) {
859 Instruction *User = cast<Instruction>(CI->use_back());
860 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
861 if (BCI->getType() == NewGV->getType()) {
862 BCI->replaceAllUsesWith(NewGV);
863 BCI->eraseFromParent();
865 BCI->setOperand(0, NewGV);
869 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
870 User->replaceUsesOfWith(CI, TheBC);
874 Constant *RepValue = NewGV;
875 if (NewGV->getType() != GV->getType()->getElementType())
876 RepValue = ConstantExpr::getBitCast(RepValue,
877 GV->getType()->getElementType());
879 // If there is a comparison against null, we will insert a global bool to
880 // keep track of whether the global was initialized yet or not.
881 GlobalVariable *InitBool =
882 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
883 GlobalValue::InternalLinkage,
884 ConstantInt::getFalse(GV->getContext()),
885 GV->getName()+".init", GV->getThreadLocalMode());
886 bool InitBoolUsed = false;
888 // Loop over all uses of GV, processing them in turn.
889 while (!GV->use_empty()) {
890 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
891 // The global is initialized when the store to it occurs.
892 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
893 SI->getOrdering(), SI->getSynchScope(), SI);
894 SI->eraseFromParent();
898 LoadInst *LI = cast<LoadInst>(GV->use_back());
899 while (!LI->use_empty()) {
900 Use &LoadUse = LI->use_begin().getUse();
901 if (!isa<ICmpInst>(LoadUse.getUser())) {
906 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
907 // Replace the cmp X, 0 with a use of the bool value.
908 // Sink the load to where the compare was, if atomic rules allow us to.
909 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
910 LI->getOrdering(), LI->getSynchScope(),
911 LI->isUnordered() ? (Instruction*)ICI : LI);
913 switch (ICI->getPredicate()) {
914 default: llvm_unreachable("Unknown ICmp Predicate!");
915 case ICmpInst::ICMP_ULT:
916 case ICmpInst::ICMP_SLT: // X < null -> always false
917 LV = ConstantInt::getFalse(GV->getContext());
919 case ICmpInst::ICMP_ULE:
920 case ICmpInst::ICMP_SLE:
921 case ICmpInst::ICMP_EQ:
922 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
924 case ICmpInst::ICMP_NE:
925 case ICmpInst::ICMP_UGE:
926 case ICmpInst::ICMP_SGE:
927 case ICmpInst::ICMP_UGT:
928 case ICmpInst::ICMP_SGT:
931 ICI->replaceAllUsesWith(LV);
932 ICI->eraseFromParent();
934 LI->eraseFromParent();
937 // If the initialization boolean was used, insert it, otherwise delete it.
939 while (!InitBool->use_empty()) // Delete initializations
940 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
943 GV->getParent()->getGlobalList().insert(GV, InitBool);
945 // Now the GV is dead, nuke it and the malloc..
946 GV->eraseFromParent();
947 CI->eraseFromParent();
949 // To further other optimizations, loop over all users of NewGV and try to
950 // constant prop them. This will promote GEP instructions with constant
951 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
952 ConstantPropUsersOf(NewGV, TD, TLI);
953 if (RepValue != NewGV)
954 ConstantPropUsersOf(RepValue, TD, TLI);
959 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
960 /// to make sure that there are no complex uses of V. We permit simple things
961 /// like dereferencing the pointer, but not storing through the address, unless
962 /// it is to the specified global.
963 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
964 const GlobalVariable *GV,
965 SmallPtrSet<const PHINode*, 8> &PHIs) {
966 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
968 const Instruction *Inst = cast<Instruction>(*UI);
970 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
971 continue; // Fine, ignore.
974 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
975 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
976 return false; // Storing the pointer itself... bad.
977 continue; // Otherwise, storing through it, or storing into GV... fine.
980 // Must index into the array and into the struct.
981 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
982 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
987 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
988 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
991 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
996 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
997 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1007 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1008 /// somewhere. Transform all uses of the allocation into loads from the
1009 /// global and uses of the resultant pointer. Further, delete the store into
1010 /// GV. This assumes that these value pass the
1011 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1012 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1013 GlobalVariable *GV) {
1014 while (!Alloc->use_empty()) {
1015 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1016 Instruction *InsertPt = U;
1017 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1018 // If this is the store of the allocation into the global, remove it.
1019 if (SI->getOperand(1) == GV) {
1020 SI->eraseFromParent();
1023 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1024 // Insert the load in the corresponding predecessor, not right before the
1026 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1027 } else if (isa<BitCastInst>(U)) {
1028 // Must be bitcast between the malloc and store to initialize the global.
1029 ReplaceUsesOfMallocWithGlobal(U, GV);
1030 U->eraseFromParent();
1032 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1033 // If this is a "GEP bitcast" and the user is a store to the global, then
1034 // just process it as a bitcast.
1035 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1036 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1037 if (SI->getOperand(1) == GV) {
1038 // Must be bitcast GEP between the malloc and store to initialize
1040 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1041 GEPI->eraseFromParent();
1046 // Insert a load from the global, and use it instead of the malloc.
1047 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1048 U->replaceUsesOfWith(Alloc, NL);
1052 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1053 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1054 /// that index through the array and struct field, icmps of null, and PHIs.
1055 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1056 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1057 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1058 // We permit two users of the load: setcc comparing against the null
1059 // pointer, and a getelementptr of a specific form.
1060 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1062 const Instruction *User = cast<Instruction>(*UI);
1064 // Comparison against null is ok.
1065 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1066 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1071 // getelementptr is also ok, but only a simple form.
1072 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1073 // Must index into the array and into the struct.
1074 if (GEPI->getNumOperands() < 3)
1077 // Otherwise the GEP is ok.
1081 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1082 if (!LoadUsingPHIsPerLoad.insert(PN))
1083 // This means some phi nodes are dependent on each other.
1084 // Avoid infinite looping!
1086 if (!LoadUsingPHIs.insert(PN))
1087 // If we have already analyzed this PHI, then it is safe.
1090 // Make sure all uses of the PHI are simple enough to transform.
1091 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1092 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1098 // Otherwise we don't know what this is, not ok.
1106 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1107 /// GV are simple enough to perform HeapSRA, return true.
1108 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1109 Instruction *StoredVal) {
1110 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1111 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1112 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1114 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1115 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1116 LoadUsingPHIsPerLoad))
1118 LoadUsingPHIsPerLoad.clear();
1121 // If we reach here, we know that all uses of the loads and transitive uses
1122 // (through PHI nodes) are simple enough to transform. However, we don't know
1123 // that all inputs the to the PHI nodes are in the same equivalence sets.
1124 // Check to verify that all operands of the PHIs are either PHIS that can be
1125 // transformed, loads from GV, or MI itself.
1126 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1127 , E = LoadUsingPHIs.end(); I != E; ++I) {
1128 const PHINode *PN = *I;
1129 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1130 Value *InVal = PN->getIncomingValue(op);
1132 // PHI of the stored value itself is ok.
1133 if (InVal == StoredVal) continue;
1135 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1136 // One of the PHIs in our set is (optimistically) ok.
1137 if (LoadUsingPHIs.count(InPN))
1142 // Load from GV is ok.
1143 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1144 if (LI->getOperand(0) == GV)
1149 // Anything else is rejected.
1157 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1158 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1159 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1160 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1162 if (FieldNo >= FieldVals.size())
1163 FieldVals.resize(FieldNo+1);
1165 // If we already have this value, just reuse the previously scalarized
1167 if (Value *FieldVal = FieldVals[FieldNo])
1170 // Depending on what instruction this is, we have several cases.
1172 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1173 // This is a scalarized version of the load from the global. Just create
1174 // a new Load of the scalarized global.
1175 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1176 InsertedScalarizedValues,
1178 LI->getName()+".f"+Twine(FieldNo), LI);
1179 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1180 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1182 StructType *ST = cast<StructType>(PN->getType()->getPointerElementType());
1185 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1186 PN->getNumIncomingValues(),
1187 PN->getName()+".f"+Twine(FieldNo), PN);
1189 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1191 llvm_unreachable("Unknown usable value");
1194 return FieldVals[FieldNo] = Result;
1197 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1198 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1199 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1200 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1201 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1202 // If this is a comparison against null, handle it.
1203 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1204 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1205 // If we have a setcc of the loaded pointer, we can use a setcc of any
1207 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1208 InsertedScalarizedValues, PHIsToRewrite);
1210 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1211 Constant::getNullValue(NPtr->getType()),
1213 SCI->replaceAllUsesWith(New);
1214 SCI->eraseFromParent();
1218 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1219 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1220 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1221 && "Unexpected GEPI!");
1223 // Load the pointer for this field.
1224 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1225 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1226 InsertedScalarizedValues, PHIsToRewrite);
1228 // Create the new GEP idx vector.
1229 SmallVector<Value*, 8> GEPIdx;
1230 GEPIdx.push_back(GEPI->getOperand(1));
1231 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1233 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
1234 GEPI->getName(), GEPI);
1235 GEPI->replaceAllUsesWith(NGEPI);
1236 GEPI->eraseFromParent();
1240 // Recursively transform the users of PHI nodes. This will lazily create the
1241 // PHIs that are needed for individual elements. Keep track of what PHIs we
1242 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1243 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1244 // already been seen first by another load, so its uses have already been
1246 PHINode *PN = cast<PHINode>(LoadUser);
1247 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1248 std::vector<Value*>())).second)
1251 // If this is the first time we've seen this PHI, recursively process all
1253 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1254 Instruction *User = cast<Instruction>(*UI++);
1255 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1259 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1260 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1261 /// use FieldGlobals instead. All uses of loaded values satisfy
1262 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1263 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1264 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1265 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1266 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1268 Instruction *User = cast<Instruction>(*UI++);
1269 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1272 if (Load->use_empty()) {
1273 Load->eraseFromParent();
1274 InsertedScalarizedValues.erase(Load);
1278 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1279 /// it up into multiple allocations of arrays of the fields.
1280 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1281 Value *NElems, DataLayout *TD,
1282 const TargetLibraryInfo *TLI) {
1283 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1284 Type *MAT = getMallocAllocatedType(CI, TLI);
1285 StructType *STy = cast<StructType>(MAT);
1287 // There is guaranteed to be at least one use of the malloc (storing
1288 // it into GV). If there are other uses, change them to be uses of
1289 // the global to simplify later code. This also deletes the store
1291 ReplaceUsesOfMallocWithGlobal(CI, GV);
1293 // Okay, at this point, there are no users of the malloc. Insert N
1294 // new mallocs at the same place as CI, and N globals.
1295 std::vector<Value*> FieldGlobals;
1296 std::vector<Value*> FieldMallocs;
1298 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1299 Type *FieldTy = STy->getElementType(FieldNo);
1300 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1302 GlobalVariable *NGV =
1303 new GlobalVariable(*GV->getParent(),
1304 PFieldTy, false, GlobalValue::InternalLinkage,
1305 Constant::getNullValue(PFieldTy),
1306 GV->getName() + ".f" + Twine(FieldNo), GV,
1307 GV->getThreadLocalMode());
1308 FieldGlobals.push_back(NGV);
1310 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1311 if (StructType *ST = dyn_cast<StructType>(FieldTy))
1312 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1313 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
1314 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1315 ConstantInt::get(IntPtrTy, TypeSize),
1317 CI->getName() + ".f" + Twine(FieldNo));
1318 FieldMallocs.push_back(NMI);
1319 new StoreInst(NMI, NGV, CI);
1322 // The tricky aspect of this transformation is handling the case when malloc
1323 // fails. In the original code, malloc failing would set the result pointer
1324 // of malloc to null. In this case, some mallocs could succeed and others
1325 // could fail. As such, we emit code that looks like this:
1326 // F0 = malloc(field0)
1327 // F1 = malloc(field1)
1328 // F2 = malloc(field2)
1329 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1330 // if (F0) { free(F0); F0 = 0; }
1331 // if (F1) { free(F1); F1 = 0; }
1332 // if (F2) { free(F2); F2 = 0; }
1334 // The malloc can also fail if its argument is too large.
1335 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1336 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1337 ConstantZero, "isneg");
1338 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1339 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1340 Constant::getNullValue(FieldMallocs[i]->getType()),
1342 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1345 // Split the basic block at the old malloc.
1346 BasicBlock *OrigBB = CI->getParent();
1347 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1349 // Create the block to check the first condition. Put all these blocks at the
1350 // end of the function as they are unlikely to be executed.
1351 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1353 OrigBB->getParent());
1355 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1356 // branch on RunningOr.
1357 OrigBB->getTerminator()->eraseFromParent();
1358 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1360 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1361 // pointer, because some may be null while others are not.
1362 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1363 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1364 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1365 Constant::getNullValue(GVVal->getType()));
1366 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1367 OrigBB->getParent());
1368 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1369 OrigBB->getParent());
1370 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1373 // Fill in FreeBlock.
1374 CallInst::CreateFree(GVVal, BI);
1375 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1377 BranchInst::Create(NextBlock, FreeBlock);
1379 NullPtrBlock = NextBlock;
1382 BranchInst::Create(ContBB, NullPtrBlock);
1384 // CI is no longer needed, remove it.
1385 CI->eraseFromParent();
1387 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1388 /// update all uses of the load, keep track of what scalarized loads are
1389 /// inserted for a given load.
1390 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1391 InsertedScalarizedValues[GV] = FieldGlobals;
1393 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1395 // Okay, the malloc site is completely handled. All of the uses of GV are now
1396 // loads, and all uses of those loads are simple. Rewrite them to use loads
1397 // of the per-field globals instead.
1398 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1399 Instruction *User = cast<Instruction>(*UI++);
1401 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1402 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1406 // Must be a store of null.
1407 StoreInst *SI = cast<StoreInst>(User);
1408 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1409 "Unexpected heap-sra user!");
1411 // Insert a store of null into each global.
1412 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1413 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1414 Constant *Null = Constant::getNullValue(PT->getElementType());
1415 new StoreInst(Null, FieldGlobals[i], SI);
1417 // Erase the original store.
1418 SI->eraseFromParent();
1421 // While we have PHIs that are interesting to rewrite, do it.
1422 while (!PHIsToRewrite.empty()) {
1423 PHINode *PN = PHIsToRewrite.back().first;
1424 unsigned FieldNo = PHIsToRewrite.back().second;
1425 PHIsToRewrite.pop_back();
1426 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1427 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1429 // Add all the incoming values. This can materialize more phis.
1430 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1431 Value *InVal = PN->getIncomingValue(i);
1432 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1434 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1438 // Drop all inter-phi links and any loads that made it this far.
1439 for (DenseMap<Value*, std::vector<Value*> >::iterator
1440 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1442 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1443 PN->dropAllReferences();
1444 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1445 LI->dropAllReferences();
1448 // Delete all the phis and loads now that inter-references are dead.
1449 for (DenseMap<Value*, std::vector<Value*> >::iterator
1450 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1452 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1453 PN->eraseFromParent();
1454 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1455 LI->eraseFromParent();
1458 // The old global is now dead, remove it.
1459 GV->eraseFromParent();
1462 return cast<GlobalVariable>(FieldGlobals[0]);
1465 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1466 /// pointer global variable with a single value stored it that is a malloc or
1468 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1471 AtomicOrdering Ordering,
1472 Module::global_iterator &GVI,
1474 TargetLibraryInfo *TLI) {
1478 // If this is a malloc of an abstract type, don't touch it.
1479 if (!AllocTy->isSized())
1482 // We can't optimize this global unless all uses of it are *known* to be
1483 // of the malloc value, not of the null initializer value (consider a use
1484 // that compares the global's value against zero to see if the malloc has
1485 // been reached). To do this, we check to see if all uses of the global
1486 // would trap if the global were null: this proves that they must all
1487 // happen after the malloc.
1488 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1491 // We can't optimize this if the malloc itself is used in a complex way,
1492 // for example, being stored into multiple globals. This allows the
1493 // malloc to be stored into the specified global, loaded icmp'd, and
1494 // GEP'd. These are all things we could transform to using the global
1496 SmallPtrSet<const PHINode*, 8> PHIs;
1497 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1500 // If we have a global that is only initialized with a fixed size malloc,
1501 // transform the program to use global memory instead of malloc'd memory.
1502 // This eliminates dynamic allocation, avoids an indirection accessing the
1503 // data, and exposes the resultant global to further GlobalOpt.
1504 // We cannot optimize the malloc if we cannot determine malloc array size.
1505 Value *NElems = getMallocArraySize(CI, TD, TLI, true);
1509 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1510 // Restrict this transformation to only working on small allocations
1511 // (2048 bytes currently), as we don't want to introduce a 16M global or
1513 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1514 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
1518 // If the allocation is an array of structures, consider transforming this
1519 // into multiple malloc'd arrays, one for each field. This is basically
1520 // SRoA for malloc'd memory.
1522 if (Ordering != NotAtomic)
1525 // If this is an allocation of a fixed size array of structs, analyze as a
1526 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1527 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1528 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1529 AllocTy = AT->getElementType();
1531 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1535 // This the structure has an unreasonable number of fields, leave it
1537 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1538 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1540 // If this is a fixed size array, transform the Malloc to be an alloc of
1541 // structs. malloc [100 x struct],1 -> malloc struct, 100
1542 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
1543 Type *IntPtrTy = TD->getIntPtrType(CI->getType());
1544 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1545 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1546 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1547 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1548 AllocSize, NumElements,
1550 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1551 CI->replaceAllUsesWith(Cast);
1552 CI->eraseFromParent();
1553 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1554 CI = cast<CallInst>(BCI->getOperand(0));
1556 CI = cast<CallInst>(Malloc);
1559 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
1567 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1568 // that only one value (besides its initializer) is ever stored to the global.
1569 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1570 AtomicOrdering Ordering,
1571 Module::global_iterator &GVI,
1572 DataLayout *TD, TargetLibraryInfo *TLI) {
1573 // Ignore no-op GEPs and bitcasts.
1574 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1576 // If we are dealing with a pointer global that is initialized to null and
1577 // only has one (non-null) value stored into it, then we can optimize any
1578 // users of the loaded value (often calls and loads) that would trap if the
1580 if (GV->getInitializer()->getType()->isPointerTy() &&
1581 GV->getInitializer()->isNullValue()) {
1582 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1583 if (GV->getInitializer()->getType() != SOVC->getType())
1584 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1586 // Optimize away any trapping uses of the loaded value.
1587 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
1589 } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
1590 Type *MallocType = getMallocAllocatedType(CI, TLI);
1592 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1601 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1602 /// two values ever stored into GV are its initializer and OtherVal. See if we
1603 /// can shrink the global into a boolean and select between the two values
1604 /// whenever it is used. This exposes the values to other scalar optimizations.
1605 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1606 Type *GVElType = GV->getType()->getElementType();
1608 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1609 // an FP value, pointer or vector, don't do this optimization because a select
1610 // between them is very expensive and unlikely to lead to later
1611 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1612 // where v1 and v2 both require constant pool loads, a big loss.
1613 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1614 GVElType->isFloatingPointTy() ||
1615 GVElType->isPointerTy() || GVElType->isVectorTy())
1618 // Walk the use list of the global seeing if all the uses are load or store.
1619 // If there is anything else, bail out.
1620 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1622 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1626 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1628 // Create the new global, initializing it to false.
1629 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1631 GlobalValue::InternalLinkage,
1632 ConstantInt::getFalse(GV->getContext()),
1634 GV->getThreadLocalMode(),
1635 GV->getType()->getAddressSpace());
1636 GV->getParent()->getGlobalList().insert(GV, NewGV);
1638 Constant *InitVal = GV->getInitializer();
1639 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1640 "No reason to shrink to bool!");
1642 // If initialized to zero and storing one into the global, we can use a cast
1643 // instead of a select to synthesize the desired value.
1644 bool IsOneZero = false;
1645 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1646 IsOneZero = InitVal->isNullValue() && CI->isOne();
1648 while (!GV->use_empty()) {
1649 Instruction *UI = cast<Instruction>(GV->use_back());
1650 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1651 // Change the store into a boolean store.
1652 bool StoringOther = SI->getOperand(0) == OtherVal;
1653 // Only do this if we weren't storing a loaded value.
1655 if (StoringOther || SI->getOperand(0) == InitVal) {
1656 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1659 // Otherwise, we are storing a previously loaded copy. To do this,
1660 // change the copy from copying the original value to just copying the
1662 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1664 // If we've already replaced the input, StoredVal will be a cast or
1665 // select instruction. If not, it will be a load of the original
1667 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1668 assert(LI->getOperand(0) == GV && "Not a copy!");
1669 // Insert a new load, to preserve the saved value.
1670 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1671 LI->getOrdering(), LI->getSynchScope(), LI);
1673 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1674 "This is not a form that we understand!");
1675 StoreVal = StoredVal->getOperand(0);
1676 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1679 new StoreInst(StoreVal, NewGV, false, 0,
1680 SI->getOrdering(), SI->getSynchScope(), SI);
1682 // Change the load into a load of bool then a select.
1683 LoadInst *LI = cast<LoadInst>(UI);
1684 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1685 LI->getOrdering(), LI->getSynchScope(), LI);
1688 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1690 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1692 LI->replaceAllUsesWith(NSI);
1694 UI->eraseFromParent();
1697 // Retain the name of the old global variable. People who are debugging their
1698 // programs may expect these variables to be named the same.
1699 NewGV->takeName(GV);
1700 GV->eraseFromParent();
1705 /// ProcessGlobal - Analyze the specified global variable and optimize it if
1706 /// possible. If we make a change, return true.
1707 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1708 Module::global_iterator &GVI) {
1709 if (!GV->isDiscardableIfUnused())
1712 // Do more involved optimizations if the global is internal.
1713 GV->removeDeadConstantUsers();
1715 if (GV->use_empty()) {
1716 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1717 GV->eraseFromParent();
1722 if (!GV->hasLocalLinkage())
1727 if (GlobalStatus::analyzeGlobal(GV, GS))
1730 if (!GS.IsCompared && !GV->hasUnnamedAddr()) {
1731 GV->setUnnamedAddr(true);
1735 if (GV->isConstant() || !GV->hasInitializer())
1738 return ProcessInternalGlobal(GV, GVI, GS);
1741 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1742 /// it if possible. If we make a change, return true.
1743 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1744 Module::global_iterator &GVI,
1745 const GlobalStatus &GS) {
1746 // If this is a first class global and has only one accessing function
1747 // and this function is main (which we know is not recursive), we replace
1748 // the global with a local alloca in this function.
1750 // NOTE: It doesn't make sense to promote non-single-value types since we
1751 // are just replacing static memory to stack memory.
1753 // If the global is in different address space, don't bring it to stack.
1754 if (!GS.HasMultipleAccessingFunctions &&
1755 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1756 GV->getType()->getElementType()->isSingleValueType() &&
1757 GS.AccessingFunction->getName() == "main" &&
1758 GS.AccessingFunction->hasExternalLinkage() &&
1759 GV->getType()->getAddressSpace() == 0) {
1760 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1761 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1762 ->getEntryBlock().begin());
1763 Type *ElemTy = GV->getType()->getElementType();
1764 // FIXME: Pass Global's alignment when globals have alignment
1765 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1766 if (!isa<UndefValue>(GV->getInitializer()))
1767 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1769 GV->replaceAllUsesWith(Alloca);
1770 GV->eraseFromParent();
1775 // If the global is never loaded (but may be stored to), it is dead.
1778 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1781 if (isLeakCheckerRoot(GV)) {
1782 // Delete any constant stores to the global.
1783 Changed = CleanupPointerRootUsers(GV, TLI);
1785 // Delete any stores we can find to the global. We may not be able to
1786 // make it completely dead though.
1787 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1790 // If the global is dead now, delete it.
1791 if (GV->use_empty()) {
1792 GV->eraseFromParent();
1798 } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
1799 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
1800 GV->setConstant(true);
1802 // Clean up any obviously simplifiable users now.
1803 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1805 // If the global is dead now, just nuke it.
1806 if (GV->use_empty()) {
1807 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1808 << "all users and delete global!\n");
1809 GV->eraseFromParent();
1815 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1816 if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
1817 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1818 GVI = FirstNewGV; // Don't skip the newly produced globals!
1821 } else if (GS.StoredType == GlobalStatus::StoredOnce) {
1822 // If the initial value for the global was an undef value, and if only
1823 // one other value was stored into it, we can just change the
1824 // initializer to be the stored value, then delete all stores to the
1825 // global. This allows us to mark it constant.
1826 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1827 if (isa<UndefValue>(GV->getInitializer())) {
1828 // Change the initial value here.
1829 GV->setInitializer(SOVConstant);
1831 // Clean up any obviously simplifiable users now.
1832 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1834 if (GV->use_empty()) {
1835 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1836 << "simplify all users and delete global!\n");
1837 GV->eraseFromParent();
1846 // Try to optimize globals based on the knowledge that only one value
1847 // (besides its initializer) is ever stored to the global.
1848 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
1852 // Otherwise, if the global was not a boolean, we can shrink it to be a
1854 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
1855 if (GS.Ordering == NotAtomic) {
1856 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1867 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1868 /// function, changing them to FastCC.
1869 static void ChangeCalleesToFastCall(Function *F) {
1870 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1871 if (isa<BlockAddress>(*UI))
1873 CallSite User(cast<Instruction>(*UI));
1874 User.setCallingConv(CallingConv::Fast);
1878 static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
1879 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1880 unsigned Index = Attrs.getSlotIndex(i);
1881 if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
1884 // There can be only one.
1885 return Attrs.removeAttribute(C, Index, Attribute::Nest);
1891 static void RemoveNestAttribute(Function *F) {
1892 F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
1893 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1894 if (isa<BlockAddress>(*UI))
1896 CallSite User(cast<Instruction>(*UI));
1897 User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
1901 bool GlobalOpt::OptimizeFunctions(Module &M) {
1902 bool Changed = false;
1903 // Optimize functions.
1904 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1906 // Functions without names cannot be referenced outside this module.
1907 if (!F->hasName() && !F->isDeclaration())
1908 F->setLinkage(GlobalValue::InternalLinkage);
1909 F->removeDeadConstantUsers();
1910 if (F->isDefTriviallyDead()) {
1911 F->eraseFromParent();
1914 } else if (F->hasLocalLinkage()) {
1915 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1916 !F->hasAddressTaken()) {
1917 // If this function has C calling conventions, is not a varargs
1918 // function, and is only called directly, promote it to use the Fast
1919 // calling convention.
1920 F->setCallingConv(CallingConv::Fast);
1921 ChangeCalleesToFastCall(F);
1926 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1927 !F->hasAddressTaken()) {
1928 // The function is not used by a trampoline intrinsic, so it is safe
1929 // to remove the 'nest' attribute.
1930 RemoveNestAttribute(F);
1939 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1940 bool Changed = false;
1941 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1943 GlobalVariable *GV = GVI++;
1944 // Global variables without names cannot be referenced outside this module.
1945 if (!GV->hasName() && !GV->isDeclaration())
1946 GV->setLinkage(GlobalValue::InternalLinkage);
1947 // Simplify the initializer.
1948 if (GV->hasInitializer())
1949 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1950 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
1951 if (New && New != CE)
1952 GV->setInitializer(New);
1955 Changed |= ProcessGlobal(GV, GVI);
1960 /// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
1961 /// initializers have an init priority of 65535.
1962 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1963 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1964 if (GV == 0) return 0;
1966 // Verify that the initializer is simple enough for us to handle. We are
1967 // only allowed to optimize the initializer if it is unique.
1968 if (!GV->hasUniqueInitializer()) return 0;
1970 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1972 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1974 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1975 if (isa<ConstantAggregateZero>(*i))
1977 ConstantStruct *CS = cast<ConstantStruct>(*i);
1978 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1981 // Must have a function or null ptr.
1982 if (!isa<Function>(CS->getOperand(1)))
1985 // Init priority must be standard.
1986 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1987 if (CI->getZExtValue() != 65535)
1994 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1995 /// return a list of the functions and null terminator as a vector.
1996 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1997 if (GV->getInitializer()->isNullValue())
1998 return std::vector<Function*>();
1999 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2000 std::vector<Function*> Result;
2001 Result.reserve(CA->getNumOperands());
2002 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2003 ConstantStruct *CS = cast<ConstantStruct>(*i);
2004 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2009 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2010 /// specified array, returning the new global to use.
2011 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
2012 const std::vector<Function*> &Ctors) {
2013 // If we made a change, reassemble the initializer list.
2014 Constant *CSVals[2];
2015 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2018 StructType *StructTy =
2019 cast<StructType>(GCL->getType()->getElementType()->getArrayElementType());
2021 // Create the new init list.
2022 std::vector<Constant*> CAList;
2023 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2025 CSVals[1] = Ctors[i];
2027 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2029 PointerType *PFTy = PointerType::getUnqual(FTy);
2030 CSVals[1] = Constant::getNullValue(PFTy);
2031 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2034 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
2037 // Create the array initializer.
2038 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2039 CAList.size()), CAList);
2041 // If we didn't change the number of elements, don't create a new GV.
2042 if (CA->getType() == GCL->getInitializer()->getType()) {
2043 GCL->setInitializer(CA);
2047 // Create the new global and insert it next to the existing list.
2048 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2049 GCL->getLinkage(), CA, "",
2050 GCL->getThreadLocalMode());
2051 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2054 // Nuke the old list, replacing any uses with the new one.
2055 if (!GCL->use_empty()) {
2057 if (V->getType() != GCL->getType())
2058 V = ConstantExpr::getBitCast(V, GCL->getType());
2059 GCL->replaceAllUsesWith(V);
2061 GCL->eraseFromParent();
2071 isSimpleEnoughValueToCommit(Constant *C,
2072 SmallPtrSet<Constant*, 8> &SimpleConstants,
2073 const DataLayout *TD);
2076 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2077 /// handled by the code generator. We don't want to generate something like:
2078 /// void *X = &X/42;
2079 /// because the code generator doesn't have a relocation that can handle that.
2081 /// This function should be called if C was not found (but just got inserted)
2082 /// in SimpleConstants to avoid having to rescan the same constants all the
2084 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2085 SmallPtrSet<Constant*, 8> &SimpleConstants,
2086 const DataLayout *TD) {
2087 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2089 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2090 isa<GlobalValue>(C))
2093 // Aggregate values are safe if all their elements are.
2094 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2095 isa<ConstantVector>(C)) {
2096 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2097 Constant *Op = cast<Constant>(C->getOperand(i));
2098 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
2104 // We don't know exactly what relocations are allowed in constant expressions,
2105 // so we allow &global+constantoffset, which is safe and uniformly supported
2107 ConstantExpr *CE = cast<ConstantExpr>(C);
2108 switch (CE->getOpcode()) {
2109 case Instruction::BitCast:
2110 // Bitcast is fine if the casted value is fine.
2111 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2113 case Instruction::IntToPtr:
2114 case Instruction::PtrToInt:
2115 // int <=> ptr is fine if the int type is the same size as the
2117 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2118 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2120 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2122 // GEP is fine if it is simple + constant offset.
2123 case Instruction::GetElementPtr:
2124 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2125 if (!isa<ConstantInt>(CE->getOperand(i)))
2127 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2129 case Instruction::Add:
2130 // We allow simple+cst.
2131 if (!isa<ConstantInt>(CE->getOperand(1)))
2133 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2139 isSimpleEnoughValueToCommit(Constant *C,
2140 SmallPtrSet<Constant*, 8> &SimpleConstants,
2141 const DataLayout *TD) {
2142 // If we already checked this constant, we win.
2143 if (!SimpleConstants.insert(C)) return true;
2144 // Check the constant.
2145 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
2149 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2150 /// enough for us to understand. In particular, if it is a cast to anything
2151 /// other than from one pointer type to another pointer type, we punt.
2152 /// We basically just support direct accesses to globals and GEP's of
2153 /// globals. This should be kept up to date with CommitValueTo.
2154 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2155 // Conservatively, avoid aggregate types. This is because we don't
2156 // want to worry about them partially overlapping other stores.
2157 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2160 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2161 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2162 // external globals.
2163 return GV->hasUniqueInitializer();
2165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2166 // Handle a constantexpr gep.
2167 if (CE->getOpcode() == Instruction::GetElementPtr &&
2168 isa<GlobalVariable>(CE->getOperand(0)) &&
2169 cast<GEPOperator>(CE)->isInBounds()) {
2170 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2171 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2172 // external globals.
2173 if (!GV->hasUniqueInitializer())
2176 // The first index must be zero.
2177 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
2178 if (!CI || !CI->isZero()) return false;
2180 // The remaining indices must be compile-time known integers within the
2181 // notional bounds of the corresponding static array types.
2182 if (!CE->isGEPWithNoNotionalOverIndexing())
2185 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2187 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2188 // and we know how to evaluate it by moving the bitcast from the pointer
2189 // operand to the value operand.
2190 } else if (CE->getOpcode() == Instruction::BitCast &&
2191 isa<GlobalVariable>(CE->getOperand(0))) {
2192 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2193 // external globals.
2194 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
2201 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2202 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2203 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2204 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2205 ConstantExpr *Addr, unsigned OpNo) {
2206 // Base case of the recursion.
2207 if (OpNo == Addr->getNumOperands()) {
2208 assert(Val->getType() == Init->getType() && "Type mismatch!");
2212 SmallVector<Constant*, 32> Elts;
2213 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
2214 // Break up the constant into its elements.
2215 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2216 Elts.push_back(Init->getAggregateElement(i));
2218 // Replace the element that we are supposed to.
2219 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2220 unsigned Idx = CU->getZExtValue();
2221 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2222 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2224 // Return the modified struct.
2225 return ConstantStruct::get(STy, Elts);
2228 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2229 SequentialType *InitTy = cast<SequentialType>(Init->getType());
2232 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2233 NumElts = ATy->getNumElements();
2235 NumElts = InitTy->getVectorNumElements();
2237 // Break up the array into elements.
2238 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2239 Elts.push_back(Init->getAggregateElement(i));
2241 assert(CI->getZExtValue() < NumElts);
2242 Elts[CI->getZExtValue()] =
2243 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2245 if (Init->getType()->isArrayTy())
2246 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2247 return ConstantVector::get(Elts);
2250 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2251 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2252 static void CommitValueTo(Constant *Val, Constant *Addr) {
2253 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2254 assert(GV->hasInitializer());
2255 GV->setInitializer(Val);
2259 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2260 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2261 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2266 /// Evaluator - This class evaluates LLVM IR, producing the Constant
2267 /// representing each SSA instruction. Changes to global variables are stored
2268 /// in a mapping that can be iterated over after the evaluation is complete.
2269 /// Once an evaluation call fails, the evaluation object should not be reused.
2272 Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
2273 : TD(TD), TLI(TLI) {
2274 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2278 DeleteContainerPointers(ValueStack);
2279 while (!AllocaTmps.empty()) {
2280 GlobalVariable *Tmp = AllocaTmps.back();
2281 AllocaTmps.pop_back();
2283 // If there are still users of the alloca, the program is doing something
2284 // silly, e.g. storing the address of the alloca somewhere and using it
2285 // later. Since this is undefined, we'll just make it be null.
2286 if (!Tmp->use_empty())
2287 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2292 /// EvaluateFunction - Evaluate a call to function F, returning true if
2293 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2294 /// arguments for the function.
2295 bool EvaluateFunction(Function *F, Constant *&RetVal,
2296 const SmallVectorImpl<Constant*> &ActualArgs);
2298 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2299 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2300 /// control flows into, or null upon return.
2301 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2303 Constant *getVal(Value *V) {
2304 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2305 Constant *R = ValueStack.back()->lookup(V);
2306 assert(R && "Reference to an uncomputed value!");
2310 void setVal(Value *V, Constant *C) {
2311 ValueStack.back()->operator[](V) = C;
2314 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2315 return MutatedMemory;
2318 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2323 Constant *ComputeLoadResult(Constant *P);
2325 /// ValueStack - As we compute SSA register values, we store their contents
2326 /// here. The back of the vector contains the current function and the stack
2327 /// contains the values in the calling frames.
2328 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2330 /// CallStack - This is used to detect recursion. In pathological situations
2331 /// we could hit exponential behavior, but at least there is nothing
2333 SmallVector<Function*, 4> CallStack;
2335 /// MutatedMemory - For each store we execute, we update this map. Loads
2336 /// check this to get the most up-to-date value. If evaluation is successful,
2337 /// this state is committed to the process.
2338 DenseMap<Constant*, Constant*> MutatedMemory;
2340 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2341 /// to represent its body. This vector is needed so we can delete the
2342 /// temporary globals when we are done.
2343 SmallVector<GlobalVariable*, 32> AllocaTmps;
2345 /// Invariants - These global variables have been marked invariant by the
2346 /// static constructor.
2347 SmallPtrSet<GlobalVariable*, 8> Invariants;
2349 /// SimpleConstants - These are constants we have checked and know to be
2350 /// simple enough to live in a static initializer of a global.
2351 SmallPtrSet<Constant*, 8> SimpleConstants;
2353 const DataLayout *TD;
2354 const TargetLibraryInfo *TLI;
2357 } // anonymous namespace
2359 /// ComputeLoadResult - Return the value that would be computed by a load from
2360 /// P after the stores reflected by 'memory' have been performed. If we can't
2361 /// decide, return null.
2362 Constant *Evaluator::ComputeLoadResult(Constant *P) {
2363 // If this memory location has been recently stored, use the stored value: it
2364 // is the most up-to-date.
2365 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2366 if (I != MutatedMemory.end()) return I->second;
2369 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2370 if (GV->hasDefinitiveInitializer())
2371 return GV->getInitializer();
2375 // Handle a constantexpr getelementptr.
2376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2377 if (CE->getOpcode() == Instruction::GetElementPtr &&
2378 isa<GlobalVariable>(CE->getOperand(0))) {
2379 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2380 if (GV->hasDefinitiveInitializer())
2381 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2384 return 0; // don't know how to evaluate.
2387 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2388 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2389 /// control flows into, or null upon return.
2390 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2391 BasicBlock *&NextBB) {
2392 // This is the main evaluation loop.
2394 Constant *InstResult = 0;
2396 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
2398 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2399 if (!SI->isSimple()) {
2400 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
2401 return false; // no volatile/atomic accesses.
2403 Constant *Ptr = getVal(SI->getOperand(1));
2404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
2405 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
2406 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2407 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
2409 if (!isSimpleEnoughPointerToCommit(Ptr)) {
2410 // If this is too complex for us to commit, reject it.
2411 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
2415 Constant *Val = getVal(SI->getOperand(0));
2417 // If this might be too difficult for the backend to handle (e.g. the addr
2418 // of one global variable divided by another) then we can't commit it.
2419 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
2420 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
2425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
2426 if (CE->getOpcode() == Instruction::BitCast) {
2427 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
2428 // If we're evaluating a store through a bitcast, then we need
2429 // to pull the bitcast off the pointer type and push it onto the
2431 Ptr = CE->getOperand(0);
2433 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
2435 // In order to push the bitcast onto the stored value, a bitcast
2436 // from NewTy to Val's type must be legal. If it's not, we can try
2437 // introspecting NewTy to find a legal conversion.
2438 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2439 // If NewTy is a struct, we can convert the pointer to the struct
2440 // into a pointer to its first member.
2441 // FIXME: This could be extended to support arrays as well.
2442 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
2443 NewTy = STy->getTypeAtIndex(0U);
2445 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
2446 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2447 Constant * const IdxList[] = {IdxZero, IdxZero};
2449 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
2450 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2451 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2453 // If we can't improve the situation by introspecting NewTy,
2454 // we have to give up.
2456 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
2462 // If we found compatible types, go ahead and push the bitcast
2463 // onto the stored value.
2464 Val = ConstantExpr::getBitCast(Val, NewTy);
2466 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
2470 MutatedMemory[Ptr] = Val;
2471 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2472 InstResult = ConstantExpr::get(BO->getOpcode(),
2473 getVal(BO->getOperand(0)),
2474 getVal(BO->getOperand(1)));
2475 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
2477 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2478 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2479 getVal(CI->getOperand(0)),
2480 getVal(CI->getOperand(1)));
2481 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
2483 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2484 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2485 getVal(CI->getOperand(0)),
2487 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
2489 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2490 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2491 getVal(SI->getOperand(1)),
2492 getVal(SI->getOperand(2)));
2493 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
2495 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2496 Constant *P = getVal(GEP->getOperand(0));
2497 SmallVector<Constant*, 8> GEPOps;
2498 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2500 GEPOps.push_back(getVal(*i));
2502 ConstantExpr::getGetElementPtr(P, GEPOps,
2503 cast<GEPOperator>(GEP)->isInBounds());
2504 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
2506 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2508 if (!LI->isSimple()) {
2509 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
2510 return false; // no volatile/atomic accesses.
2513 Constant *Ptr = getVal(LI->getOperand(0));
2514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
2515 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2516 DEBUG(dbgs() << "Found a constant pointer expression, constant "
2517 "folding: " << *Ptr << "\n");
2519 InstResult = ComputeLoadResult(Ptr);
2520 if (InstResult == 0) {
2521 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
2523 return false; // Could not evaluate load.
2526 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
2527 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2528 if (AI->isArrayAllocation()) {
2529 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
2530 return false; // Cannot handle array allocs.
2532 Type *Ty = AI->getType()->getElementType();
2533 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2534 GlobalValue::InternalLinkage,
2535 UndefValue::get(Ty),
2537 InstResult = AllocaTmps.back();
2538 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
2539 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2540 CallSite CS(CurInst);
2542 // Debug info can safely be ignored here.
2543 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
2544 DEBUG(dbgs() << "Ignoring debug info.\n");
2549 // Cannot handle inline asm.
2550 if (isa<InlineAsm>(CS.getCalledValue())) {
2551 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
2555 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2556 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2557 if (MSI->isVolatile()) {
2558 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
2562 Constant *Ptr = getVal(MSI->getDest());
2563 Constant *Val = getVal(MSI->getValue());
2564 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
2565 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2566 // This memset is a no-op.
2567 DEBUG(dbgs() << "Ignoring no-op memset.\n");
2573 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2574 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2575 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
2580 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2581 // We don't insert an entry into Values, as it doesn't have a
2582 // meaningful return value.
2583 if (!II->use_empty()) {
2584 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
2587 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
2588 Value *PtrArg = getVal(II->getArgOperand(1));
2589 Value *Ptr = PtrArg->stripPointerCasts();
2590 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2591 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2592 if (TD && !Size->isAllOnesValue() &&
2593 Size->getValue().getLimitedValue() >=
2594 TD->getTypeStoreSize(ElemTy)) {
2595 Invariants.insert(GV);
2596 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
2599 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
2603 // Continue even if we do nothing.
2608 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
2612 // Resolve function pointers.
2613 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
2614 if (!Callee || Callee->mayBeOverridden()) {
2615 DEBUG(dbgs() << "Can not resolve function pointer.\n");
2616 return false; // Cannot resolve.
2619 SmallVector<Constant*, 8> Formals;
2620 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
2621 Formals.push_back(getVal(*i));
2623 if (Callee->isDeclaration()) {
2624 // If this is a function we can constant fold, do it.
2625 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
2627 DEBUG(dbgs() << "Constant folded function call. Result: " <<
2628 *InstResult << "\n");
2630 DEBUG(dbgs() << "Can not constant fold function call.\n");
2634 if (Callee->getFunctionType()->isVarArg()) {
2635 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
2639 Constant *RetVal = 0;
2640 // Execute the call, if successful, use the return value.
2641 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2642 if (!EvaluateFunction(Callee, RetVal, Formals)) {
2643 DEBUG(dbgs() << "Failed to evaluate function.\n");
2646 delete ValueStack.pop_back_val();
2647 InstResult = RetVal;
2649 if (InstResult != NULL) {
2650 DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
2651 InstResult << "\n\n");
2653 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
2656 } else if (isa<TerminatorInst>(CurInst)) {
2657 DEBUG(dbgs() << "Found a terminator instruction.\n");
2659 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2660 if (BI->isUnconditional()) {
2661 NextBB = BI->getSuccessor(0);
2664 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
2665 if (!Cond) return false; // Cannot determine.
2667 NextBB = BI->getSuccessor(!Cond->getZExtValue());
2669 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2671 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
2672 if (!Val) return false; // Cannot determine.
2673 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
2674 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2675 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
2676 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2677 NextBB = BA->getBasicBlock();
2679 return false; // Cannot determine.
2680 } else if (isa<ReturnInst>(CurInst)) {
2683 // invoke, unwind, resume, unreachable.
2684 DEBUG(dbgs() << "Can not handle terminator.");
2685 return false; // Cannot handle this terminator.
2688 // We succeeded at evaluating this block!
2689 DEBUG(dbgs() << "Successfully evaluated block.\n");
2692 // Did not know how to evaluate this!
2693 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
2698 if (!CurInst->use_empty()) {
2699 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2700 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
2702 setVal(CurInst, InstResult);
2705 // If we just processed an invoke, we finished evaluating the block.
2706 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2707 NextBB = II->getNormalDest();
2708 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
2712 // Advance program counter.
2717 /// EvaluateFunction - Evaluate a call to function F, returning true if
2718 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2719 /// arguments for the function.
2720 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2721 const SmallVectorImpl<Constant*> &ActualArgs) {
2722 // Check to see if this function is already executing (recursion). If so,
2723 // bail out. TODO: we might want to accept limited recursion.
2724 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2727 CallStack.push_back(F);
2729 // Initialize arguments to the incoming values specified.
2731 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2733 setVal(AI, ActualArgs[ArgNo]);
2735 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2736 // we can only evaluate any one basic block at most once. This set keeps
2737 // track of what we have executed so we can detect recursive cases etc.
2738 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2740 // CurBB - The current basic block we're evaluating.
2741 BasicBlock *CurBB = F->begin();
2743 BasicBlock::iterator CurInst = CurBB->begin();
2746 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
2747 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
2749 if (!EvaluateBlock(CurInst, NextBB))
2753 // Successfully running until there's no next block means that we found
2754 // the return. Fill it the return value and pop the call stack.
2755 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2756 if (RI->getNumOperands())
2757 RetVal = getVal(RI->getOperand(0));
2758 CallStack.pop_back();
2762 // Okay, we succeeded in evaluating this control flow. See if we have
2763 // executed the new block before. If so, we have a looping function,
2764 // which we cannot evaluate in reasonable time.
2765 if (!ExecutedBlocks.insert(NextBB))
2766 return false; // looped!
2768 // Okay, we have never been in this block before. Check to see if there
2769 // are any PHI nodes. If so, evaluate them with information about where
2772 for (CurInst = NextBB->begin();
2773 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2774 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
2776 // Advance to the next block.
2781 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2782 /// we can. Return true if we can, false otherwise.
2783 static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
2784 const TargetLibraryInfo *TLI) {
2785 // Call the function.
2786 Evaluator Eval(TD, TLI);
2787 Constant *RetValDummy;
2788 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2789 SmallVector<Constant*, 0>());
2792 // We succeeded at evaluation: commit the result.
2793 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2794 << F->getName() << "' to " << Eval.getMutatedMemory().size()
2796 for (DenseMap<Constant*, Constant*>::const_iterator I =
2797 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2799 CommitValueTo(I->second, I->first);
2800 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2801 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2803 (*I)->setConstant(true);
2809 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2810 /// Return true if anything changed.
2811 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2812 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2813 bool MadeChange = false;
2814 if (Ctors.empty()) return false;
2816 // Loop over global ctors, optimizing them when we can.
2817 for (unsigned i = 0; i != Ctors.size(); ++i) {
2818 Function *F = Ctors[i];
2819 // Found a null terminator in the middle of the list, prune off the rest of
2822 if (i != Ctors.size()-1) {
2828 DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
2830 // We cannot simplify external ctor functions.
2831 if (F->empty()) continue;
2833 // If we can evaluate the ctor at compile time, do.
2834 if (EvaluateStaticConstructor(F, TD, TLI)) {
2835 Ctors.erase(Ctors.begin()+i);
2838 ++NumCtorsEvaluated;
2843 if (!MadeChange) return false;
2845 GCL = InstallGlobalCtors(GCL, Ctors);
2849 static int compareNames(Constant *const *A, Constant *const *B) {
2850 return (*A)->getName().compare((*B)->getName());
2853 static void setUsedInitializer(GlobalVariable &V,
2854 SmallPtrSet<GlobalValue *, 8> Init) {
2856 V.eraseFromParent();
2860 // Type of pointer to the array of pointers.
2861 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
2863 SmallVector<llvm::Constant *, 8> UsedArray;
2864 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Init.begin(), E = Init.end();
2867 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(*I, Int8PtrTy);
2868 UsedArray.push_back(Cast);
2870 // Sort to get deterministic order.
2871 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2872 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
2874 Module *M = V.getParent();
2875 V.removeFromParent();
2876 GlobalVariable *NV =
2877 new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
2878 llvm::ConstantArray::get(ATy, UsedArray), "");
2880 NV->setSection("llvm.metadata");
2885 /// \brief An easy to access representation of llvm.used and llvm.compiler.used.
2887 SmallPtrSet<GlobalValue *, 8> Used;
2888 SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2889 GlobalVariable *UsedV;
2890 GlobalVariable *CompilerUsedV;
2893 LLVMUsed(Module &M) {
2894 UsedV = collectUsedGlobalVariables(M, Used, false);
2895 CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
2897 typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
2898 iterator usedBegin() { return Used.begin(); }
2899 iterator usedEnd() { return Used.end(); }
2900 iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2901 iterator compilerUsedEnd() { return CompilerUsed.end(); }
2902 bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2903 bool compilerUsedCount(GlobalValue *GV) const {
2904 return CompilerUsed.count(GV);
2906 bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2907 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2908 bool usedInsert(GlobalValue *GV) { return Used.insert(GV); }
2909 bool compilerUsedInsert(GlobalValue *GV) { return CompilerUsed.insert(GV); }
2911 void syncVariablesAndSets() {
2913 setUsedInitializer(*UsedV, Used);
2915 setUsedInitializer(*CompilerUsedV, CompilerUsed);
2920 static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2921 if (GA.use_empty()) // No use at all.
2924 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2925 "We should have removed the duplicated "
2926 "element from llvm.compiler.used");
2927 if (!GA.hasOneUse())
2928 // Strictly more than one use. So at least one is not in llvm.used and
2929 // llvm.compiler.used.
2932 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
2933 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2936 static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2937 const LLVMUsed &U) {
2939 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2940 "We should have removed the duplicated "
2941 "element from llvm.compiler.used");
2942 if (U.usedCount(&V) || U.compilerUsedCount(&V))
2944 return V.hasNUsesOrMore(N);
2947 static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2948 if (!GA.hasLocalLinkage())
2951 return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2954 static bool hasUsesToReplace(GlobalAlias &GA, LLVMUsed &U, bool &RenameTarget) {
2955 RenameTarget = false;
2957 if (hasUseOtherThanLLVMUsed(GA, U))
2960 // If the alias is externally visible, we may still be able to simplify it.
2961 if (!mayHaveOtherReferences(GA, U))
2964 // If the aliasee has internal linkage, give it the name and linkage
2965 // of the alias, and delete the alias. This turns:
2966 // define internal ... @f(...)
2967 // @a = alias ... @f
2969 // define ... @a(...)
2970 Constant *Aliasee = GA.getAliasee();
2971 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2972 if (!Target->hasLocalLinkage())
2975 // Do not perform the transform if multiple aliases potentially target the
2976 // aliasee. This check also ensures that it is safe to replace the section
2977 // and other attributes of the aliasee with those of the alias.
2978 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2981 RenameTarget = true;
2985 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2986 bool Changed = false;
2989 for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.usedBegin(),
2992 Used.compilerUsedErase(*I);
2994 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2996 Module::alias_iterator J = I++;
2997 // Aliases without names cannot be referenced outside this module.
2998 if (!J->hasName() && !J->isDeclaration())
2999 J->setLinkage(GlobalValue::InternalLinkage);
3000 // If the aliasee may change at link time, nothing can be done - bail out.
3001 if (J->mayBeOverridden())
3004 Constant *Aliasee = J->getAliasee();
3005 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
3006 Target->removeDeadConstantUsers();
3008 // Make all users of the alias use the aliasee instead.
3010 if (!hasUsesToReplace(*J, Used, RenameTarget))
3013 J->replaceAllUsesWith(Aliasee);
3014 ++NumAliasesResolved;
3018 // Give the aliasee the name, linkage and other attributes of the alias.
3019 Target->takeName(J);
3020 Target->setLinkage(J->getLinkage());
3021 Target->GlobalValue::copyAttributesFrom(J);
3023 if (Used.usedErase(J))
3024 Used.usedInsert(Target);
3026 if (Used.compilerUsedErase(J))
3027 Used.compilerUsedInsert(Target);
3028 } else if (mayHaveOtherReferences(*J, Used))
3031 // Delete the alias.
3032 M.getAliasList().erase(J);
3033 ++NumAliasesRemoved;
3037 Used.syncVariablesAndSets();
3042 static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
3043 if (!TLI->has(LibFunc::cxa_atexit))
3046 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
3051 FunctionType *FTy = Fn->getFunctionType();
3053 // Checking that the function has the right return type, the right number of
3054 // parameters and that they all have pointer types should be enough.
3055 if (!FTy->getReturnType()->isIntegerTy() ||
3056 FTy->getNumParams() != 3 ||
3057 !FTy->getParamType(0)->isPointerTy() ||
3058 !FTy->getParamType(1)->isPointerTy() ||
3059 !FTy->getParamType(2)->isPointerTy())
3065 /// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3066 /// destructor and can therefore be eliminated.
3067 /// Note that we assume that other optimization passes have already simplified
3068 /// the code so we only look for a function with a single basic block, where
3069 /// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3070 /// other side-effect free instructions.
3071 static bool cxxDtorIsEmpty(const Function &Fn,
3072 SmallPtrSet<const Function *, 8> &CalledFunctions) {
3073 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
3074 // nounwind, but that doesn't seem worth doing.
3075 if (Fn.isDeclaration())
3078 if (++Fn.begin() != Fn.end())
3081 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3082 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3084 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
3085 // Ignore debug intrinsics.
3086 if (isa<DbgInfoIntrinsic>(CI))
3089 const Function *CalledFn = CI->getCalledFunction();
3094 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3096 // Don't treat recursive functions as empty.
3097 if (!NewCalledFunctions.insert(CalledFn))
3100 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
3102 } else if (isa<ReturnInst>(*I))
3103 return true; // We're done.
3104 else if (I->mayHaveSideEffects())
3105 return false; // Destructor with side effects, bail.
3111 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3112 /// Itanium C++ ABI p3.3.5:
3114 /// After constructing a global (or local static) object, that will require
3115 /// destruction on exit, a termination function is registered as follows:
3117 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3119 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3120 /// call f(p) when DSO d is unloaded, before all such termination calls
3121 /// registered before this one. It returns zero if registration is
3122 /// successful, nonzero on failure.
3124 // This pass will look for calls to __cxa_atexit where the function is trivial
3126 bool Changed = false;
3128 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3129 E = CXAAtExitFn->use_end(); I != E;) {
3130 // We're only interested in calls. Theoretically, we could handle invoke
3131 // instructions as well, but neither llvm-gcc nor clang generate invokes
3133 CallInst *CI = dyn_cast<CallInst>(*I++);
3138 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
3142 SmallPtrSet<const Function *, 8> CalledFunctions;
3143 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
3146 // Just remove the call.
3147 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3148 CI->eraseFromParent();
3150 ++NumCXXDtorsRemoved;
3158 bool GlobalOpt::runOnModule(Module &M) {
3159 bool Changed = false;
3161 TD = getAnalysisIfAvailable<DataLayout>();
3162 TLI = &getAnalysis<TargetLibraryInfo>();
3164 // Try to find the llvm.globalctors list.
3165 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
3167 bool LocalChange = true;
3168 while (LocalChange) {
3169 LocalChange = false;
3171 // Delete functions that are trivially dead, ccc -> fastcc
3172 LocalChange |= OptimizeFunctions(M);
3174 // Optimize global_ctors list.
3176 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
3178 // Optimize non-address-taken globals.
3179 LocalChange |= OptimizeGlobalVars(M);
3181 // Resolve aliases, when possible.
3182 LocalChange |= OptimizeGlobalAliases(M);
3184 // Try to remove trivial global destructors if they are not removed
3186 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
3188 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3190 Changed |= LocalChange;
3193 // TODO: Move all global ctors functions to the end of the module for code