1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms simple global variables that never have their address
11 // taken. If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLibraryInfo.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/STLExtras.h"
44 STATISTIC(NumMarked , "Number of globals marked constant");
45 STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
46 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49 STATISTIC(NumDeleted , "Number of globals deleted");
50 STATISTIC(NumFnDeleted , "Number of functions deleted");
51 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52 STATISTIC(NumLocalized , "Number of globals localized");
53 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
56 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
57 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
59 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
63 struct GlobalOpt : public ModulePass {
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<TargetLibraryInfo>();
67 static char ID; // Pass identification, replacement for typeid
68 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
72 bool runOnModule(Module &M);
75 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
78 bool OptimizeGlobalAliases(Module &M);
79 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
80 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
84 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
87 TargetLibraryInfo *TLI;
91 char GlobalOpt::ID = 0;
92 INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95 INITIALIZE_PASS_END(GlobalOpt, "globalopt",
96 "Global Variable Optimizer", false, false)
98 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
102 /// GlobalStatus - As we analyze each global, keep track of some information
103 /// about it. If we find out that the address of the global is taken, none of
104 /// this info will be accurate.
105 struct GlobalStatus {
106 /// isCompared - True if the global's address is used in a comparison.
109 /// isLoaded - True if the global is ever loaded. If the global isn't ever
110 /// loaded it can be deleted.
113 /// StoredType - Keep track of what stores to the global look like.
116 /// NotStored - There is no store to this global. It can thus be marked
120 /// isInitializerStored - This global is stored to, but the only thing
121 /// stored is the constant it was initialized with. This is only tracked
122 /// for scalar globals.
125 /// isStoredOnce - This global is stored to, but only its initializer and
126 /// one other value is ever stored to it. If this global isStoredOnce, we
127 /// track the value stored to it in StoredOnceValue below. This is only
128 /// tracked for scalar globals.
131 /// isStored - This global is stored to by multiple values or something else
132 /// that we cannot track.
136 /// StoredOnceValue - If only one value (besides the initializer constant) is
137 /// ever stored to this global, keep track of what value it is.
138 Value *StoredOnceValue;
140 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
141 /// null/false. When the first accessing function is noticed, it is recorded.
142 /// When a second different accessing function is noticed,
143 /// HasMultipleAccessingFunctions is set to true.
144 const Function *AccessingFunction;
145 bool HasMultipleAccessingFunctions;
147 /// HasNonInstructionUser - Set to true if this global has a user that is not
148 /// an instruction (e.g. a constant expr or GV initializer).
149 bool HasNonInstructionUser;
151 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
154 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
155 AtomicOrdering Ordering;
157 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
158 StoredOnceValue(0), AccessingFunction(0),
159 HasMultipleAccessingFunctions(false),
160 HasNonInstructionUser(false), HasPHIUser(false),
161 Ordering(NotAtomic) {}
166 /// StrongerOrdering - Return the stronger of the two ordering. If the two
167 /// orderings are acquire and release, then return AcquireRelease.
169 static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
170 if (X == Acquire && Y == Release) return AcquireRelease;
171 if (Y == Acquire && X == Release) return AcquireRelease;
172 return (AtomicOrdering)std::max(X, Y);
175 /// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
176 /// by constants itself. Note that constants cannot be cyclic, so this test is
177 /// pretty easy to implement recursively.
179 static bool SafeToDestroyConstant(const Constant *C) {
180 if (isa<GlobalValue>(C)) return false;
182 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
184 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
185 if (!SafeToDestroyConstant(CU)) return false;
192 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
193 /// structure. If the global has its address taken, return true to indicate we
194 /// can't do anything with it.
196 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
197 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
198 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
201 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
202 GS.HasNonInstructionUser = true;
204 // If the result of the constantexpr isn't pointer type, then we won't
205 // know to expect it in various places. Just reject early.
206 if (!isa<PointerType>(CE->getType())) return true;
208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
210 if (!GS.HasMultipleAccessingFunctions) {
211 const Function *F = I->getParent()->getParent();
212 if (GS.AccessingFunction == 0)
213 GS.AccessingFunction = F;
214 else if (GS.AccessingFunction != F)
215 GS.HasMultipleAccessingFunctions = true;
217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
219 // Don't hack on volatile loads.
220 if (LI->isVolatile()) return true;
221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
223 // Don't allow a store OF the address, only stores TO the address.
224 if (SI->getOperand(0) == V) return true;
226 // Don't hack on volatile stores.
227 if (SI->isVolatile()) return true;
228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
230 // If this is a direct store to the global (i.e., the global is a scalar
231 // value, not an aggregate), keep more specific information about
233 if (GS.StoredType != GlobalStatus::isStored) {
234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
235 SI->getOperand(1))) {
236 Value *StoredVal = SI->getOperand(0);
237 if (StoredVal == GV->getInitializer()) {
238 if (GS.StoredType < GlobalStatus::isInitializerStored)
239 GS.StoredType = GlobalStatus::isInitializerStored;
240 } else if (isa<LoadInst>(StoredVal) &&
241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
242 if (GS.StoredType < GlobalStatus::isInitializerStored)
243 GS.StoredType = GlobalStatus::isInitializerStored;
244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
245 GS.StoredType = GlobalStatus::isStoredOnce;
246 GS.StoredOnceValue = StoredVal;
247 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
248 GS.StoredOnceValue == StoredVal) {
251 GS.StoredType = GlobalStatus::isStored;
254 GS.StoredType = GlobalStatus::isStored;
257 } else if (isa<BitCastInst>(I)) {
258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
259 } else if (isa<GetElementPtrInst>(I)) {
260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
261 } else if (isa<SelectInst>(I)) {
262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
263 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
264 // PHI nodes we can check just like select or GEP instructions, but we
265 // have to be careful about infinite recursion.
266 if (PHIUsers.insert(PN)) // Not already visited.
267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
268 GS.HasPHIUser = true;
269 } else if (isa<CmpInst>(I)) {
270 GS.isCompared = true;
271 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
272 if (MTI->isVolatile()) return true;
273 if (MTI->getArgOperand(0) == V)
274 GS.StoredType = GlobalStatus::isStored;
275 if (MTI->getArgOperand(1) == V)
277 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
278 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
279 if (MSI->isVolatile()) return true;
280 GS.StoredType = GlobalStatus::isStored;
282 return true; // Any other non-load instruction might take address!
284 } else if (const Constant *C = dyn_cast<Constant>(U)) {
285 GS.HasNonInstructionUser = true;
286 // We might have a dead and dangling constant hanging off of here.
287 if (!SafeToDestroyConstant(C))
290 GS.HasNonInstructionUser = true;
291 // Otherwise must be some other user.
299 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
300 /// users of the global, cleaning up the obvious ones. This is largely just a
301 /// quick scan over the use list to clean up the easy and obvious cruft. This
302 /// returns true if it made a change.
303 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
304 TargetData *TD, TargetLibraryInfo *TLI) {
305 bool Changed = false;
306 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
309 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
311 // Replace the load with the initializer.
312 LI->replaceAllUsesWith(Init);
313 LI->eraseFromParent();
316 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
317 // Store must be unreachable or storing Init into the global.
318 SI->eraseFromParent();
320 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
321 if (CE->getOpcode() == Instruction::GetElementPtr) {
322 Constant *SubInit = 0;
324 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
325 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
326 } else if (CE->getOpcode() == Instruction::BitCast &&
327 CE->getType()->isPointerTy()) {
328 // Pointer cast, delete any stores and memsets to the global.
329 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
332 if (CE->use_empty()) {
333 CE->destroyConstant();
336 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
337 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
338 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
339 // and will invalidate our notion of what Init is.
340 Constant *SubInit = 0;
341 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
343 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
344 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
345 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
347 // If the initializer is an all-null value and we have an inbounds GEP,
348 // we already know what the result of any load from that GEP is.
349 // TODO: Handle splats.
350 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
351 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
353 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
355 if (GEP->use_empty()) {
356 GEP->eraseFromParent();
359 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
360 if (MI->getRawDest() == V) {
361 MI->eraseFromParent();
365 } else if (Constant *C = dyn_cast<Constant>(U)) {
366 // If we have a chain of dead constantexprs or other things dangling from
367 // us, and if they are all dead, nuke them without remorse.
368 if (SafeToDestroyConstant(C)) {
369 C->destroyConstant();
370 // This could have invalidated UI, start over from scratch.
371 CleanupConstantGlobalUsers(V, Init, TD, TLI);
379 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
380 /// user of a derived expression from a global that we want to SROA.
381 static bool isSafeSROAElementUse(Value *V) {
382 // We might have a dead and dangling constant hanging off of here.
383 if (Constant *C = dyn_cast<Constant>(V))
384 return SafeToDestroyConstant(C);
386 Instruction *I = dyn_cast<Instruction>(V);
387 if (!I) return false;
390 if (isa<LoadInst>(I)) return true;
392 // Stores *to* the pointer are ok.
393 if (StoreInst *SI = dyn_cast<StoreInst>(I))
394 return SI->getOperand(0) != V;
396 // Otherwise, it must be a GEP.
397 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
398 if (GEPI == 0) return false;
400 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
401 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
404 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
406 if (!isSafeSROAElementUse(*I))
412 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
413 /// Look at it and its uses and decide whether it is safe to SROA this global.
415 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
416 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
417 if (!isa<GetElementPtrInst>(U) &&
418 (!isa<ConstantExpr>(U) ||
419 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
422 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
423 // don't like < 3 operand CE's, and we don't like non-constant integer
424 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
426 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
427 !cast<Constant>(U->getOperand(1))->isNullValue() ||
428 !isa<ConstantInt>(U->getOperand(2)))
431 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
432 ++GEPI; // Skip over the pointer index.
434 // If this is a use of an array allocation, do a bit more checking for sanity.
435 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
436 uint64_t NumElements = AT->getNumElements();
437 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
439 // Check to make sure that index falls within the array. If not,
440 // something funny is going on, so we won't do the optimization.
442 if (Idx->getZExtValue() >= NumElements)
445 // We cannot scalar repl this level of the array unless any array
446 // sub-indices are in-range constants. In particular, consider:
447 // A[0][i]. We cannot know that the user isn't doing invalid things like
448 // allowing i to index an out-of-range subscript that accesses A[1].
450 // Scalar replacing *just* the outer index of the array is probably not
451 // going to be a win anyway, so just give up.
452 for (++GEPI; // Skip array index.
455 uint64_t NumElements;
456 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
457 NumElements = SubArrayTy->getNumElements();
458 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
459 NumElements = SubVectorTy->getNumElements();
461 assert((*GEPI)->isStructTy() &&
462 "Indexed GEP type is not array, vector, or struct!");
466 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
467 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
472 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
473 if (!isSafeSROAElementUse(*I))
478 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
479 /// is safe for us to perform this transformation.
481 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
482 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
484 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
491 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
492 /// variable. This opens the door for other optimizations by exposing the
493 /// behavior of the program in a more fine-grained way. We have determined that
494 /// this transformation is safe already. We return the first global variable we
495 /// insert so that the caller can reprocess it.
496 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
497 // Make sure this global only has simple uses that we can SRA.
498 if (!GlobalUsersSafeToSRA(GV))
501 assert(GV->hasLocalLinkage() && !GV->isConstant());
502 Constant *Init = GV->getInitializer();
503 Type *Ty = Init->getType();
505 std::vector<GlobalVariable*> NewGlobals;
506 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
508 // Get the alignment of the global, either explicit or target-specific.
509 unsigned StartAlignment = GV->getAlignment();
510 if (StartAlignment == 0)
511 StartAlignment = TD.getABITypeAlignment(GV->getType());
513 if (StructType *STy = dyn_cast<StructType>(Ty)) {
514 NewGlobals.reserve(STy->getNumElements());
515 const StructLayout &Layout = *TD.getStructLayout(STy);
516 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
517 Constant *In = Init->getAggregateElement(i);
518 assert(In && "Couldn't get element of initializer?");
519 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
520 GlobalVariable::InternalLinkage,
521 In, GV->getName()+"."+Twine(i),
522 GV->getThreadLocalMode(),
523 GV->getType()->getAddressSpace());
524 Globals.insert(GV, NGV);
525 NewGlobals.push_back(NGV);
527 // Calculate the known alignment of the field. If the original aggregate
528 // had 256 byte alignment for example, something might depend on that:
529 // propagate info to each field.
530 uint64_t FieldOffset = Layout.getElementOffset(i);
531 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
532 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
533 NGV->setAlignment(NewAlign);
535 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
536 unsigned NumElements = 0;
537 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
538 NumElements = ATy->getNumElements();
540 NumElements = cast<VectorType>(STy)->getNumElements();
542 if (NumElements > 16 && GV->hasNUsesOrMore(16))
543 return 0; // It's not worth it.
544 NewGlobals.reserve(NumElements);
546 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
547 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
548 for (unsigned i = 0, e = NumElements; i != e; ++i) {
549 Constant *In = Init->getAggregateElement(i);
550 assert(In && "Couldn't get element of initializer?");
552 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
553 GlobalVariable::InternalLinkage,
554 In, GV->getName()+"."+Twine(i),
555 GV->getThreadLocalMode(),
556 GV->getType()->getAddressSpace());
557 Globals.insert(GV, NGV);
558 NewGlobals.push_back(NGV);
560 // Calculate the known alignment of the field. If the original aggregate
561 // had 256 byte alignment for example, something might depend on that:
562 // propagate info to each field.
563 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
564 if (NewAlign > EltAlign)
565 NGV->setAlignment(NewAlign);
569 if (NewGlobals.empty())
572 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
574 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
576 // Loop over all of the uses of the global, replacing the constantexpr geps,
577 // with smaller constantexpr geps or direct references.
578 while (!GV->use_empty()) {
579 User *GEP = GV->use_back();
580 assert(((isa<ConstantExpr>(GEP) &&
581 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
582 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
584 // Ignore the 1th operand, which has to be zero or else the program is quite
585 // broken (undefined). Get the 2nd operand, which is the structure or array
587 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
588 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
590 Value *NewPtr = NewGlobals[Val];
592 // Form a shorter GEP if needed.
593 if (GEP->getNumOperands() > 3) {
594 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
595 SmallVector<Constant*, 8> Idxs;
596 Idxs.push_back(NullInt);
597 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
598 Idxs.push_back(CE->getOperand(i));
599 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
601 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
602 SmallVector<Value*, 8> Idxs;
603 Idxs.push_back(NullInt);
604 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
605 Idxs.push_back(GEPI->getOperand(i));
606 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
607 GEPI->getName()+"."+Twine(Val),GEPI);
610 GEP->replaceAllUsesWith(NewPtr);
612 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
613 GEPI->eraseFromParent();
615 cast<ConstantExpr>(GEP)->destroyConstant();
618 // Delete the old global, now that it is dead.
622 // Loop over the new globals array deleting any globals that are obviously
623 // dead. This can arise due to scalarization of a structure or an array that
624 // has elements that are dead.
625 unsigned FirstGlobal = 0;
626 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
627 if (NewGlobals[i]->use_empty()) {
628 Globals.erase(NewGlobals[i]);
629 if (FirstGlobal == i) ++FirstGlobal;
632 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
635 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
636 /// value will trap if the value is dynamically null. PHIs keeps track of any
637 /// phi nodes we've seen to avoid reprocessing them.
638 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
639 SmallPtrSet<const PHINode*, 8> &PHIs) {
640 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
644 if (isa<LoadInst>(U)) {
646 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
647 if (SI->getOperand(0) == V) {
648 //cerr << "NONTRAPPING USE: " << *U;
649 return false; // Storing the value.
651 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
652 if (CI->getCalledValue() != V) {
653 //cerr << "NONTRAPPING USE: " << *U;
654 return false; // Not calling the ptr
656 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
657 if (II->getCalledValue() != V) {
658 //cerr << "NONTRAPPING USE: " << *U;
659 return false; // Not calling the ptr
661 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
662 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
663 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
664 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
665 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
666 // If we've already seen this phi node, ignore it, it has already been
668 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
670 } else if (isa<ICmpInst>(U) &&
671 isa<ConstantPointerNull>(UI->getOperand(1))) {
672 // Ignore icmp X, null
674 //cerr << "NONTRAPPING USE: " << *U;
681 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
682 /// from GV will trap if the loaded value is null. Note that this also permits
683 /// comparisons of the loaded value against null, as a special case.
684 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
685 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
689 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
690 SmallPtrSet<const PHINode*, 8> PHIs;
691 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
693 } else if (isa<StoreInst>(U)) {
694 // Ignore stores to the global.
696 // We don't know or understand this user, bail out.
697 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
704 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
705 bool Changed = false;
706 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
707 Instruction *I = cast<Instruction>(*UI++);
708 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
709 LI->setOperand(0, NewV);
711 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
712 if (SI->getOperand(1) == V) {
713 SI->setOperand(1, NewV);
716 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
718 if (CS.getCalledValue() == V) {
719 // Calling through the pointer! Turn into a direct call, but be careful
720 // that the pointer is not also being passed as an argument.
721 CS.setCalledFunction(NewV);
723 bool PassedAsArg = false;
724 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
725 if (CS.getArgument(i) == V) {
727 CS.setArgument(i, NewV);
731 // Being passed as an argument also. Be careful to not invalidate UI!
735 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
736 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
737 ConstantExpr::getCast(CI->getOpcode(),
738 NewV, CI->getType()));
739 if (CI->use_empty()) {
741 CI->eraseFromParent();
743 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
744 // Should handle GEP here.
745 SmallVector<Constant*, 8> Idxs;
746 Idxs.reserve(GEPI->getNumOperands()-1);
747 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
749 if (Constant *C = dyn_cast<Constant>(*i))
753 if (Idxs.size() == GEPI->getNumOperands()-1)
754 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
755 ConstantExpr::getGetElementPtr(NewV, Idxs));
756 if (GEPI->use_empty()) {
758 GEPI->eraseFromParent();
767 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
768 /// value stored into it. If there are uses of the loaded value that would trap
769 /// if the loaded value is dynamically null, then we know that they cannot be
770 /// reachable with a null optimize away the load.
771 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
773 TargetLibraryInfo *TLI) {
774 bool Changed = false;
776 // Keep track of whether we are able to remove all the uses of the global
777 // other than the store that defines it.
778 bool AllNonStoreUsesGone = true;
780 // Replace all uses of loads with uses of uses of the stored value.
781 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
782 User *GlobalUser = *GUI++;
783 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
784 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
785 // If we were able to delete all uses of the loads
786 if (LI->use_empty()) {
787 LI->eraseFromParent();
790 AllNonStoreUsesGone = false;
792 } else if (isa<StoreInst>(GlobalUser)) {
793 // Ignore the store that stores "LV" to the global.
794 assert(GlobalUser->getOperand(1) == GV &&
795 "Must be storing *to* the global");
797 AllNonStoreUsesGone = false;
799 // If we get here we could have other crazy uses that are transitively
801 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
802 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
803 "Only expect load and stores!");
808 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
812 // If we nuked all of the loads, then none of the stores are needed either,
813 // nor is the global.
814 if (AllNonStoreUsesGone) {
815 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
816 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
817 if (GV->use_empty()) {
818 GV->eraseFromParent();
826 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
827 /// instructions that are foldable.
828 static void ConstantPropUsersOf(Value *V,
829 TargetData *TD, TargetLibraryInfo *TLI) {
830 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
831 if (Instruction *I = dyn_cast<Instruction>(*UI++))
832 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
833 I->replaceAllUsesWith(NewC);
835 // Advance UI to the next non-I use to avoid invalidating it!
836 // Instructions could multiply use V.
837 while (UI != E && *UI == I)
839 I->eraseFromParent();
843 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
844 /// variable, and transforms the program as if it always contained the result of
845 /// the specified malloc. Because it is always the result of the specified
846 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
847 /// malloc into a global, and any loads of GV as uses of the new global.
848 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
851 ConstantInt *NElements,
853 TargetLibraryInfo *TLI) {
854 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
857 if (NElements->getZExtValue() == 1)
858 GlobalType = AllocTy;
860 // If we have an array allocation, the global variable is of an array.
861 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
863 // Create the new global variable. The contents of the malloc'd memory is
864 // undefined, so initialize with an undef value.
865 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
867 GlobalValue::InternalLinkage,
868 UndefValue::get(GlobalType),
869 GV->getName()+".body",
871 GV->getThreadLocalMode());
873 // If there are bitcast users of the malloc (which is typical, usually we have
874 // a malloc + bitcast) then replace them with uses of the new global. Update
875 // other users to use the global as well.
876 BitCastInst *TheBC = 0;
877 while (!CI->use_empty()) {
878 Instruction *User = cast<Instruction>(CI->use_back());
879 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
880 if (BCI->getType() == NewGV->getType()) {
881 BCI->replaceAllUsesWith(NewGV);
882 BCI->eraseFromParent();
884 BCI->setOperand(0, NewGV);
888 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
889 User->replaceUsesOfWith(CI, TheBC);
893 Constant *RepValue = NewGV;
894 if (NewGV->getType() != GV->getType()->getElementType())
895 RepValue = ConstantExpr::getBitCast(RepValue,
896 GV->getType()->getElementType());
898 // If there is a comparison against null, we will insert a global bool to
899 // keep track of whether the global was initialized yet or not.
900 GlobalVariable *InitBool =
901 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
902 GlobalValue::InternalLinkage,
903 ConstantInt::getFalse(GV->getContext()),
904 GV->getName()+".init", GV->getThreadLocalMode());
905 bool InitBoolUsed = false;
907 // Loop over all uses of GV, processing them in turn.
908 while (!GV->use_empty()) {
909 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
910 // The global is initialized when the store to it occurs.
911 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
912 SI->getOrdering(), SI->getSynchScope(), SI);
913 SI->eraseFromParent();
917 LoadInst *LI = cast<LoadInst>(GV->use_back());
918 while (!LI->use_empty()) {
919 Use &LoadUse = LI->use_begin().getUse();
920 if (!isa<ICmpInst>(LoadUse.getUser())) {
925 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
926 // Replace the cmp X, 0 with a use of the bool value.
927 // Sink the load to where the compare was, if atomic rules allow us to.
928 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
929 LI->getOrdering(), LI->getSynchScope(),
930 LI->isUnordered() ? (Instruction*)ICI : LI);
932 switch (ICI->getPredicate()) {
933 default: llvm_unreachable("Unknown ICmp Predicate!");
934 case ICmpInst::ICMP_ULT:
935 case ICmpInst::ICMP_SLT: // X < null -> always false
936 LV = ConstantInt::getFalse(GV->getContext());
938 case ICmpInst::ICMP_ULE:
939 case ICmpInst::ICMP_SLE:
940 case ICmpInst::ICMP_EQ:
941 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
943 case ICmpInst::ICMP_NE:
944 case ICmpInst::ICMP_UGE:
945 case ICmpInst::ICMP_SGE:
946 case ICmpInst::ICMP_UGT:
947 case ICmpInst::ICMP_SGT:
950 ICI->replaceAllUsesWith(LV);
951 ICI->eraseFromParent();
953 LI->eraseFromParent();
956 // If the initialization boolean was used, insert it, otherwise delete it.
958 while (!InitBool->use_empty()) // Delete initializations
959 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
962 GV->getParent()->getGlobalList().insert(GV, InitBool);
964 // Now the GV is dead, nuke it and the malloc..
965 GV->eraseFromParent();
966 CI->eraseFromParent();
968 // To further other optimizations, loop over all users of NewGV and try to
969 // constant prop them. This will promote GEP instructions with constant
970 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
971 ConstantPropUsersOf(NewGV, TD, TLI);
972 if (RepValue != NewGV)
973 ConstantPropUsersOf(RepValue, TD, TLI);
978 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
979 /// to make sure that there are no complex uses of V. We permit simple things
980 /// like dereferencing the pointer, but not storing through the address, unless
981 /// it is to the specified global.
982 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
983 const GlobalVariable *GV,
984 SmallPtrSet<const PHINode*, 8> &PHIs) {
985 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
987 const Instruction *Inst = cast<Instruction>(*UI);
989 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
990 continue; // Fine, ignore.
993 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
994 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
995 return false; // Storing the pointer itself... bad.
996 continue; // Otherwise, storing through it, or storing into GV... fine.
999 // Must index into the array and into the struct.
1000 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
1001 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
1006 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
1007 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1009 if (PHIs.insert(PN))
1010 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1015 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1016 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1026 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1027 /// somewhere. Transform all uses of the allocation into loads from the
1028 /// global and uses of the resultant pointer. Further, delete the store into
1029 /// GV. This assumes that these value pass the
1030 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1031 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1032 GlobalVariable *GV) {
1033 while (!Alloc->use_empty()) {
1034 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1035 Instruction *InsertPt = U;
1036 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1037 // If this is the store of the allocation into the global, remove it.
1038 if (SI->getOperand(1) == GV) {
1039 SI->eraseFromParent();
1042 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1043 // Insert the load in the corresponding predecessor, not right before the
1045 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1046 } else if (isa<BitCastInst>(U)) {
1047 // Must be bitcast between the malloc and store to initialize the global.
1048 ReplaceUsesOfMallocWithGlobal(U, GV);
1049 U->eraseFromParent();
1051 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1052 // If this is a "GEP bitcast" and the user is a store to the global, then
1053 // just process it as a bitcast.
1054 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1055 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1056 if (SI->getOperand(1) == GV) {
1057 // Must be bitcast GEP between the malloc and store to initialize
1059 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1060 GEPI->eraseFromParent();
1065 // Insert a load from the global, and use it instead of the malloc.
1066 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1067 U->replaceUsesOfWith(Alloc, NL);
1071 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1072 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1073 /// that index through the array and struct field, icmps of null, and PHIs.
1074 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1075 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1076 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1077 // We permit two users of the load: setcc comparing against the null
1078 // pointer, and a getelementptr of a specific form.
1079 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1081 const Instruction *User = cast<Instruction>(*UI);
1083 // Comparison against null is ok.
1084 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1085 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1090 // getelementptr is also ok, but only a simple form.
1091 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1092 // Must index into the array and into the struct.
1093 if (GEPI->getNumOperands() < 3)
1096 // Otherwise the GEP is ok.
1100 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1101 if (!LoadUsingPHIsPerLoad.insert(PN))
1102 // This means some phi nodes are dependent on each other.
1103 // Avoid infinite looping!
1105 if (!LoadUsingPHIs.insert(PN))
1106 // If we have already analyzed this PHI, then it is safe.
1109 // Make sure all uses of the PHI are simple enough to transform.
1110 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1111 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1117 // Otherwise we don't know what this is, not ok.
1125 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1126 /// GV are simple enough to perform HeapSRA, return true.
1127 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1128 Instruction *StoredVal) {
1129 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1130 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1131 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1133 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1134 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1135 LoadUsingPHIsPerLoad))
1137 LoadUsingPHIsPerLoad.clear();
1140 // If we reach here, we know that all uses of the loads and transitive uses
1141 // (through PHI nodes) are simple enough to transform. However, we don't know
1142 // that all inputs the to the PHI nodes are in the same equivalence sets.
1143 // Check to verify that all operands of the PHIs are either PHIS that can be
1144 // transformed, loads from GV, or MI itself.
1145 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1146 , E = LoadUsingPHIs.end(); I != E; ++I) {
1147 const PHINode *PN = *I;
1148 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1149 Value *InVal = PN->getIncomingValue(op);
1151 // PHI of the stored value itself is ok.
1152 if (InVal == StoredVal) continue;
1154 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1155 // One of the PHIs in our set is (optimistically) ok.
1156 if (LoadUsingPHIs.count(InPN))
1161 // Load from GV is ok.
1162 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1163 if (LI->getOperand(0) == GV)
1168 // Anything else is rejected.
1176 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1177 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1178 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1179 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1181 if (FieldNo >= FieldVals.size())
1182 FieldVals.resize(FieldNo+1);
1184 // If we already have this value, just reuse the previously scalarized
1186 if (Value *FieldVal = FieldVals[FieldNo])
1189 // Depending on what instruction this is, we have several cases.
1191 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1192 // This is a scalarized version of the load from the global. Just create
1193 // a new Load of the scalarized global.
1194 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1195 InsertedScalarizedValues,
1197 LI->getName()+".f"+Twine(FieldNo), LI);
1198 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1199 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1202 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1205 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1206 PN->getNumIncomingValues(),
1207 PN->getName()+".f"+Twine(FieldNo), PN);
1209 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1211 llvm_unreachable("Unknown usable value");
1214 return FieldVals[FieldNo] = Result;
1217 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1218 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1219 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1220 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1221 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1222 // If this is a comparison against null, handle it.
1223 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1224 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1225 // If we have a setcc of the loaded pointer, we can use a setcc of any
1227 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1228 InsertedScalarizedValues, PHIsToRewrite);
1230 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1231 Constant::getNullValue(NPtr->getType()),
1233 SCI->replaceAllUsesWith(New);
1234 SCI->eraseFromParent();
1238 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1239 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1240 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1241 && "Unexpected GEPI!");
1243 // Load the pointer for this field.
1244 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1245 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1246 InsertedScalarizedValues, PHIsToRewrite);
1248 // Create the new GEP idx vector.
1249 SmallVector<Value*, 8> GEPIdx;
1250 GEPIdx.push_back(GEPI->getOperand(1));
1251 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1253 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
1254 GEPI->getName(), GEPI);
1255 GEPI->replaceAllUsesWith(NGEPI);
1256 GEPI->eraseFromParent();
1260 // Recursively transform the users of PHI nodes. This will lazily create the
1261 // PHIs that are needed for individual elements. Keep track of what PHIs we
1262 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1263 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1264 // already been seen first by another load, so its uses have already been
1266 PHINode *PN = cast<PHINode>(LoadUser);
1267 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1268 std::vector<Value*>())).second)
1271 // If this is the first time we've seen this PHI, recursively process all
1273 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1274 Instruction *User = cast<Instruction>(*UI++);
1275 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1279 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1280 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1281 /// use FieldGlobals instead. All uses of loaded values satisfy
1282 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1283 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1284 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1285 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1286 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1288 Instruction *User = cast<Instruction>(*UI++);
1289 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1292 if (Load->use_empty()) {
1293 Load->eraseFromParent();
1294 InsertedScalarizedValues.erase(Load);
1298 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1299 /// it up into multiple allocations of arrays of the fields.
1300 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1301 Value *NElems, TargetData *TD) {
1302 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1303 Type *MAT = getMallocAllocatedType(CI);
1304 StructType *STy = cast<StructType>(MAT);
1306 // There is guaranteed to be at least one use of the malloc (storing
1307 // it into GV). If there are other uses, change them to be uses of
1308 // the global to simplify later code. This also deletes the store
1310 ReplaceUsesOfMallocWithGlobal(CI, GV);
1312 // Okay, at this point, there are no users of the malloc. Insert N
1313 // new mallocs at the same place as CI, and N globals.
1314 std::vector<Value*> FieldGlobals;
1315 std::vector<Value*> FieldMallocs;
1317 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1318 Type *FieldTy = STy->getElementType(FieldNo);
1319 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1321 GlobalVariable *NGV =
1322 new GlobalVariable(*GV->getParent(),
1323 PFieldTy, false, GlobalValue::InternalLinkage,
1324 Constant::getNullValue(PFieldTy),
1325 GV->getName() + ".f" + Twine(FieldNo), GV,
1326 GV->getThreadLocalMode());
1327 FieldGlobals.push_back(NGV);
1329 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1330 if (StructType *ST = dyn_cast<StructType>(FieldTy))
1331 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1332 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1333 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1334 ConstantInt::get(IntPtrTy, TypeSize),
1336 CI->getName() + ".f" + Twine(FieldNo));
1337 FieldMallocs.push_back(NMI);
1338 new StoreInst(NMI, NGV, CI);
1341 // The tricky aspect of this transformation is handling the case when malloc
1342 // fails. In the original code, malloc failing would set the result pointer
1343 // of malloc to null. In this case, some mallocs could succeed and others
1344 // could fail. As such, we emit code that looks like this:
1345 // F0 = malloc(field0)
1346 // F1 = malloc(field1)
1347 // F2 = malloc(field2)
1348 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1349 // if (F0) { free(F0); F0 = 0; }
1350 // if (F1) { free(F1); F1 = 0; }
1351 // if (F2) { free(F2); F2 = 0; }
1353 // The malloc can also fail if its argument is too large.
1354 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1355 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1356 ConstantZero, "isneg");
1357 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1358 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1359 Constant::getNullValue(FieldMallocs[i]->getType()),
1361 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1364 // Split the basic block at the old malloc.
1365 BasicBlock *OrigBB = CI->getParent();
1366 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1368 // Create the block to check the first condition. Put all these blocks at the
1369 // end of the function as they are unlikely to be executed.
1370 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1372 OrigBB->getParent());
1374 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1375 // branch on RunningOr.
1376 OrigBB->getTerminator()->eraseFromParent();
1377 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1379 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1380 // pointer, because some may be null while others are not.
1381 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1382 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1383 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1384 Constant::getNullValue(GVVal->getType()));
1385 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1386 OrigBB->getParent());
1387 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1388 OrigBB->getParent());
1389 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1392 // Fill in FreeBlock.
1393 CallInst::CreateFree(GVVal, BI);
1394 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1396 BranchInst::Create(NextBlock, FreeBlock);
1398 NullPtrBlock = NextBlock;
1401 BranchInst::Create(ContBB, NullPtrBlock);
1403 // CI is no longer needed, remove it.
1404 CI->eraseFromParent();
1406 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1407 /// update all uses of the load, keep track of what scalarized loads are
1408 /// inserted for a given load.
1409 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1410 InsertedScalarizedValues[GV] = FieldGlobals;
1412 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1414 // Okay, the malloc site is completely handled. All of the uses of GV are now
1415 // loads, and all uses of those loads are simple. Rewrite them to use loads
1416 // of the per-field globals instead.
1417 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1418 Instruction *User = cast<Instruction>(*UI++);
1420 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1421 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1425 // Must be a store of null.
1426 StoreInst *SI = cast<StoreInst>(User);
1427 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1428 "Unexpected heap-sra user!");
1430 // Insert a store of null into each global.
1431 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1432 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1433 Constant *Null = Constant::getNullValue(PT->getElementType());
1434 new StoreInst(Null, FieldGlobals[i], SI);
1436 // Erase the original store.
1437 SI->eraseFromParent();
1440 // While we have PHIs that are interesting to rewrite, do it.
1441 while (!PHIsToRewrite.empty()) {
1442 PHINode *PN = PHIsToRewrite.back().first;
1443 unsigned FieldNo = PHIsToRewrite.back().second;
1444 PHIsToRewrite.pop_back();
1445 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1446 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1448 // Add all the incoming values. This can materialize more phis.
1449 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1450 Value *InVal = PN->getIncomingValue(i);
1451 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1453 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1457 // Drop all inter-phi links and any loads that made it this far.
1458 for (DenseMap<Value*, std::vector<Value*> >::iterator
1459 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1461 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1462 PN->dropAllReferences();
1463 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1464 LI->dropAllReferences();
1467 // Delete all the phis and loads now that inter-references are dead.
1468 for (DenseMap<Value*, std::vector<Value*> >::iterator
1469 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1471 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1472 PN->eraseFromParent();
1473 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1474 LI->eraseFromParent();
1477 // The old global is now dead, remove it.
1478 GV->eraseFromParent();
1481 return cast<GlobalVariable>(FieldGlobals[0]);
1484 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1485 /// pointer global variable with a single value stored it that is a malloc or
1487 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1490 AtomicOrdering Ordering,
1491 Module::global_iterator &GVI,
1493 TargetLibraryInfo *TLI) {
1497 // If this is a malloc of an abstract type, don't touch it.
1498 if (!AllocTy->isSized())
1501 // We can't optimize this global unless all uses of it are *known* to be
1502 // of the malloc value, not of the null initializer value (consider a use
1503 // that compares the global's value against zero to see if the malloc has
1504 // been reached). To do this, we check to see if all uses of the global
1505 // would trap if the global were null: this proves that they must all
1506 // happen after the malloc.
1507 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1510 // We can't optimize this if the malloc itself is used in a complex way,
1511 // for example, being stored into multiple globals. This allows the
1512 // malloc to be stored into the specified global, loaded icmp'd, and
1513 // GEP'd. These are all things we could transform to using the global
1515 SmallPtrSet<const PHINode*, 8> PHIs;
1516 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1519 // If we have a global that is only initialized with a fixed size malloc,
1520 // transform the program to use global memory instead of malloc'd memory.
1521 // This eliminates dynamic allocation, avoids an indirection accessing the
1522 // data, and exposes the resultant global to further GlobalOpt.
1523 // We cannot optimize the malloc if we cannot determine malloc array size.
1524 Value *NElems = getMallocArraySize(CI, TD, true);
1528 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1529 // Restrict this transformation to only working on small allocations
1530 // (2048 bytes currently), as we don't want to introduce a 16M global or
1532 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1533 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
1537 // If the allocation is an array of structures, consider transforming this
1538 // into multiple malloc'd arrays, one for each field. This is basically
1539 // SRoA for malloc'd memory.
1541 if (Ordering != NotAtomic)
1544 // If this is an allocation of a fixed size array of structs, analyze as a
1545 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1546 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1547 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1548 AllocTy = AT->getElementType();
1550 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1554 // This the structure has an unreasonable number of fields, leave it
1556 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1557 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1559 // If this is a fixed size array, transform the Malloc to be an alloc of
1560 // structs. malloc [100 x struct],1 -> malloc struct, 100
1561 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1562 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1563 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1564 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1565 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1566 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1567 AllocSize, NumElements,
1569 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1570 CI->replaceAllUsesWith(Cast);
1571 CI->eraseFromParent();
1572 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1573 CI = cast<CallInst>(BCI->getOperand(0));
1575 CI = cast<CallInst>(Malloc);
1578 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
1585 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1586 // that only one value (besides its initializer) is ever stored to the global.
1587 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1588 AtomicOrdering Ordering,
1589 Module::global_iterator &GVI,
1590 TargetData *TD, TargetLibraryInfo *TLI) {
1591 // Ignore no-op GEPs and bitcasts.
1592 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1594 // If we are dealing with a pointer global that is initialized to null and
1595 // only has one (non-null) value stored into it, then we can optimize any
1596 // users of the loaded value (often calls and loads) that would trap if the
1598 if (GV->getInitializer()->getType()->isPointerTy() &&
1599 GV->getInitializer()->isNullValue()) {
1600 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1601 if (GV->getInitializer()->getType() != SOVC->getType())
1602 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1604 // Optimize away any trapping uses of the loaded value.
1605 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
1607 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1608 Type *MallocType = getMallocAllocatedType(CI);
1610 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1619 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1620 /// two values ever stored into GV are its initializer and OtherVal. See if we
1621 /// can shrink the global into a boolean and select between the two values
1622 /// whenever it is used. This exposes the values to other scalar optimizations.
1623 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1624 Type *GVElType = GV->getType()->getElementType();
1626 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1627 // an FP value, pointer or vector, don't do this optimization because a select
1628 // between them is very expensive and unlikely to lead to later
1629 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1630 // where v1 and v2 both require constant pool loads, a big loss.
1631 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1632 GVElType->isFloatingPointTy() ||
1633 GVElType->isPointerTy() || GVElType->isVectorTy())
1636 // Walk the use list of the global seeing if all the uses are load or store.
1637 // If there is anything else, bail out.
1638 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1640 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1644 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1646 // Create the new global, initializing it to false.
1647 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1649 GlobalValue::InternalLinkage,
1650 ConstantInt::getFalse(GV->getContext()),
1652 GV->getThreadLocalMode());
1653 GV->getParent()->getGlobalList().insert(GV, NewGV);
1655 Constant *InitVal = GV->getInitializer();
1656 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1657 "No reason to shrink to bool!");
1659 // If initialized to zero and storing one into the global, we can use a cast
1660 // instead of a select to synthesize the desired value.
1661 bool IsOneZero = false;
1662 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1663 IsOneZero = InitVal->isNullValue() && CI->isOne();
1665 while (!GV->use_empty()) {
1666 Instruction *UI = cast<Instruction>(GV->use_back());
1667 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1668 // Change the store into a boolean store.
1669 bool StoringOther = SI->getOperand(0) == OtherVal;
1670 // Only do this if we weren't storing a loaded value.
1672 if (StoringOther || SI->getOperand(0) == InitVal)
1673 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1676 // Otherwise, we are storing a previously loaded copy. To do this,
1677 // change the copy from copying the original value to just copying the
1679 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1681 // If we've already replaced the input, StoredVal will be a cast or
1682 // select instruction. If not, it will be a load of the original
1684 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1685 assert(LI->getOperand(0) == GV && "Not a copy!");
1686 // Insert a new load, to preserve the saved value.
1687 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1688 LI->getOrdering(), LI->getSynchScope(), LI);
1690 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1691 "This is not a form that we understand!");
1692 StoreVal = StoredVal->getOperand(0);
1693 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1696 new StoreInst(StoreVal, NewGV, false, 0,
1697 SI->getOrdering(), SI->getSynchScope(), SI);
1699 // Change the load into a load of bool then a select.
1700 LoadInst *LI = cast<LoadInst>(UI);
1701 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1702 LI->getOrdering(), LI->getSynchScope(), LI);
1705 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1707 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1709 LI->replaceAllUsesWith(NSI);
1711 UI->eraseFromParent();
1714 GV->eraseFromParent();
1719 /// ProcessGlobal - Analyze the specified global variable and optimize it if
1720 /// possible. If we make a change, return true.
1721 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1722 Module::global_iterator &GVI) {
1723 if (!GV->isDiscardableIfUnused())
1726 // Do more involved optimizations if the global is internal.
1727 GV->removeDeadConstantUsers();
1729 if (GV->use_empty()) {
1730 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1731 GV->eraseFromParent();
1736 if (!GV->hasLocalLinkage())
1739 SmallPtrSet<const PHINode*, 16> PHIUsers;
1742 if (AnalyzeGlobal(GV, GS, PHIUsers))
1745 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1746 GV->setUnnamedAddr(true);
1750 if (GV->isConstant() || !GV->hasInitializer())
1753 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1756 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1757 /// it if possible. If we make a change, return true.
1758 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1759 Module::global_iterator &GVI,
1760 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1761 const GlobalStatus &GS) {
1762 // If this is a first class global and has only one accessing function
1763 // and this function is main (which we know is not recursive we can make
1764 // this global a local variable) we replace the global with a local alloca
1765 // in this function.
1767 // NOTE: It doesn't make sense to promote non single-value types since we
1768 // are just replacing static memory to stack memory.
1770 // If the global is in different address space, don't bring it to stack.
1771 if (!GS.HasMultipleAccessingFunctions &&
1772 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1773 GV->getType()->getElementType()->isSingleValueType() &&
1774 GS.AccessingFunction->getName() == "main" &&
1775 GS.AccessingFunction->hasExternalLinkage() &&
1776 GV->getType()->getAddressSpace() == 0) {
1777 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1778 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1779 ->getEntryBlock().begin());
1780 Type *ElemTy = GV->getType()->getElementType();
1781 // FIXME: Pass Global's alignment when globals have alignment
1782 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1783 if (!isa<UndefValue>(GV->getInitializer()))
1784 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1786 GV->replaceAllUsesWith(Alloca);
1787 GV->eraseFromParent();
1792 // If the global is never loaded (but may be stored to), it is dead.
1795 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1797 // Delete any stores we can find to the global. We may not be able to
1798 // make it completely dead though.
1799 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(),
1802 // If the global is dead now, delete it.
1803 if (GV->use_empty()) {
1804 GV->eraseFromParent();
1810 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1811 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1812 GV->setConstant(true);
1814 // Clean up any obviously simplifiable users now.
1815 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1817 // If the global is dead now, just nuke it.
1818 if (GV->use_empty()) {
1819 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1820 << "all users and delete global!\n");
1821 GV->eraseFromParent();
1827 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1828 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1829 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1830 GVI = FirstNewGV; // Don't skip the newly produced globals!
1833 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1834 // If the initial value for the global was an undef value, and if only
1835 // one other value was stored into it, we can just change the
1836 // initializer to be the stored value, then delete all stores to the
1837 // global. This allows us to mark it constant.
1838 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1839 if (isa<UndefValue>(GV->getInitializer())) {
1840 // Change the initial value here.
1841 GV->setInitializer(SOVConstant);
1843 // Clean up any obviously simplifiable users now.
1844 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1846 if (GV->use_empty()) {
1847 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1848 << "simplify all users and delete global!\n");
1849 GV->eraseFromParent();
1858 // Try to optimize globals based on the knowledge that only one value
1859 // (besides its initializer) is ever stored to the global.
1860 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
1864 // Otherwise, if the global was not a boolean, we can shrink it to be a
1866 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1867 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1876 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1877 /// function, changing them to FastCC.
1878 static void ChangeCalleesToFastCall(Function *F) {
1879 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1880 if (isa<BlockAddress>(*UI))
1882 CallSite User(cast<Instruction>(*UI));
1883 User.setCallingConv(CallingConv::Fast);
1887 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1888 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1889 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1892 // There can be only one.
1893 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1899 static void RemoveNestAttribute(Function *F) {
1900 F->setAttributes(StripNest(F->getAttributes()));
1901 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1902 if (isa<BlockAddress>(*UI))
1904 CallSite User(cast<Instruction>(*UI));
1905 User.setAttributes(StripNest(User.getAttributes()));
1909 bool GlobalOpt::OptimizeFunctions(Module &M) {
1910 bool Changed = false;
1911 // Optimize functions.
1912 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1914 // Functions without names cannot be referenced outside this module.
1915 if (!F->hasName() && !F->isDeclaration())
1916 F->setLinkage(GlobalValue::InternalLinkage);
1917 F->removeDeadConstantUsers();
1918 if (F->isDefTriviallyDead()) {
1919 F->eraseFromParent();
1922 } else if (F->hasLocalLinkage()) {
1923 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1924 !F->hasAddressTaken()) {
1925 // If this function has C calling conventions, is not a varargs
1926 // function, and is only called directly, promote it to use the Fast
1927 // calling convention.
1928 F->setCallingConv(CallingConv::Fast);
1929 ChangeCalleesToFastCall(F);
1934 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1935 !F->hasAddressTaken()) {
1936 // The function is not used by a trampoline intrinsic, so it is safe
1937 // to remove the 'nest' attribute.
1938 RemoveNestAttribute(F);
1947 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1948 bool Changed = false;
1949 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1951 GlobalVariable *GV = GVI++;
1952 // Global variables without names cannot be referenced outside this module.
1953 if (!GV->hasName() && !GV->isDeclaration())
1954 GV->setLinkage(GlobalValue::InternalLinkage);
1955 // Simplify the initializer.
1956 if (GV->hasInitializer())
1957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1958 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
1959 if (New && New != CE)
1960 GV->setInitializer(New);
1963 Changed |= ProcessGlobal(GV, GVI);
1968 /// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
1969 /// initializers have an init priority of 65535.
1970 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1971 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1972 if (GV == 0) return 0;
1974 // Verify that the initializer is simple enough for us to handle. We are
1975 // only allowed to optimize the initializer if it is unique.
1976 if (!GV->hasUniqueInitializer()) return 0;
1978 if (isa<ConstantAggregateZero>(GV->getInitializer()))
1980 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1982 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1983 if (isa<ConstantAggregateZero>(*i))
1985 ConstantStruct *CS = cast<ConstantStruct>(*i);
1986 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1989 // Must have a function or null ptr.
1990 if (!isa<Function>(CS->getOperand(1)))
1993 // Init priority must be standard.
1994 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
1995 if (CI->getZExtValue() != 65535)
2002 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2003 /// return a list of the functions and null terminator as a vector.
2004 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
2005 if (GV->getInitializer()->isNullValue())
2006 return std::vector<Function*>();
2007 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2008 std::vector<Function*> Result;
2009 Result.reserve(CA->getNumOperands());
2010 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2011 ConstantStruct *CS = cast<ConstantStruct>(*i);
2012 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2017 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2018 /// specified array, returning the new global to use.
2019 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
2020 const std::vector<Function*> &Ctors) {
2021 // If we made a change, reassemble the initializer list.
2022 Constant *CSVals[2];
2023 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2026 StructType *StructTy =
2028 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
2030 // Create the new init list.
2031 std::vector<Constant*> CAList;
2032 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2034 CSVals[1] = Ctors[i];
2036 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2038 PointerType *PFTy = PointerType::getUnqual(FTy);
2039 CSVals[1] = Constant::getNullValue(PFTy);
2040 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2043 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
2046 // Create the array initializer.
2047 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2048 CAList.size()), CAList);
2050 // If we didn't change the number of elements, don't create a new GV.
2051 if (CA->getType() == GCL->getInitializer()->getType()) {
2052 GCL->setInitializer(CA);
2056 // Create the new global and insert it next to the existing list.
2057 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2058 GCL->getLinkage(), CA, "",
2059 GCL->getThreadLocalMode());
2060 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2063 // Nuke the old list, replacing any uses with the new one.
2064 if (!GCL->use_empty()) {
2066 if (V->getType() != GCL->getType())
2067 V = ConstantExpr::getBitCast(V, GCL->getType());
2068 GCL->replaceAllUsesWith(V);
2070 GCL->eraseFromParent();
2080 isSimpleEnoughValueToCommit(Constant *C,
2081 SmallPtrSet<Constant*, 8> &SimpleConstants,
2082 const TargetData *TD);
2085 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2086 /// handled by the code generator. We don't want to generate something like:
2087 /// void *X = &X/42;
2088 /// because the code generator doesn't have a relocation that can handle that.
2090 /// This function should be called if C was not found (but just got inserted)
2091 /// in SimpleConstants to avoid having to rescan the same constants all the
2093 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2094 SmallPtrSet<Constant*, 8> &SimpleConstants,
2095 const TargetData *TD) {
2096 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2098 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2099 isa<GlobalValue>(C))
2102 // Aggregate values are safe if all their elements are.
2103 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2104 isa<ConstantVector>(C)) {
2105 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2106 Constant *Op = cast<Constant>(C->getOperand(i));
2107 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
2113 // We don't know exactly what relocations are allowed in constant expressions,
2114 // so we allow &global+constantoffset, which is safe and uniformly supported
2116 ConstantExpr *CE = cast<ConstantExpr>(C);
2117 switch (CE->getOpcode()) {
2118 case Instruction::BitCast:
2119 // Bitcast is fine if the casted value is fine.
2120 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2122 case Instruction::IntToPtr:
2123 case Instruction::PtrToInt:
2124 // int <=> ptr is fine if the int type is the same size as the
2126 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2127 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2129 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2131 // GEP is fine if it is simple + constant offset.
2132 case Instruction::GetElementPtr:
2133 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2134 if (!isa<ConstantInt>(CE->getOperand(i)))
2136 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2138 case Instruction::Add:
2139 // We allow simple+cst.
2140 if (!isa<ConstantInt>(CE->getOperand(1)))
2142 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2148 isSimpleEnoughValueToCommit(Constant *C,
2149 SmallPtrSet<Constant*, 8> &SimpleConstants,
2150 const TargetData *TD) {
2151 // If we already checked this constant, we win.
2152 if (!SimpleConstants.insert(C)) return true;
2153 // Check the constant.
2154 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
2158 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2159 /// enough for us to understand. In particular, if it is a cast to anything
2160 /// other than from one pointer type to another pointer type, we punt.
2161 /// We basically just support direct accesses to globals and GEP's of
2162 /// globals. This should be kept up to date with CommitValueTo.
2163 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2164 // Conservatively, avoid aggregate types. This is because we don't
2165 // want to worry about them partially overlapping other stores.
2166 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2169 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2170 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2171 // external globals.
2172 return GV->hasUniqueInitializer();
2174 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2175 // Handle a constantexpr gep.
2176 if (CE->getOpcode() == Instruction::GetElementPtr &&
2177 isa<GlobalVariable>(CE->getOperand(0)) &&
2178 cast<GEPOperator>(CE)->isInBounds()) {
2179 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2180 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2181 // external globals.
2182 if (!GV->hasUniqueInitializer())
2185 // The first index must be zero.
2186 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
2187 if (!CI || !CI->isZero()) return false;
2189 // The remaining indices must be compile-time known integers within the
2190 // notional bounds of the corresponding static array types.
2191 if (!CE->isGEPWithNoNotionalOverIndexing())
2194 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2196 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2197 // and we know how to evaluate it by moving the bitcast from the pointer
2198 // operand to the value operand.
2199 } else if (CE->getOpcode() == Instruction::BitCast &&
2200 isa<GlobalVariable>(CE->getOperand(0))) {
2201 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2202 // external globals.
2203 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
2210 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2211 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2212 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2213 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2214 ConstantExpr *Addr, unsigned OpNo) {
2215 // Base case of the recursion.
2216 if (OpNo == Addr->getNumOperands()) {
2217 assert(Val->getType() == Init->getType() && "Type mismatch!");
2221 SmallVector<Constant*, 32> Elts;
2222 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
2223 // Break up the constant into its elements.
2224 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2225 Elts.push_back(Init->getAggregateElement(i));
2227 // Replace the element that we are supposed to.
2228 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2229 unsigned Idx = CU->getZExtValue();
2230 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2231 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2233 // Return the modified struct.
2234 return ConstantStruct::get(STy, Elts);
2237 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2238 SequentialType *InitTy = cast<SequentialType>(Init->getType());
2241 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2242 NumElts = ATy->getNumElements();
2244 NumElts = InitTy->getVectorNumElements();
2246 // Break up the array into elements.
2247 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2248 Elts.push_back(Init->getAggregateElement(i));
2250 assert(CI->getZExtValue() < NumElts);
2251 Elts[CI->getZExtValue()] =
2252 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2254 if (Init->getType()->isArrayTy())
2255 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2256 return ConstantVector::get(Elts);
2259 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2260 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2261 static void CommitValueTo(Constant *Val, Constant *Addr) {
2262 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2263 assert(GV->hasInitializer());
2264 GV->setInitializer(Val);
2268 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2269 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2270 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2275 /// Evaluator - This class evaluates LLVM IR, producing the Constant
2276 /// representing each SSA instruction. Changes to global variables are stored
2277 /// in a mapping that can be iterated over after the evaluation is complete.
2278 /// Once an evaluation call fails, the evaluation object should not be reused.
2281 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
2282 : TD(TD), TLI(TLI) {
2283 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2287 DeleteContainerPointers(ValueStack);
2288 while (!AllocaTmps.empty()) {
2289 GlobalVariable *Tmp = AllocaTmps.back();
2290 AllocaTmps.pop_back();
2292 // If there are still users of the alloca, the program is doing something
2293 // silly, e.g. storing the address of the alloca somewhere and using it
2294 // later. Since this is undefined, we'll just make it be null.
2295 if (!Tmp->use_empty())
2296 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2301 /// EvaluateFunction - Evaluate a call to function F, returning true if
2302 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2303 /// arguments for the function.
2304 bool EvaluateFunction(Function *F, Constant *&RetVal,
2305 const SmallVectorImpl<Constant*> &ActualArgs);
2307 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2308 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2309 /// control flows into, or null upon return.
2310 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2312 Constant *getVal(Value *V) {
2313 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2314 Constant *R = ValueStack.back()->lookup(V);
2315 assert(R && "Reference to an uncomputed value!");
2319 void setVal(Value *V, Constant *C) {
2320 ValueStack.back()->operator[](V) = C;
2323 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2324 return MutatedMemory;
2327 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2332 Constant *ComputeLoadResult(Constant *P);
2334 /// ValueStack - As we compute SSA register values, we store their contents
2335 /// here. The back of the vector contains the current function and the stack
2336 /// contains the values in the calling frames.
2337 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2339 /// CallStack - This is used to detect recursion. In pathological situations
2340 /// we could hit exponential behavior, but at least there is nothing
2342 SmallVector<Function*, 4> CallStack;
2344 /// MutatedMemory - For each store we execute, we update this map. Loads
2345 /// check this to get the most up-to-date value. If evaluation is successful,
2346 /// this state is committed to the process.
2347 DenseMap<Constant*, Constant*> MutatedMemory;
2349 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2350 /// to represent its body. This vector is needed so we can delete the
2351 /// temporary globals when we are done.
2352 SmallVector<GlobalVariable*, 32> AllocaTmps;
2354 /// Invariants - These global variables have been marked invariant by the
2355 /// static constructor.
2356 SmallPtrSet<GlobalVariable*, 8> Invariants;
2358 /// SimpleConstants - These are constants we have checked and know to be
2359 /// simple enough to live in a static initializer of a global.
2360 SmallPtrSet<Constant*, 8> SimpleConstants;
2362 const TargetData *TD;
2363 const TargetLibraryInfo *TLI;
2366 } // anonymous namespace
2368 /// ComputeLoadResult - Return the value that would be computed by a load from
2369 /// P after the stores reflected by 'memory' have been performed. If we can't
2370 /// decide, return null.
2371 Constant *Evaluator::ComputeLoadResult(Constant *P) {
2372 // If this memory location has been recently stored, use the stored value: it
2373 // is the most up-to-date.
2374 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2375 if (I != MutatedMemory.end()) return I->second;
2378 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2379 if (GV->hasDefinitiveInitializer())
2380 return GV->getInitializer();
2384 // Handle a constantexpr getelementptr.
2385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2386 if (CE->getOpcode() == Instruction::GetElementPtr &&
2387 isa<GlobalVariable>(CE->getOperand(0))) {
2388 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2389 if (GV->hasDefinitiveInitializer())
2390 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2393 return 0; // don't know how to evaluate.
2396 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2397 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2398 /// control flows into, or null upon return.
2399 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2400 BasicBlock *&NextBB) {
2401 // This is the main evaluation loop.
2403 Constant *InstResult = 0;
2405 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2406 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
2407 Constant *Ptr = getVal(SI->getOperand(1));
2408 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2409 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2410 if (!isSimpleEnoughPointerToCommit(Ptr))
2411 // If this is too complex for us to commit, reject it.
2414 Constant *Val = getVal(SI->getOperand(0));
2416 // If this might be too difficult for the backend to handle (e.g. the addr
2417 // of one global variable divided by another) then we can't commit it.
2418 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
2421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2422 if (CE->getOpcode() == Instruction::BitCast) {
2423 // If we're evaluating a store through a bitcast, then we need
2424 // to pull the bitcast off the pointer type and push it onto the
2426 Ptr = CE->getOperand(0);
2428 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
2430 // In order to push the bitcast onto the stored value, a bitcast
2431 // from NewTy to Val's type must be legal. If it's not, we can try
2432 // introspecting NewTy to find a legal conversion.
2433 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2434 // If NewTy is a struct, we can convert the pointer to the struct
2435 // into a pointer to its first member.
2436 // FIXME: This could be extended to support arrays as well.
2437 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
2438 NewTy = STy->getTypeAtIndex(0U);
2440 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
2441 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2442 Constant * const IdxList[] = {IdxZero, IdxZero};
2444 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
2445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2446 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2448 // If we can't improve the situation by introspecting NewTy,
2449 // we have to give up.
2455 // If we found compatible types, go ahead and push the bitcast
2456 // onto the stored value.
2457 Val = ConstantExpr::getBitCast(Val, NewTy);
2460 MutatedMemory[Ptr] = Val;
2461 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2462 InstResult = ConstantExpr::get(BO->getOpcode(),
2463 getVal(BO->getOperand(0)),
2464 getVal(BO->getOperand(1)));
2465 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2466 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2467 getVal(CI->getOperand(0)),
2468 getVal(CI->getOperand(1)));
2469 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2470 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2471 getVal(CI->getOperand(0)),
2473 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2474 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2475 getVal(SI->getOperand(1)),
2476 getVal(SI->getOperand(2)));
2477 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2478 Constant *P = getVal(GEP->getOperand(0));
2479 SmallVector<Constant*, 8> GEPOps;
2480 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2482 GEPOps.push_back(getVal(*i));
2484 ConstantExpr::getGetElementPtr(P, GEPOps,
2485 cast<GEPOperator>(GEP)->isInBounds());
2486 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2487 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
2488 Constant *Ptr = getVal(LI->getOperand(0));
2489 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2490 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2491 InstResult = ComputeLoadResult(Ptr);
2492 if (InstResult == 0) return false; // Could not evaluate load.
2493 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2494 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2495 Type *Ty = AI->getType()->getElementType();
2496 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2497 GlobalValue::InternalLinkage,
2498 UndefValue::get(Ty),
2500 InstResult = AllocaTmps.back();
2501 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2502 CallSite CS(CurInst);
2504 // Debug info can safely be ignored here.
2505 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
2510 // Cannot handle inline asm.
2511 if (isa<InlineAsm>(CS.getCalledValue())) return false;
2513 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2514 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2515 if (MSI->isVolatile()) return false;
2516 Constant *Ptr = getVal(MSI->getDest());
2517 Constant *Val = getVal(MSI->getValue());
2518 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
2519 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2520 // This memset is a no-op.
2526 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2527 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2532 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2533 // We don't insert an entry into Values, as it doesn't have a
2534 // meaningful return value.
2535 if (!II->use_empty())
2537 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
2538 Value *PtrArg = getVal(II->getArgOperand(1));
2539 Value *Ptr = PtrArg->stripPointerCasts();
2540 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2541 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2542 if (!Size->isAllOnesValue() &&
2543 Size->getValue().getLimitedValue() >=
2544 TD->getTypeStoreSize(ElemTy))
2545 Invariants.insert(GV);
2547 // Continue even if we do nothing.
2554 // Resolve function pointers.
2555 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
2556 if (!Callee || Callee->mayBeOverridden())
2557 return false; // Cannot resolve.
2559 SmallVector<Constant*, 8> Formals;
2560 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
2561 Formals.push_back(getVal(*i));
2563 if (Callee->isDeclaration()) {
2564 // If this is a function we can constant fold, do it.
2565 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
2571 if (Callee->getFunctionType()->isVarArg())
2575 // Execute the call, if successful, use the return value.
2576 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2577 if (!EvaluateFunction(Callee, RetVal, Formals))
2579 delete ValueStack.pop_back_val();
2580 InstResult = RetVal;
2582 } else if (isa<TerminatorInst>(CurInst)) {
2583 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2584 if (BI->isUnconditional()) {
2585 NextBB = BI->getSuccessor(0);
2588 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
2589 if (!Cond) return false; // Cannot determine.
2591 NextBB = BI->getSuccessor(!Cond->getZExtValue());
2593 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2595 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
2596 if (!Val) return false; // Cannot determine.
2597 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
2598 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2599 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
2600 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2601 NextBB = BA->getBasicBlock();
2603 return false; // Cannot determine.
2604 } else if (isa<ReturnInst>(CurInst)) {
2607 // invoke, unwind, resume, unreachable.
2608 return false; // Cannot handle this terminator.
2611 // We succeeded at evaluating this block!
2614 // Did not know how to evaluate this!
2618 if (!CurInst->use_empty()) {
2619 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2620 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
2622 setVal(CurInst, InstResult);
2625 // If we just processed an invoke, we finished evaluating the block.
2626 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2627 NextBB = II->getNormalDest();
2631 // Advance program counter.
2636 /// EvaluateFunction - Evaluate a call to function F, returning true if
2637 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2638 /// arguments for the function.
2639 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2640 const SmallVectorImpl<Constant*> &ActualArgs) {
2641 // Check to see if this function is already executing (recursion). If so,
2642 // bail out. TODO: we might want to accept limited recursion.
2643 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2646 CallStack.push_back(F);
2648 // Initialize arguments to the incoming values specified.
2650 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2652 setVal(AI, ActualArgs[ArgNo]);
2654 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2655 // we can only evaluate any one basic block at most once. This set keeps
2656 // track of what we have executed so we can detect recursive cases etc.
2657 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2659 // CurBB - The current basic block we're evaluating.
2660 BasicBlock *CurBB = F->begin();
2662 BasicBlock::iterator CurInst = CurBB->begin();
2665 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
2666 if (!EvaluateBlock(CurInst, NextBB))
2670 // Successfully running until there's no next block means that we found
2671 // the return. Fill it the return value and pop the call stack.
2672 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2673 if (RI->getNumOperands())
2674 RetVal = getVal(RI->getOperand(0));
2675 CallStack.pop_back();
2679 // Okay, we succeeded in evaluating this control flow. See if we have
2680 // executed the new block before. If so, we have a looping function,
2681 // which we cannot evaluate in reasonable time.
2682 if (!ExecutedBlocks.insert(NextBB))
2683 return false; // looped!
2685 // Okay, we have never been in this block before. Check to see if there
2686 // are any PHI nodes. If so, evaluate them with information about where
2689 for (CurInst = NextBB->begin();
2690 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2691 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
2693 // Advance to the next block.
2698 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2699 /// we can. Return true if we can, false otherwise.
2700 static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2701 const TargetLibraryInfo *TLI) {
2702 // Call the function.
2703 Evaluator Eval(TD, TLI);
2704 Constant *RetValDummy;
2705 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2706 SmallVector<Constant*, 0>());
2709 // We succeeded at evaluation: commit the result.
2710 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2711 << F->getName() << "' to " << Eval.getMutatedMemory().size()
2713 for (DenseMap<Constant*, Constant*>::const_iterator I =
2714 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2716 CommitValueTo(I->second, I->first);
2717 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2718 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2720 (*I)->setConstant(true);
2726 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2727 /// Return true if anything changed.
2728 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2729 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2730 bool MadeChange = false;
2731 if (Ctors.empty()) return false;
2733 // Loop over global ctors, optimizing them when we can.
2734 for (unsigned i = 0; i != Ctors.size(); ++i) {
2735 Function *F = Ctors[i];
2736 // Found a null terminator in the middle of the list, prune off the rest of
2739 if (i != Ctors.size()-1) {
2746 // We cannot simplify external ctor functions.
2747 if (F->empty()) continue;
2749 // If we can evaluate the ctor at compile time, do.
2750 if (EvaluateStaticConstructor(F, TD, TLI)) {
2751 Ctors.erase(Ctors.begin()+i);
2754 ++NumCtorsEvaluated;
2759 if (!MadeChange) return false;
2761 GCL = InstallGlobalCtors(GCL, Ctors);
2765 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2766 bool Changed = false;
2768 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2770 Module::alias_iterator J = I++;
2771 // Aliases without names cannot be referenced outside this module.
2772 if (!J->hasName() && !J->isDeclaration())
2773 J->setLinkage(GlobalValue::InternalLinkage);
2774 // If the aliasee may change at link time, nothing can be done - bail out.
2775 if (J->mayBeOverridden())
2778 Constant *Aliasee = J->getAliasee();
2779 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2780 Target->removeDeadConstantUsers();
2781 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2783 // Make all users of the alias use the aliasee instead.
2784 if (!J->use_empty()) {
2785 J->replaceAllUsesWith(Aliasee);
2786 ++NumAliasesResolved;
2790 // If the alias is externally visible, we may still be able to simplify it.
2791 if (!J->hasLocalLinkage()) {
2792 // If the aliasee has internal linkage, give it the name and linkage
2793 // of the alias, and delete the alias. This turns:
2794 // define internal ... @f(...)
2795 // @a = alias ... @f
2797 // define ... @a(...)
2798 if (!Target->hasLocalLinkage())
2801 // Do not perform the transform if multiple aliases potentially target the
2802 // aliasee. This check also ensures that it is safe to replace the section
2803 // and other attributes of the aliasee with those of the alias.
2807 // Give the aliasee the name, linkage and other attributes of the alias.
2808 Target->takeName(J);
2809 Target->setLinkage(J->getLinkage());
2810 Target->GlobalValue::copyAttributesFrom(J);
2813 // Delete the alias.
2814 M.getAliasList().erase(J);
2815 ++NumAliasesRemoved;
2822 static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2823 if (!TLI->has(LibFunc::cxa_atexit))
2826 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
2831 FunctionType *FTy = Fn->getFunctionType();
2833 // Checking that the function has the right return type, the right number of
2834 // parameters and that they all have pointer types should be enough.
2835 if (!FTy->getReturnType()->isIntegerTy() ||
2836 FTy->getNumParams() != 3 ||
2837 !FTy->getParamType(0)->isPointerTy() ||
2838 !FTy->getParamType(1)->isPointerTy() ||
2839 !FTy->getParamType(2)->isPointerTy())
2845 /// cxxDtorIsEmpty - Returns whether the given function is an empty C++
2846 /// destructor and can therefore be eliminated.
2847 /// Note that we assume that other optimization passes have already simplified
2848 /// the code so we only look for a function with a single basic block, where
2849 /// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
2850 /// other side-effect free instructions.
2851 static bool cxxDtorIsEmpty(const Function &Fn,
2852 SmallPtrSet<const Function *, 8> &CalledFunctions) {
2853 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
2854 // nounwind, but that doesn't seem worth doing.
2855 if (Fn.isDeclaration())
2858 if (++Fn.begin() != Fn.end())
2861 const BasicBlock &EntryBlock = Fn.getEntryBlock();
2862 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
2864 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
2865 // Ignore debug intrinsics.
2866 if (isa<DbgInfoIntrinsic>(CI))
2869 const Function *CalledFn = CI->getCalledFunction();
2874 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
2876 // Don't treat recursive functions as empty.
2877 if (!NewCalledFunctions.insert(CalledFn))
2880 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
2882 } else if (isa<ReturnInst>(*I))
2883 return true; // We're done.
2884 else if (I->mayHaveSideEffects())
2885 return false; // Destructor with side effects, bail.
2891 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
2892 /// Itanium C++ ABI p3.3.5:
2894 /// After constructing a global (or local static) object, that will require
2895 /// destruction on exit, a termination function is registered as follows:
2897 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
2899 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
2900 /// call f(p) when DSO d is unloaded, before all such termination calls
2901 /// registered before this one. It returns zero if registration is
2902 /// successful, nonzero on failure.
2904 // This pass will look for calls to __cxa_atexit where the function is trivial
2906 bool Changed = false;
2908 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
2909 E = CXAAtExitFn->use_end(); I != E;) {
2910 // We're only interested in calls. Theoretically, we could handle invoke
2911 // instructions as well, but neither llvm-gcc nor clang generate invokes
2913 CallInst *CI = dyn_cast<CallInst>(*I++);
2918 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
2922 SmallPtrSet<const Function *, 8> CalledFunctions;
2923 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
2926 // Just remove the call.
2927 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
2928 CI->eraseFromParent();
2930 ++NumCXXDtorsRemoved;
2938 bool GlobalOpt::runOnModule(Module &M) {
2939 bool Changed = false;
2941 TD = getAnalysisIfAvailable<TargetData>();
2942 TLI = &getAnalysis<TargetLibraryInfo>();
2944 // Try to find the llvm.globalctors list.
2945 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2947 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
2949 bool LocalChange = true;
2950 while (LocalChange) {
2951 LocalChange = false;
2953 // Delete functions that are trivially dead, ccc -> fastcc
2954 LocalChange |= OptimizeFunctions(M);
2956 // Optimize global_ctors list.
2958 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2960 // Optimize non-address-taken globals.
2961 LocalChange |= OptimizeGlobalVars(M);
2963 // Resolve aliases, when possible.
2964 LocalChange |= OptimizeGlobalAliases(M);
2966 // Try to remove trivial global destructors.
2968 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
2970 Changed |= LocalChange;
2973 // TODO: Move all global ctors functions to the end of the module for code