LLVM API Documentation

GlobalOpt.cpp
Go to the documentation of this file.
00001 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass transforms simple global variables that never have their address
00011 // taken.  If obviously true, it marks read/write globals as constant, deletes
00012 // variables only stored to, etc.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #define DEBUG_TYPE "globalopt"
00017 #include "llvm/Transforms/IPO.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallPtrSet.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Analysis/ConstantFolding.h"
00024 #include "llvm/Analysis/MemoryBuiltins.h"
00025 #include "llvm/IR/CallingConv.h"
00026 #include "llvm/IR/Constants.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/DerivedTypes.h"
00029 #include "llvm/IR/Instructions.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/IR/Module.h"
00032 #include "llvm/IR/Operator.h"
00033 #include "llvm/Pass.h"
00034 #include "llvm/Support/CallSite.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/GetElementPtrTypeIterator.h"
00038 #include "llvm/Support/MathExtras.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 #include "llvm/Target/TargetLibraryInfo.h"
00041 #include <algorithm>
00042 using namespace llvm;
00043 
00044 STATISTIC(NumMarked    , "Number of globals marked constant");
00045 STATISTIC(NumUnnamed   , "Number of globals marked unnamed_addr");
00046 STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
00047 STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
00048 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
00049 STATISTIC(NumDeleted   , "Number of globals deleted");
00050 STATISTIC(NumFnDeleted , "Number of functions deleted");
00051 STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
00052 STATISTIC(NumLocalized , "Number of globals localized");
00053 STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
00054 STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
00055 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
00056 STATISTIC(NumNestRemoved   , "Number of nest attributes removed");
00057 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
00058 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
00059 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
00060 
00061 namespace {
00062   struct GlobalStatus;
00063   struct GlobalOpt : public ModulePass {
00064     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00065       AU.addRequired<TargetLibraryInfo>();
00066     }
00067     static char ID; // Pass identification, replacement for typeid
00068     GlobalOpt() : ModulePass(ID) {
00069       initializeGlobalOptPass(*PassRegistry::getPassRegistry());
00070     }
00071 
00072     bool runOnModule(Module &M);
00073 
00074   private:
00075     GlobalVariable *FindGlobalCtors(Module &M);
00076     bool OptimizeFunctions(Module &M);
00077     bool OptimizeGlobalVars(Module &M);
00078     bool OptimizeGlobalAliases(Module &M);
00079     bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
00080     bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
00081     bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
00082                                const SmallPtrSet<const PHINode*, 16> &PHIUsers,
00083                                const GlobalStatus &GS);
00084     bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
00085 
00086     DataLayout *TD;
00087     TargetLibraryInfo *TLI;
00088   };
00089 }
00090 
00091 char GlobalOpt::ID = 0;
00092 INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
00093                 "Global Variable Optimizer", false, false)
00094 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00095 INITIALIZE_PASS_END(GlobalOpt, "globalopt",
00096                 "Global Variable Optimizer", false, false)
00097 
00098 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
00099 
00100 namespace {
00101 
00102 /// GlobalStatus - As we analyze each global, keep track of some information
00103 /// about it.  If we find out that the address of the global is taken, none of
00104 /// this info will be accurate.
00105 struct GlobalStatus {
00106   /// isCompared - True if the global's address is used in a comparison.
00107   bool isCompared;
00108 
00109   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
00110   /// loaded it can be deleted.
00111   bool isLoaded;
00112 
00113   /// StoredType - Keep track of what stores to the global look like.
00114   ///
00115   enum StoredType {
00116     /// NotStored - There is no store to this global.  It can thus be marked
00117     /// constant.
00118     NotStored,
00119 
00120     /// isInitializerStored - This global is stored to, but the only thing
00121     /// stored is the constant it was initialized with.  This is only tracked
00122     /// for scalar globals.
00123     isInitializerStored,
00124 
00125     /// isStoredOnce - This global is stored to, but only its initializer and
00126     /// one other value is ever stored to it.  If this global isStoredOnce, we
00127     /// track the value stored to it in StoredOnceValue below.  This is only
00128     /// tracked for scalar globals.
00129     isStoredOnce,
00130 
00131     /// isStored - This global is stored to by multiple values or something else
00132     /// that we cannot track.
00133     isStored
00134   } StoredType;
00135 
00136   /// StoredOnceValue - If only one value (besides the initializer constant) is
00137   /// ever stored to this global, keep track of what value it is.
00138   Value *StoredOnceValue;
00139 
00140   /// AccessingFunction/HasMultipleAccessingFunctions - These start out
00141   /// null/false.  When the first accessing function is noticed, it is recorded.
00142   /// When a second different accessing function is noticed,
00143   /// HasMultipleAccessingFunctions is set to true.
00144   const Function *AccessingFunction;
00145   bool HasMultipleAccessingFunctions;
00146 
00147   /// HasNonInstructionUser - Set to true if this global has a user that is not
00148   /// an instruction (e.g. a constant expr or GV initializer).
00149   bool HasNonInstructionUser;
00150 
00151   /// AtomicOrdering - Set to the strongest atomic ordering requirement.
00152   AtomicOrdering Ordering;
00153 
00154   GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
00155                    StoredOnceValue(0), AccessingFunction(0),
00156                    HasMultipleAccessingFunctions(false),
00157                    HasNonInstructionUser(false), Ordering(NotAtomic) {}
00158 };
00159 
00160 }
00161 
00162 /// StrongerOrdering - Return the stronger of the two ordering. If the two
00163 /// orderings are acquire and release, then return AcquireRelease.
00164 ///
00165 static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
00166   if (X == Acquire && Y == Release) return AcquireRelease;
00167   if (Y == Acquire && X == Release) return AcquireRelease;
00168   return (AtomicOrdering)std::max(X, Y);
00169 }
00170 
00171 /// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
00172 /// by constants itself.  Note that constants cannot be cyclic, so this test is
00173 /// pretty easy to implement recursively.
00174 ///
00175 static bool SafeToDestroyConstant(const Constant *C) {
00176   if (isa<GlobalValue>(C)) return false;
00177 
00178   for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
00179        ++UI)
00180     if (const Constant *CU = dyn_cast<Constant>(*UI)) {
00181       if (!SafeToDestroyConstant(CU)) return false;
00182     } else
00183       return false;
00184   return true;
00185 }
00186 
00187 
00188 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
00189 /// structure.  If the global has its address taken, return true to indicate we
00190 /// can't do anything with it.
00191 ///
00192 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
00193                           SmallPtrSet<const PHINode*, 16> &PHIUsers) {
00194   for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
00195        ++UI) {
00196     const User *U = *UI;
00197     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00198       GS.HasNonInstructionUser = true;
00199 
00200       // If the result of the constantexpr isn't pointer type, then we won't
00201       // know to expect it in various places.  Just reject early.
00202       if (!isa<PointerType>(CE->getType())) return true;
00203 
00204       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
00205     } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
00206       if (!GS.HasMultipleAccessingFunctions) {
00207         const Function *F = I->getParent()->getParent();
00208         if (GS.AccessingFunction == 0)
00209           GS.AccessingFunction = F;
00210         else if (GS.AccessingFunction != F)
00211           GS.HasMultipleAccessingFunctions = true;
00212       }
00213       if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
00214         GS.isLoaded = true;
00215         // Don't hack on volatile loads.
00216         if (LI->isVolatile()) return true;
00217         GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
00218       } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
00219         // Don't allow a store OF the address, only stores TO the address.
00220         if (SI->getOperand(0) == V) return true;
00221 
00222         // Don't hack on volatile stores.
00223         if (SI->isVolatile()) return true;
00224 
00225         GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
00226 
00227         // If this is a direct store to the global (i.e., the global is a scalar
00228         // value, not an aggregate), keep more specific information about
00229         // stores.
00230         if (GS.StoredType != GlobalStatus::isStored) {
00231           if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
00232                                                            SI->getOperand(1))) {
00233             Value *StoredVal = SI->getOperand(0);
00234 
00235             if (Constant *C = dyn_cast<Constant>(StoredVal)) {
00236               if (C->isThreadDependent()) {
00237                 // The stored value changes between threads; don't track it.
00238                 return true;
00239               }
00240             }
00241 
00242             if (StoredVal == GV->getInitializer()) {
00243               if (GS.StoredType < GlobalStatus::isInitializerStored)
00244                 GS.StoredType = GlobalStatus::isInitializerStored;
00245             } else if (isa<LoadInst>(StoredVal) &&
00246                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
00247               if (GS.StoredType < GlobalStatus::isInitializerStored)
00248                 GS.StoredType = GlobalStatus::isInitializerStored;
00249             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
00250               GS.StoredType = GlobalStatus::isStoredOnce;
00251               GS.StoredOnceValue = StoredVal;
00252             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
00253                        GS.StoredOnceValue == StoredVal) {
00254               // noop.
00255             } else {
00256               GS.StoredType = GlobalStatus::isStored;
00257             }
00258           } else {
00259             GS.StoredType = GlobalStatus::isStored;
00260           }
00261         }
00262       } else if (isa<BitCastInst>(I)) {
00263         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
00264       } else if (isa<GetElementPtrInst>(I)) {
00265         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
00266       } else if (isa<SelectInst>(I)) {
00267         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
00268       } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
00269         // PHI nodes we can check just like select or GEP instructions, but we
00270         // have to be careful about infinite recursion.
00271         if (PHIUsers.insert(PN))  // Not already visited.
00272           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
00273       } else if (isa<CmpInst>(I)) {
00274         GS.isCompared = true;
00275       } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
00276         if (MTI->isVolatile()) return true;
00277         if (MTI->getArgOperand(0) == V)
00278           GS.StoredType = GlobalStatus::isStored;
00279         if (MTI->getArgOperand(1) == V)
00280           GS.isLoaded = true;
00281       } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
00282         assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
00283         if (MSI->isVolatile()) return true;
00284         GS.StoredType = GlobalStatus::isStored;
00285       } else {
00286         return true;  // Any other non-load instruction might take address!
00287       }
00288     } else if (const Constant *C = dyn_cast<Constant>(U)) {
00289       GS.HasNonInstructionUser = true;
00290       // We might have a dead and dangling constant hanging off of here.
00291       if (!SafeToDestroyConstant(C))
00292         return true;
00293     } else {
00294       GS.HasNonInstructionUser = true;
00295       // Otherwise must be some other user.
00296       return true;
00297     }
00298   }
00299 
00300   return false;
00301 }
00302 
00303 /// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
00304 /// as a root?  If so, we might not really want to eliminate the stores to it.
00305 static bool isLeakCheckerRoot(GlobalVariable *GV) {
00306   // A global variable is a root if it is a pointer, or could plausibly contain
00307   // a pointer.  There are two challenges; one is that we could have a struct
00308   // the has an inner member which is a pointer.  We recurse through the type to
00309   // detect these (up to a point).  The other is that we may actually be a union
00310   // of a pointer and another type, and so our LLVM type is an integer which
00311   // gets converted into a pointer, or our type is an [i8 x #] with a pointer
00312   // potentially contained here.
00313 
00314   if (GV->hasPrivateLinkage())
00315     return false;
00316 
00317   SmallVector<Type *, 4> Types;
00318   Types.push_back(cast<PointerType>(GV->getType())->getElementType());
00319 
00320   unsigned Limit = 20;
00321   do {
00322     Type *Ty = Types.pop_back_val();
00323     switch (Ty->getTypeID()) {
00324       default: break;
00325       case Type::PointerTyID: return true;
00326       case Type::ArrayTyID:
00327       case Type::VectorTyID: {
00328         SequentialType *STy = cast<SequentialType>(Ty);
00329         Types.push_back(STy->getElementType());
00330         break;
00331       }
00332       case Type::StructTyID: {
00333         StructType *STy = cast<StructType>(Ty);
00334         if (STy->isOpaque()) return true;
00335         for (StructType::element_iterator I = STy->element_begin(),
00336                  E = STy->element_end(); I != E; ++I) {
00337           Type *InnerTy = *I;
00338           if (isa<PointerType>(InnerTy)) return true;
00339           if (isa<CompositeType>(InnerTy))
00340             Types.push_back(InnerTy);
00341         }
00342         break;
00343       }
00344     }
00345     if (--Limit == 0) return true;
00346   } while (!Types.empty());
00347   return false;
00348 }
00349 
00350 /// Given a value that is stored to a global but never read, determine whether
00351 /// it's safe to remove the store and the chain of computation that feeds the
00352 /// store.
00353 static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
00354   do {
00355     if (isa<Constant>(V))
00356       return true;
00357     if (!V->hasOneUse())
00358       return false;
00359     if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
00360         isa<GlobalValue>(V))
00361       return false;
00362     if (isAllocationFn(V, TLI))
00363       return true;
00364 
00365     Instruction *I = cast<Instruction>(V);
00366     if (I->mayHaveSideEffects())
00367       return false;
00368     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00369       if (!GEP->hasAllConstantIndices())
00370         return false;
00371     } else if (I->getNumOperands() != 1) {
00372       return false;
00373     }
00374 
00375     V = I->getOperand(0);
00376   } while (1);
00377 }
00378 
00379 /// CleanupPointerRootUsers - This GV is a pointer root.  Loop over all users
00380 /// of the global and clean up any that obviously don't assign the global a
00381 /// value that isn't dynamically allocated.
00382 ///
00383 static bool CleanupPointerRootUsers(GlobalVariable *GV,
00384                                     const TargetLibraryInfo *TLI) {
00385   // A brief explanation of leak checkers.  The goal is to find bugs where
00386   // pointers are forgotten, causing an accumulating growth in memory
00387   // usage over time.  The common strategy for leak checkers is to whitelist the
00388   // memory pointed to by globals at exit.  This is popular because it also
00389   // solves another problem where the main thread of a C++ program may shut down
00390   // before other threads that are still expecting to use those globals.  To
00391   // handle that case, we expect the program may create a singleton and never
00392   // destroy it.
00393 
00394   bool Changed = false;
00395 
00396   // If Dead[n].first is the only use of a malloc result, we can delete its
00397   // chain of computation and the store to the global in Dead[n].second.
00398   SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
00399 
00400   // Constants can't be pointers to dynamically allocated memory.
00401   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
00402        UI != E;) {
00403     User *U = *UI++;
00404     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00405       Value *V = SI->getValueOperand();
00406       if (isa<Constant>(V)) {
00407         Changed = true;
00408         SI->eraseFromParent();
00409       } else if (Instruction *I = dyn_cast<Instruction>(V)) {
00410         if (I->hasOneUse())
00411           Dead.push_back(std::make_pair(I, SI));
00412       }
00413     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
00414       if (isa<Constant>(MSI->getValue())) {
00415         Changed = true;
00416         MSI->eraseFromParent();
00417       } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
00418         if (I->hasOneUse())
00419           Dead.push_back(std::make_pair(I, MSI));
00420       }
00421     } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
00422       GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
00423       if (MemSrc && MemSrc->isConstant()) {
00424         Changed = true;
00425         MTI->eraseFromParent();
00426       } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
00427         if (I->hasOneUse())
00428           Dead.push_back(std::make_pair(I, MTI));
00429       }
00430     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00431       if (CE->use_empty()) {
00432         CE->destroyConstant();
00433         Changed = true;
00434       }
00435     } else if (Constant *C = dyn_cast<Constant>(U)) {
00436       if (SafeToDestroyConstant(C)) {
00437         C->destroyConstant();
00438         // This could have invalidated UI, start over from scratch.
00439         Dead.clear();
00440         CleanupPointerRootUsers(GV, TLI);
00441         return true;
00442       }
00443     }
00444   }
00445 
00446   for (int i = 0, e = Dead.size(); i != e; ++i) {
00447     if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
00448       Dead[i].second->eraseFromParent();
00449       Instruction *I = Dead[i].first;
00450       do {
00451         if (isAllocationFn(I, TLI))
00452           break;
00453         Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
00454         if (!J)
00455           break;
00456         I->eraseFromParent();
00457         I = J;
00458       } while (1);
00459       I->eraseFromParent();
00460     }
00461   }
00462 
00463   return Changed;
00464 }
00465 
00466 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
00467 /// users of the global, cleaning up the obvious ones.  This is largely just a
00468 /// quick scan over the use list to clean up the easy and obvious cruft.  This
00469 /// returns true if it made a change.
00470 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
00471                                        DataLayout *TD, TargetLibraryInfo *TLI) {
00472   bool Changed = false;
00473   SmallVector<User*, 8> WorkList(V->use_begin(), V->use_end());
00474   while (!WorkList.empty()) {
00475     User *U = WorkList.pop_back_val();
00476 
00477     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
00478       if (Init) {
00479         // Replace the load with the initializer.
00480         LI->replaceAllUsesWith(Init);
00481         LI->eraseFromParent();
00482         Changed = true;
00483       }
00484     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00485       // Store must be unreachable or storing Init into the global.
00486       SI->eraseFromParent();
00487       Changed = true;
00488     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00489       if (CE->getOpcode() == Instruction::GetElementPtr) {
00490         Constant *SubInit = 0;
00491         if (Init)
00492           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
00493         Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
00494       } else if (CE->getOpcode() == Instruction::BitCast &&
00495                  CE->getType()->isPointerTy()) {
00496         // Pointer cast, delete any stores and memsets to the global.
00497         Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
00498       }
00499 
00500       if (CE->use_empty()) {
00501         CE->destroyConstant();
00502         Changed = true;
00503       }
00504     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
00505       // Do not transform "gepinst (gep constexpr (GV))" here, because forming
00506       // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
00507       // and will invalidate our notion of what Init is.
00508       Constant *SubInit = 0;
00509       if (!isa<ConstantExpr>(GEP->getOperand(0))) {
00510         ConstantExpr *CE =
00511           dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
00512         if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
00513           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
00514 
00515         // If the initializer is an all-null value and we have an inbounds GEP,
00516         // we already know what the result of any load from that GEP is.
00517         // TODO: Handle splats.
00518         if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
00519           SubInit = Constant::getNullValue(GEP->getType()->getElementType());
00520       }
00521       Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
00522 
00523       if (GEP->use_empty()) {
00524         GEP->eraseFromParent();
00525         Changed = true;
00526       }
00527     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
00528       if (MI->getRawDest() == V) {
00529         MI->eraseFromParent();
00530         Changed = true;
00531       }
00532 
00533     } else if (Constant *C = dyn_cast<Constant>(U)) {
00534       // If we have a chain of dead constantexprs or other things dangling from
00535       // us, and if they are all dead, nuke them without remorse.
00536       if (SafeToDestroyConstant(C)) {
00537         C->destroyConstant();
00538         CleanupConstantGlobalUsers(V, Init, TD, TLI);
00539         return true;
00540       }
00541     }
00542   }
00543   return Changed;
00544 }
00545 
00546 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
00547 /// user of a derived expression from a global that we want to SROA.
00548 static bool isSafeSROAElementUse(Value *V) {
00549   // We might have a dead and dangling constant hanging off of here.
00550   if (Constant *C = dyn_cast<Constant>(V))
00551     return SafeToDestroyConstant(C);
00552 
00553   Instruction *I = dyn_cast<Instruction>(V);
00554   if (!I) return false;
00555 
00556   // Loads are ok.
00557   if (isa<LoadInst>(I)) return true;
00558 
00559   // Stores *to* the pointer are ok.
00560   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00561     return SI->getOperand(0) != V;
00562 
00563   // Otherwise, it must be a GEP.
00564   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
00565   if (GEPI == 0) return false;
00566 
00567   if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
00568       !cast<Constant>(GEPI->getOperand(1))->isNullValue())
00569     return false;
00570 
00571   for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
00572        I != E; ++I)
00573     if (!isSafeSROAElementUse(*I))
00574       return false;
00575   return true;
00576 }
00577 
00578 
00579 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
00580 /// Look at it and its uses and decide whether it is safe to SROA this global.
00581 ///
00582 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
00583   // The user of the global must be a GEP Inst or a ConstantExpr GEP.
00584   if (!isa<GetElementPtrInst>(U) &&
00585       (!isa<ConstantExpr>(U) ||
00586        cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
00587     return false;
00588 
00589   // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
00590   // don't like < 3 operand CE's, and we don't like non-constant integer
00591   // indices.  This enforces that all uses are 'gep GV, 0, C, ...' for some
00592   // value of C.
00593   if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
00594       !cast<Constant>(U->getOperand(1))->isNullValue() ||
00595       !isa<ConstantInt>(U->getOperand(2)))
00596     return false;
00597 
00598   gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
00599   ++GEPI;  // Skip over the pointer index.
00600 
00601   // If this is a use of an array allocation, do a bit more checking for sanity.
00602   if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
00603     uint64_t NumElements = AT->getNumElements();
00604     ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
00605 
00606     // Check to make sure that index falls within the array.  If not,
00607     // something funny is going on, so we won't do the optimization.
00608     //
00609     if (Idx->getZExtValue() >= NumElements)
00610       return false;
00611 
00612     // We cannot scalar repl this level of the array unless any array
00613     // sub-indices are in-range constants.  In particular, consider:
00614     // A[0][i].  We cannot know that the user isn't doing invalid things like
00615     // allowing i to index an out-of-range subscript that accesses A[1].
00616     //
00617     // Scalar replacing *just* the outer index of the array is probably not
00618     // going to be a win anyway, so just give up.
00619     for (++GEPI; // Skip array index.
00620          GEPI != E;
00621          ++GEPI) {
00622       uint64_t NumElements;
00623       if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
00624         NumElements = SubArrayTy->getNumElements();
00625       else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
00626         NumElements = SubVectorTy->getNumElements();
00627       else {
00628         assert((*GEPI)->isStructTy() &&
00629                "Indexed GEP type is not array, vector, or struct!");
00630         continue;
00631       }
00632 
00633       ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
00634       if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
00635         return false;
00636     }
00637   }
00638 
00639   for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
00640     if (!isSafeSROAElementUse(*I))
00641       return false;
00642   return true;
00643 }
00644 
00645 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
00646 /// is safe for us to perform this transformation.
00647 ///
00648 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
00649   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
00650        UI != E; ++UI) {
00651     if (!IsUserOfGlobalSafeForSRA(*UI, GV))
00652       return false;
00653   }
00654   return true;
00655 }
00656 
00657 
00658 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
00659 /// variable.  This opens the door for other optimizations by exposing the
00660 /// behavior of the program in a more fine-grained way.  We have determined that
00661 /// this transformation is safe already.  We return the first global variable we
00662 /// insert so that the caller can reprocess it.
00663 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &TD) {
00664   // Make sure this global only has simple uses that we can SRA.
00665   if (!GlobalUsersSafeToSRA(GV))
00666     return 0;
00667 
00668   assert(GV->hasLocalLinkage() && !GV->isConstant());
00669   Constant *Init = GV->getInitializer();
00670   Type *Ty = Init->getType();
00671 
00672   std::vector<GlobalVariable*> NewGlobals;
00673   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
00674 
00675   // Get the alignment of the global, either explicit or target-specific.
00676   unsigned StartAlignment = GV->getAlignment();
00677   if (StartAlignment == 0)
00678     StartAlignment = TD.getABITypeAlignment(GV->getType());
00679 
00680   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00681     NewGlobals.reserve(STy->getNumElements());
00682     const StructLayout &Layout = *TD.getStructLayout(STy);
00683     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00684       Constant *In = Init->getAggregateElement(i);
00685       assert(In && "Couldn't get element of initializer?");
00686       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
00687                                                GlobalVariable::InternalLinkage,
00688                                                In, GV->getName()+"."+Twine(i),
00689                                                GV->getThreadLocalMode(),
00690                                               GV->getType()->getAddressSpace());
00691       Globals.insert(GV, NGV);
00692       NewGlobals.push_back(NGV);
00693 
00694       // Calculate the known alignment of the field.  If the original aggregate
00695       // had 256 byte alignment for example, something might depend on that:
00696       // propagate info to each field.
00697       uint64_t FieldOffset = Layout.getElementOffset(i);
00698       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
00699       if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
00700         NGV->setAlignment(NewAlign);
00701     }
00702   } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
00703     unsigned NumElements = 0;
00704     if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
00705       NumElements = ATy->getNumElements();
00706     else
00707       NumElements = cast<VectorType>(STy)->getNumElements();
00708 
00709     if (NumElements > 16 && GV->hasNUsesOrMore(16))
00710       return 0; // It's not worth it.
00711     NewGlobals.reserve(NumElements);
00712 
00713     uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
00714     unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
00715     for (unsigned i = 0, e = NumElements; i != e; ++i) {
00716       Constant *In = Init->getAggregateElement(i);
00717       assert(In && "Couldn't get element of initializer?");
00718 
00719       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
00720                                                GlobalVariable::InternalLinkage,
00721                                                In, GV->getName()+"."+Twine(i),
00722                                                GV->getThreadLocalMode(),
00723                                               GV->getType()->getAddressSpace());
00724       Globals.insert(GV, NGV);
00725       NewGlobals.push_back(NGV);
00726 
00727       // Calculate the known alignment of the field.  If the original aggregate
00728       // had 256 byte alignment for example, something might depend on that:
00729       // propagate info to each field.
00730       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
00731       if (NewAlign > EltAlign)
00732         NGV->setAlignment(NewAlign);
00733     }
00734   }
00735 
00736   if (NewGlobals.empty())
00737     return 0;
00738 
00739   DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
00740 
00741   Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
00742 
00743   // Loop over all of the uses of the global, replacing the constantexpr geps,
00744   // with smaller constantexpr geps or direct references.
00745   while (!GV->use_empty()) {
00746     User *GEP = GV->use_back();
00747     assert(((isa<ConstantExpr>(GEP) &&
00748              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
00749             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
00750 
00751     // Ignore the 1th operand, which has to be zero or else the program is quite
00752     // broken (undefined).  Get the 2nd operand, which is the structure or array
00753     // index.
00754     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
00755     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
00756 
00757     Value *NewPtr = NewGlobals[Val];
00758 
00759     // Form a shorter GEP if needed.
00760     if (GEP->getNumOperands() > 3) {
00761       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
00762         SmallVector<Constant*, 8> Idxs;
00763         Idxs.push_back(NullInt);
00764         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
00765           Idxs.push_back(CE->getOperand(i));
00766         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
00767       } else {
00768         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
00769         SmallVector<Value*, 8> Idxs;
00770         Idxs.push_back(NullInt);
00771         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
00772           Idxs.push_back(GEPI->getOperand(i));
00773         NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
00774                                            GEPI->getName()+"."+Twine(Val),GEPI);
00775       }
00776     }
00777     GEP->replaceAllUsesWith(NewPtr);
00778 
00779     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
00780       GEPI->eraseFromParent();
00781     else
00782       cast<ConstantExpr>(GEP)->destroyConstant();
00783   }
00784 
00785   // Delete the old global, now that it is dead.
00786   Globals.erase(GV);
00787   ++NumSRA;
00788 
00789   // Loop over the new globals array deleting any globals that are obviously
00790   // dead.  This can arise due to scalarization of a structure or an array that
00791   // has elements that are dead.
00792   unsigned FirstGlobal = 0;
00793   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
00794     if (NewGlobals[i]->use_empty()) {
00795       Globals.erase(NewGlobals[i]);
00796       if (FirstGlobal == i) ++FirstGlobal;
00797     }
00798 
00799   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
00800 }
00801 
00802 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
00803 /// value will trap if the value is dynamically null.  PHIs keeps track of any
00804 /// phi nodes we've seen to avoid reprocessing them.
00805 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
00806                                          SmallPtrSet<const PHINode*, 8> &PHIs) {
00807   for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
00808        ++UI) {
00809     const User *U = *UI;
00810 
00811     if (isa<LoadInst>(U)) {
00812       // Will trap.
00813     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
00814       if (SI->getOperand(0) == V) {
00815         //cerr << "NONTRAPPING USE: " << *U;
00816         return false;  // Storing the value.
00817       }
00818     } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
00819       if (CI->getCalledValue() != V) {
00820         //cerr << "NONTRAPPING USE: " << *U;
00821         return false;  // Not calling the ptr
00822       }
00823     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
00824       if (II->getCalledValue() != V) {
00825         //cerr << "NONTRAPPING USE: " << *U;
00826         return false;  // Not calling the ptr
00827       }
00828     } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
00829       if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
00830     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
00831       if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
00832     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
00833       // If we've already seen this phi node, ignore it, it has already been
00834       // checked.
00835       if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
00836         return false;
00837     } else if (isa<ICmpInst>(U) &&
00838                isa<ConstantPointerNull>(UI->getOperand(1))) {
00839       // Ignore icmp X, null
00840     } else {
00841       //cerr << "NONTRAPPING USE: " << *U;
00842       return false;
00843     }
00844   }
00845   return true;
00846 }
00847 
00848 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
00849 /// from GV will trap if the loaded value is null.  Note that this also permits
00850 /// comparisons of the loaded value against null, as a special case.
00851 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
00852   for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
00853        UI != E; ++UI) {
00854     const User *U = *UI;
00855 
00856     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
00857       SmallPtrSet<const PHINode*, 8> PHIs;
00858       if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
00859         return false;
00860     } else if (isa<StoreInst>(U)) {
00861       // Ignore stores to the global.
00862     } else {
00863       // We don't know or understand this user, bail out.
00864       //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
00865       return false;
00866     }
00867   }
00868   return true;
00869 }
00870 
00871 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
00872   bool Changed = false;
00873   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
00874     Instruction *I = cast<Instruction>(*UI++);
00875     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00876       LI->setOperand(0, NewV);
00877       Changed = true;
00878     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00879       if (SI->getOperand(1) == V) {
00880         SI->setOperand(1, NewV);
00881         Changed = true;
00882       }
00883     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
00884       CallSite CS(I);
00885       if (CS.getCalledValue() == V) {
00886         // Calling through the pointer!  Turn into a direct call, but be careful
00887         // that the pointer is not also being passed as an argument.
00888         CS.setCalledFunction(NewV);
00889         Changed = true;
00890         bool PassedAsArg = false;
00891         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
00892           if (CS.getArgument(i) == V) {
00893             PassedAsArg = true;
00894             CS.setArgument(i, NewV);
00895           }
00896 
00897         if (PassedAsArg) {
00898           // Being passed as an argument also.  Be careful to not invalidate UI!
00899           UI = V->use_begin();
00900         }
00901       }
00902     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
00903       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
00904                                 ConstantExpr::getCast(CI->getOpcode(),
00905                                                       NewV, CI->getType()));
00906       if (CI->use_empty()) {
00907         Changed = true;
00908         CI->eraseFromParent();
00909       }
00910     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
00911       // Should handle GEP here.
00912       SmallVector<Constant*, 8> Idxs;
00913       Idxs.reserve(GEPI->getNumOperands()-1);
00914       for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
00915            i != e; ++i)
00916         if (Constant *C = dyn_cast<Constant>(*i))
00917           Idxs.push_back(C);
00918         else
00919           break;
00920       if (Idxs.size() == GEPI->getNumOperands()-1)
00921         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
00922                           ConstantExpr::getGetElementPtr(NewV, Idxs));
00923       if (GEPI->use_empty()) {
00924         Changed = true;
00925         GEPI->eraseFromParent();
00926       }
00927     }
00928   }
00929 
00930   return Changed;
00931 }
00932 
00933 
00934 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
00935 /// value stored into it.  If there are uses of the loaded value that would trap
00936 /// if the loaded value is dynamically null, then we know that they cannot be
00937 /// reachable with a null optimize away the load.
00938 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
00939                                             DataLayout *TD,
00940                                             TargetLibraryInfo *TLI) {
00941   bool Changed = false;
00942 
00943   // Keep track of whether we are able to remove all the uses of the global
00944   // other than the store that defines it.
00945   bool AllNonStoreUsesGone = true;
00946 
00947   // Replace all uses of loads with uses of uses of the stored value.
00948   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
00949     User *GlobalUser = *GUI++;
00950     if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
00951       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
00952       // If we were able to delete all uses of the loads
00953       if (LI->use_empty()) {
00954         LI->eraseFromParent();
00955         Changed = true;
00956       } else {
00957         AllNonStoreUsesGone = false;
00958       }
00959     } else if (isa<StoreInst>(GlobalUser)) {
00960       // Ignore the store that stores "LV" to the global.
00961       assert(GlobalUser->getOperand(1) == GV &&
00962              "Must be storing *to* the global");
00963     } else {
00964       AllNonStoreUsesGone = false;
00965 
00966       // If we get here we could have other crazy uses that are transitively
00967       // loaded.
00968       assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
00969               isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
00970               isa<BitCastInst>(GlobalUser) ||
00971               isa<GetElementPtrInst>(GlobalUser)) &&
00972              "Only expect load and stores!");
00973     }
00974   }
00975 
00976   if (Changed) {
00977     DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
00978     ++NumGlobUses;
00979   }
00980 
00981   // If we nuked all of the loads, then none of the stores are needed either,
00982   // nor is the global.
00983   if (AllNonStoreUsesGone) {
00984     if (isLeakCheckerRoot(GV)) {
00985       Changed |= CleanupPointerRootUsers(GV, TLI);
00986     } else {
00987       Changed = true;
00988       CleanupConstantGlobalUsers(GV, 0, TD, TLI);
00989     }
00990     if (GV->use_empty()) {
00991       DEBUG(dbgs() << "  *** GLOBAL NOW DEAD!\n");
00992       Changed = true;
00993       GV->eraseFromParent();
00994       ++NumDeleted;
00995     }
00996   }
00997   return Changed;
00998 }
00999 
01000 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
01001 /// instructions that are foldable.
01002 static void ConstantPropUsersOf(Value *V,
01003                                 DataLayout *TD, TargetLibraryInfo *TLI) {
01004   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
01005     if (Instruction *I = dyn_cast<Instruction>(*UI++))
01006       if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
01007         I->replaceAllUsesWith(NewC);
01008 
01009         // Advance UI to the next non-I use to avoid invalidating it!
01010         // Instructions could multiply use V.
01011         while (UI != E && *UI == I)
01012           ++UI;
01013         I->eraseFromParent();
01014       }
01015 }
01016 
01017 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
01018 /// variable, and transforms the program as if it always contained the result of
01019 /// the specified malloc.  Because it is always the result of the specified
01020 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
01021 /// malloc into a global, and any loads of GV as uses of the new global.
01022 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
01023                                                      CallInst *CI,
01024                                                      Type *AllocTy,
01025                                                      ConstantInt *NElements,
01026                                                      DataLayout *TD,
01027                                                      TargetLibraryInfo *TLI) {
01028   DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << "  CALL = " << *CI << '\n');
01029 
01030   Type *GlobalType;
01031   if (NElements->getZExtValue() == 1)
01032     GlobalType = AllocTy;
01033   else
01034     // If we have an array allocation, the global variable is of an array.
01035     GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
01036 
01037   // Create the new global variable.  The contents of the malloc'd memory is
01038   // undefined, so initialize with an undef value.
01039   GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
01040                                              GlobalType, false,
01041                                              GlobalValue::InternalLinkage,
01042                                              UndefValue::get(GlobalType),
01043                                              GV->getName()+".body",
01044                                              GV,
01045                                              GV->getThreadLocalMode());
01046 
01047   // If there are bitcast users of the malloc (which is typical, usually we have
01048   // a malloc + bitcast) then replace them with uses of the new global.  Update
01049   // other users to use the global as well.
01050   BitCastInst *TheBC = 0;
01051   while (!CI->use_empty()) {
01052     Instruction *User = cast<Instruction>(CI->use_back());
01053     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
01054       if (BCI->getType() == NewGV->getType()) {
01055         BCI->replaceAllUsesWith(NewGV);
01056         BCI->eraseFromParent();
01057       } else {
01058         BCI->setOperand(0, NewGV);
01059       }
01060     } else {
01061       if (TheBC == 0)
01062         TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
01063       User->replaceUsesOfWith(CI, TheBC);
01064     }
01065   }
01066 
01067   Constant *RepValue = NewGV;
01068   if (NewGV->getType() != GV->getType()->getElementType())
01069     RepValue = ConstantExpr::getBitCast(RepValue,
01070                                         GV->getType()->getElementType());
01071 
01072   // If there is a comparison against null, we will insert a global bool to
01073   // keep track of whether the global was initialized yet or not.
01074   GlobalVariable *InitBool =
01075     new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
01076                        GlobalValue::InternalLinkage,
01077                        ConstantInt::getFalse(GV->getContext()),
01078                        GV->getName()+".init", GV->getThreadLocalMode());
01079   bool InitBoolUsed = false;
01080 
01081   // Loop over all uses of GV, processing them in turn.
01082   while (!GV->use_empty()) {
01083     if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
01084       // The global is initialized when the store to it occurs.
01085       new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
01086                     SI->getOrdering(), SI->getSynchScope(), SI);
01087       SI->eraseFromParent();
01088       continue;
01089     }
01090 
01091     LoadInst *LI = cast<LoadInst>(GV->use_back());
01092     while (!LI->use_empty()) {
01093       Use &LoadUse = LI->use_begin().getUse();
01094       if (!isa<ICmpInst>(LoadUse.getUser())) {
01095         LoadUse = RepValue;
01096         continue;
01097       }
01098 
01099       ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
01100       // Replace the cmp X, 0 with a use of the bool value.
01101       // Sink the load to where the compare was, if atomic rules allow us to.
01102       Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
01103                                LI->getOrdering(), LI->getSynchScope(),
01104                                LI->isUnordered() ? (Instruction*)ICI : LI);
01105       InitBoolUsed = true;
01106       switch (ICI->getPredicate()) {
01107       default: llvm_unreachable("Unknown ICmp Predicate!");
01108       case ICmpInst::ICMP_ULT:
01109       case ICmpInst::ICMP_SLT:   // X < null -> always false
01110         LV = ConstantInt::getFalse(GV->getContext());
01111         break;
01112       case ICmpInst::ICMP_ULE:
01113       case ICmpInst::ICMP_SLE:
01114       case ICmpInst::ICMP_EQ:
01115         LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
01116         break;
01117       case ICmpInst::ICMP_NE:
01118       case ICmpInst::ICMP_UGE:
01119       case ICmpInst::ICMP_SGE:
01120       case ICmpInst::ICMP_UGT:
01121       case ICmpInst::ICMP_SGT:
01122         break;  // no change.
01123       }
01124       ICI->replaceAllUsesWith(LV);
01125       ICI->eraseFromParent();
01126     }
01127     LI->eraseFromParent();
01128   }
01129 
01130   // If the initialization boolean was used, insert it, otherwise delete it.
01131   if (!InitBoolUsed) {
01132     while (!InitBool->use_empty())  // Delete initializations
01133       cast<StoreInst>(InitBool->use_back())->eraseFromParent();
01134     delete InitBool;
01135   } else
01136     GV->getParent()->getGlobalList().insert(GV, InitBool);
01137 
01138   // Now the GV is dead, nuke it and the malloc..
01139   GV->eraseFromParent();
01140   CI->eraseFromParent();
01141 
01142   // To further other optimizations, loop over all users of NewGV and try to
01143   // constant prop them.  This will promote GEP instructions with constant
01144   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
01145   ConstantPropUsersOf(NewGV, TD, TLI);
01146   if (RepValue != NewGV)
01147     ConstantPropUsersOf(RepValue, TD, TLI);
01148 
01149   return NewGV;
01150 }
01151 
01152 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
01153 /// to make sure that there are no complex uses of V.  We permit simple things
01154 /// like dereferencing the pointer, but not storing through the address, unless
01155 /// it is to the specified global.
01156 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
01157                                                       const GlobalVariable *GV,
01158                                          SmallPtrSet<const PHINode*, 8> &PHIs) {
01159   for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
01160        UI != E; ++UI) {
01161     const Instruction *Inst = cast<Instruction>(*UI);
01162 
01163     if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
01164       continue; // Fine, ignore.
01165     }
01166 
01167     if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
01168       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
01169         return false;  // Storing the pointer itself... bad.
01170       continue; // Otherwise, storing through it, or storing into GV... fine.
01171     }
01172 
01173     // Must index into the array and into the struct.
01174     if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
01175       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
01176         return false;
01177       continue;
01178     }
01179 
01180     if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
01181       // PHIs are ok if all uses are ok.  Don't infinitely recurse through PHI
01182       // cycles.
01183       if (PHIs.insert(PN))
01184         if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
01185           return false;
01186       continue;
01187     }
01188 
01189     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
01190       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
01191         return false;
01192       continue;
01193     }
01194 
01195     return false;
01196   }
01197   return true;
01198 }
01199 
01200 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
01201 /// somewhere.  Transform all uses of the allocation into loads from the
01202 /// global and uses of the resultant pointer.  Further, delete the store into
01203 /// GV.  This assumes that these value pass the
01204 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
01205 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
01206                                           GlobalVariable *GV) {
01207   while (!Alloc->use_empty()) {
01208     Instruction *U = cast<Instruction>(*Alloc->use_begin());
01209     Instruction *InsertPt = U;
01210     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
01211       // If this is the store of the allocation into the global, remove it.
01212       if (SI->getOperand(1) == GV) {
01213         SI->eraseFromParent();
01214         continue;
01215       }
01216     } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
01217       // Insert the load in the corresponding predecessor, not right before the
01218       // PHI.
01219       InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
01220     } else if (isa<BitCastInst>(U)) {
01221       // Must be bitcast between the malloc and store to initialize the global.
01222       ReplaceUsesOfMallocWithGlobal(U, GV);
01223       U->eraseFromParent();
01224       continue;
01225     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
01226       // If this is a "GEP bitcast" and the user is a store to the global, then
01227       // just process it as a bitcast.
01228       if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
01229         if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
01230           if (SI->getOperand(1) == GV) {
01231             // Must be bitcast GEP between the malloc and store to initialize
01232             // the global.
01233             ReplaceUsesOfMallocWithGlobal(GEPI, GV);
01234             GEPI->eraseFromParent();
01235             continue;
01236           }
01237     }
01238 
01239     // Insert a load from the global, and use it instead of the malloc.
01240     Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
01241     U->replaceUsesOfWith(Alloc, NL);
01242   }
01243 }
01244 
01245 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
01246 /// of a load) are simple enough to perform heap SRA on.  This permits GEP's
01247 /// that index through the array and struct field, icmps of null, and PHIs.
01248 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
01249                         SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
01250                         SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
01251   // We permit two users of the load: setcc comparing against the null
01252   // pointer, and a getelementptr of a specific form.
01253   for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
01254        ++UI) {
01255     const Instruction *User = cast<Instruction>(*UI);
01256 
01257     // Comparison against null is ok.
01258     if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
01259       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
01260         return false;
01261       continue;
01262     }
01263 
01264     // getelementptr is also ok, but only a simple form.
01265     if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01266       // Must index into the array and into the struct.
01267       if (GEPI->getNumOperands() < 3)
01268         return false;
01269 
01270       // Otherwise the GEP is ok.
01271       continue;
01272     }
01273 
01274     if (const PHINode *PN = dyn_cast<PHINode>(User)) {
01275       if (!LoadUsingPHIsPerLoad.insert(PN))
01276         // This means some phi nodes are dependent on each other.
01277         // Avoid infinite looping!
01278         return false;
01279       if (!LoadUsingPHIs.insert(PN))
01280         // If we have already analyzed this PHI, then it is safe.
01281         continue;
01282 
01283       // Make sure all uses of the PHI are simple enough to transform.
01284       if (!LoadUsesSimpleEnoughForHeapSRA(PN,
01285                                           LoadUsingPHIs, LoadUsingPHIsPerLoad))
01286         return false;
01287 
01288       continue;
01289     }
01290 
01291     // Otherwise we don't know what this is, not ok.
01292     return false;
01293   }
01294 
01295   return true;
01296 }
01297 
01298 
01299 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
01300 /// GV are simple enough to perform HeapSRA, return true.
01301 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
01302                                                     Instruction *StoredVal) {
01303   SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
01304   SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
01305   for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
01306        UI != E; ++UI)
01307     if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
01308       if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
01309                                           LoadUsingPHIsPerLoad))
01310         return false;
01311       LoadUsingPHIsPerLoad.clear();
01312     }
01313 
01314   // If we reach here, we know that all uses of the loads and transitive uses
01315   // (through PHI nodes) are simple enough to transform.  However, we don't know
01316   // that all inputs the to the PHI nodes are in the same equivalence sets.
01317   // Check to verify that all operands of the PHIs are either PHIS that can be
01318   // transformed, loads from GV, or MI itself.
01319   for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
01320        , E = LoadUsingPHIs.end(); I != E; ++I) {
01321     const PHINode *PN = *I;
01322     for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
01323       Value *InVal = PN->getIncomingValue(op);
01324 
01325       // PHI of the stored value itself is ok.
01326       if (InVal == StoredVal) continue;
01327 
01328       if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
01329         // One of the PHIs in our set is (optimistically) ok.
01330         if (LoadUsingPHIs.count(InPN))
01331           continue;
01332         return false;
01333       }
01334 
01335       // Load from GV is ok.
01336       if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
01337         if (LI->getOperand(0) == GV)
01338           continue;
01339 
01340       // UNDEF? NULL?
01341 
01342       // Anything else is rejected.
01343       return false;
01344     }
01345   }
01346 
01347   return true;
01348 }
01349 
01350 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
01351                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01352                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01353   std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
01354 
01355   if (FieldNo >= FieldVals.size())
01356     FieldVals.resize(FieldNo+1);
01357 
01358   // If we already have this value, just reuse the previously scalarized
01359   // version.
01360   if (Value *FieldVal = FieldVals[FieldNo])
01361     return FieldVal;
01362 
01363   // Depending on what instruction this is, we have several cases.
01364   Value *Result;
01365   if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
01366     // This is a scalarized version of the load from the global.  Just create
01367     // a new Load of the scalarized global.
01368     Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
01369                                            InsertedScalarizedValues,
01370                                            PHIsToRewrite),
01371                           LI->getName()+".f"+Twine(FieldNo), LI);
01372   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
01373     // PN's type is pointer to struct.  Make a new PHI of pointer to struct
01374     // field.
01375     StructType *ST =
01376       cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
01377 
01378     PHINode *NewPN =
01379      PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
01380                      PN->getNumIncomingValues(),
01381                      PN->getName()+".f"+Twine(FieldNo), PN);
01382     Result = NewPN;
01383     PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
01384   } else {
01385     llvm_unreachable("Unknown usable value");
01386   }
01387 
01388   return FieldVals[FieldNo] = Result;
01389 }
01390 
01391 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
01392 /// the load, rewrite the derived value to use the HeapSRoA'd load.
01393 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
01394              DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01395                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01396   // If this is a comparison against null, handle it.
01397   if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
01398     assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
01399     // If we have a setcc of the loaded pointer, we can use a setcc of any
01400     // field.
01401     Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
01402                                    InsertedScalarizedValues, PHIsToRewrite);
01403 
01404     Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
01405                               Constant::getNullValue(NPtr->getType()),
01406                               SCI->getName());
01407     SCI->replaceAllUsesWith(New);
01408     SCI->eraseFromParent();
01409     return;
01410   }
01411 
01412   // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
01413   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
01414     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
01415            && "Unexpected GEPI!");
01416 
01417     // Load the pointer for this field.
01418     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
01419     Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
01420                                      InsertedScalarizedValues, PHIsToRewrite);
01421 
01422     // Create the new GEP idx vector.
01423     SmallVector<Value*, 8> GEPIdx;
01424     GEPIdx.push_back(GEPI->getOperand(1));
01425     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
01426 
01427     Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
01428                                              GEPI->getName(), GEPI);
01429     GEPI->replaceAllUsesWith(NGEPI);
01430     GEPI->eraseFromParent();
01431     return;
01432   }
01433 
01434   // Recursively transform the users of PHI nodes.  This will lazily create the
01435   // PHIs that are needed for individual elements.  Keep track of what PHIs we
01436   // see in InsertedScalarizedValues so that we don't get infinite loops (very
01437   // antisocial).  If the PHI is already in InsertedScalarizedValues, it has
01438   // already been seen first by another load, so its uses have already been
01439   // processed.
01440   PHINode *PN = cast<PHINode>(LoadUser);
01441   if (!InsertedScalarizedValues.insert(std::make_pair(PN,
01442                                               std::vector<Value*>())).second)
01443     return;
01444 
01445   // If this is the first time we've seen this PHI, recursively process all
01446   // users.
01447   for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
01448     Instruction *User = cast<Instruction>(*UI++);
01449     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
01450   }
01451 }
01452 
01453 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
01454 /// is a value loaded from the global.  Eliminate all uses of Ptr, making them
01455 /// use FieldGlobals instead.  All uses of loaded values satisfy
01456 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
01457 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
01458                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01459                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01460   for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
01461        UI != E; ) {
01462     Instruction *User = cast<Instruction>(*UI++);
01463     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
01464   }
01465 
01466   if (Load->use_empty()) {
01467     Load->eraseFromParent();
01468     InsertedScalarizedValues.erase(Load);
01469   }
01470 }
01471 
01472 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures.  Break
01473 /// it up into multiple allocations of arrays of the fields.
01474 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
01475                                             Value *NElems, DataLayout *TD,
01476                                             const TargetLibraryInfo *TLI) {
01477   DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *CI << '\n');
01478   Type *MAT = getMallocAllocatedType(CI, TLI);
01479   StructType *STy = cast<StructType>(MAT);
01480 
01481   // There is guaranteed to be at least one use of the malloc (storing
01482   // it into GV).  If there are other uses, change them to be uses of
01483   // the global to simplify later code.  This also deletes the store
01484   // into GV.
01485   ReplaceUsesOfMallocWithGlobal(CI, GV);
01486 
01487   // Okay, at this point, there are no users of the malloc.  Insert N
01488   // new mallocs at the same place as CI, and N globals.
01489   std::vector<Value*> FieldGlobals;
01490   std::vector<Value*> FieldMallocs;
01491 
01492   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
01493     Type *FieldTy = STy->getElementType(FieldNo);
01494     PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
01495 
01496     GlobalVariable *NGV =
01497       new GlobalVariable(*GV->getParent(),
01498                          PFieldTy, false, GlobalValue::InternalLinkage,
01499                          Constant::getNullValue(PFieldTy),
01500                          GV->getName() + ".f" + Twine(FieldNo), GV,
01501                          GV->getThreadLocalMode());
01502     FieldGlobals.push_back(NGV);
01503 
01504     unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
01505     if (StructType *ST = dyn_cast<StructType>(FieldTy))
01506       TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
01507     Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
01508     Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
01509                                         ConstantInt::get(IntPtrTy, TypeSize),
01510                                         NElems, 0,
01511                                         CI->getName() + ".f" + Twine(FieldNo));
01512     FieldMallocs.push_back(NMI);
01513     new StoreInst(NMI, NGV, CI);
01514   }
01515 
01516   // The tricky aspect of this transformation is handling the case when malloc
01517   // fails.  In the original code, malloc failing would set the result pointer
01518   // of malloc to null.  In this case, some mallocs could succeed and others
01519   // could fail.  As such, we emit code that looks like this:
01520   //    F0 = malloc(field0)
01521   //    F1 = malloc(field1)
01522   //    F2 = malloc(field2)
01523   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
01524   //      if (F0) { free(F0); F0 = 0; }
01525   //      if (F1) { free(F1); F1 = 0; }
01526   //      if (F2) { free(F2); F2 = 0; }
01527   //    }
01528   // The malloc can also fail if its argument is too large.
01529   Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
01530   Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
01531                                   ConstantZero, "isneg");
01532   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
01533     Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
01534                              Constant::getNullValue(FieldMallocs[i]->getType()),
01535                                "isnull");
01536     RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
01537   }
01538 
01539   // Split the basic block at the old malloc.
01540   BasicBlock *OrigBB = CI->getParent();
01541   BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
01542 
01543   // Create the block to check the first condition.  Put all these blocks at the
01544   // end of the function as they are unlikely to be executed.
01545   BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
01546                                                 "malloc_ret_null",
01547                                                 OrigBB->getParent());
01548 
01549   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
01550   // branch on RunningOr.
01551   OrigBB->getTerminator()->eraseFromParent();
01552   BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
01553 
01554   // Within the NullPtrBlock, we need to emit a comparison and branch for each
01555   // pointer, because some may be null while others are not.
01556   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
01557     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
01558     Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
01559                               Constant::getNullValue(GVVal->getType()));
01560     BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
01561                                                OrigBB->getParent());
01562     BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
01563                                                OrigBB->getParent());
01564     Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
01565                                          Cmp, NullPtrBlock);
01566 
01567     // Fill in FreeBlock.
01568     CallInst::CreateFree(GVVal, BI);
01569     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
01570                   FreeBlock);
01571     BranchInst::Create(NextBlock, FreeBlock);
01572 
01573     NullPtrBlock = NextBlock;
01574   }
01575 
01576   BranchInst::Create(ContBB, NullPtrBlock);
01577 
01578   // CI is no longer needed, remove it.
01579   CI->eraseFromParent();
01580 
01581   /// InsertedScalarizedLoads - As we process loads, if we can't immediately
01582   /// update all uses of the load, keep track of what scalarized loads are
01583   /// inserted for a given load.
01584   DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
01585   InsertedScalarizedValues[GV] = FieldGlobals;
01586 
01587   std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
01588 
01589   // Okay, the malloc site is completely handled.  All of the uses of GV are now
01590   // loads, and all uses of those loads are simple.  Rewrite them to use loads
01591   // of the per-field globals instead.
01592   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
01593     Instruction *User = cast<Instruction>(*UI++);
01594 
01595     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01596       RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
01597       continue;
01598     }
01599 
01600     // Must be a store of null.
01601     StoreInst *SI = cast<StoreInst>(User);
01602     assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
01603            "Unexpected heap-sra user!");
01604 
01605     // Insert a store of null into each global.
01606     for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
01607       PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
01608       Constant *Null = Constant::getNullValue(PT->getElementType());
01609       new StoreInst(Null, FieldGlobals[i], SI);
01610     }
01611     // Erase the original store.
01612     SI->eraseFromParent();
01613   }
01614 
01615   // While we have PHIs that are interesting to rewrite, do it.
01616   while (!PHIsToRewrite.empty()) {
01617     PHINode *PN = PHIsToRewrite.back().first;
01618     unsigned FieldNo = PHIsToRewrite.back().second;
01619     PHIsToRewrite.pop_back();
01620     PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
01621     assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
01622 
01623     // Add all the incoming values.  This can materialize more phis.
01624     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01625       Value *InVal = PN->getIncomingValue(i);
01626       InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
01627                                PHIsToRewrite);
01628       FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
01629     }
01630   }
01631 
01632   // Drop all inter-phi links and any loads that made it this far.
01633   for (DenseMap<Value*, std::vector<Value*> >::iterator
01634        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
01635        I != E; ++I) {
01636     if (PHINode *PN = dyn_cast<PHINode>(I->first))
01637       PN->dropAllReferences();
01638     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
01639       LI->dropAllReferences();
01640   }
01641 
01642   // Delete all the phis and loads now that inter-references are dead.
01643   for (DenseMap<Value*, std::vector<Value*> >::iterator
01644        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
01645        I != E; ++I) {
01646     if (PHINode *PN = dyn_cast<PHINode>(I->first))
01647       PN->eraseFromParent();
01648     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
01649       LI->eraseFromParent();
01650   }
01651 
01652   // The old global is now dead, remove it.
01653   GV->eraseFromParent();
01654 
01655   ++NumHeapSRA;
01656   return cast<GlobalVariable>(FieldGlobals[0]);
01657 }
01658 
01659 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
01660 /// pointer global variable with a single value stored it that is a malloc or
01661 /// cast of malloc.
01662 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
01663                                                CallInst *CI,
01664                                                Type *AllocTy,
01665                                                AtomicOrdering Ordering,
01666                                                Module::global_iterator &GVI,
01667                                                DataLayout *TD,
01668                                                TargetLibraryInfo *TLI) {
01669   if (!TD)
01670     return false;
01671 
01672   // If this is a malloc of an abstract type, don't touch it.
01673   if (!AllocTy->isSized())
01674     return false;
01675 
01676   // We can't optimize this global unless all uses of it are *known* to be
01677   // of the malloc value, not of the null initializer value (consider a use
01678   // that compares the global's value against zero to see if the malloc has
01679   // been reached).  To do this, we check to see if all uses of the global
01680   // would trap if the global were null: this proves that they must all
01681   // happen after the malloc.
01682   if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
01683     return false;
01684 
01685   // We can't optimize this if the malloc itself is used in a complex way,
01686   // for example, being stored into multiple globals.  This allows the
01687   // malloc to be stored into the specified global, loaded icmp'd, and
01688   // GEP'd.  These are all things we could transform to using the global
01689   // for.
01690   SmallPtrSet<const PHINode*, 8> PHIs;
01691   if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
01692     return false;
01693 
01694   // If we have a global that is only initialized with a fixed size malloc,
01695   // transform the program to use global memory instead of malloc'd memory.
01696   // This eliminates dynamic allocation, avoids an indirection accessing the
01697   // data, and exposes the resultant global to further GlobalOpt.
01698   // We cannot optimize the malloc if we cannot determine malloc array size.
01699   Value *NElems = getMallocArraySize(CI, TD, TLI, true);
01700   if (!NElems)
01701     return false;
01702 
01703   if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
01704     // Restrict this transformation to only working on small allocations
01705     // (2048 bytes currently), as we don't want to introduce a 16M global or
01706     // something.
01707     if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
01708       GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
01709       return true;
01710     }
01711 
01712   // If the allocation is an array of structures, consider transforming this
01713   // into multiple malloc'd arrays, one for each field.  This is basically
01714   // SRoA for malloc'd memory.
01715 
01716   if (Ordering != NotAtomic)
01717     return false;
01718 
01719   // If this is an allocation of a fixed size array of structs, analyze as a
01720   // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
01721   if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
01722     if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
01723       AllocTy = AT->getElementType();
01724 
01725   StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
01726   if (!AllocSTy)
01727     return false;
01728 
01729   // This the structure has an unreasonable number of fields, leave it
01730   // alone.
01731   if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
01732       AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
01733 
01734     // If this is a fixed size array, transform the Malloc to be an alloc of
01735     // structs.  malloc [100 x struct],1 -> malloc struct, 100
01736     if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
01737       Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
01738       unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
01739       Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
01740       Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
01741       Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
01742                                                    AllocSize, NumElements,
01743                                                    0, CI->getName());
01744       Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
01745       CI->replaceAllUsesWith(Cast);
01746       CI->eraseFromParent();
01747       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
01748         CI = cast<CallInst>(BCI->getOperand(0));
01749       else
01750         CI = cast<CallInst>(Malloc);
01751     }
01752 
01753     GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, TLI, true),
01754                                TD, TLI);
01755     return true;
01756   }
01757 
01758   return false;
01759 }
01760 
01761 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
01762 // that only one value (besides its initializer) is ever stored to the global.
01763 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
01764                                      AtomicOrdering Ordering,
01765                                      Module::global_iterator &GVI,
01766                                      DataLayout *TD, TargetLibraryInfo *TLI) {
01767   // Ignore no-op GEPs and bitcasts.
01768   StoredOnceVal = StoredOnceVal->stripPointerCasts();
01769 
01770   // If we are dealing with a pointer global that is initialized to null and
01771   // only has one (non-null) value stored into it, then we can optimize any
01772   // users of the loaded value (often calls and loads) that would trap if the
01773   // value was null.
01774   if (GV->getInitializer()->getType()->isPointerTy() &&
01775       GV->getInitializer()->isNullValue()) {
01776     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
01777       if (GV->getInitializer()->getType() != SOVC->getType())
01778         SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
01779 
01780       // Optimize away any trapping uses of the loaded value.
01781       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
01782         return true;
01783     } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
01784       Type *MallocType = getMallocAllocatedType(CI, TLI);
01785       if (MallocType &&
01786           TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
01787                                              TD, TLI))
01788         return true;
01789     }
01790   }
01791 
01792   return false;
01793 }
01794 
01795 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
01796 /// two values ever stored into GV are its initializer and OtherVal.  See if we
01797 /// can shrink the global into a boolean and select between the two values
01798 /// whenever it is used.  This exposes the values to other scalar optimizations.
01799 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
01800   Type *GVElType = GV->getType()->getElementType();
01801 
01802   // If GVElType is already i1, it is already shrunk.  If the type of the GV is
01803   // an FP value, pointer or vector, don't do this optimization because a select
01804   // between them is very expensive and unlikely to lead to later
01805   // simplification.  In these cases, we typically end up with "cond ? v1 : v2"
01806   // where v1 and v2 both require constant pool loads, a big loss.
01807   if (GVElType == Type::getInt1Ty(GV->getContext()) ||
01808       GVElType->isFloatingPointTy() ||
01809       GVElType->isPointerTy() || GVElType->isVectorTy())
01810     return false;
01811 
01812   // Walk the use list of the global seeing if all the uses are load or store.
01813   // If there is anything else, bail out.
01814   for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
01815     User *U = *I;
01816     if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
01817       return false;
01818   }
01819 
01820   DEBUG(dbgs() << "   *** SHRINKING TO BOOL: " << *GV);
01821 
01822   // Create the new global, initializing it to false.
01823   GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
01824                                              false,
01825                                              GlobalValue::InternalLinkage,
01826                                         ConstantInt::getFalse(GV->getContext()),
01827                                              GV->getName()+".b",
01828                                              GV->getThreadLocalMode(),
01829                                              GV->getType()->getAddressSpace());
01830   GV->getParent()->getGlobalList().insert(GV, NewGV);
01831 
01832   Constant *InitVal = GV->getInitializer();
01833   assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
01834          "No reason to shrink to bool!");
01835 
01836   // If initialized to zero and storing one into the global, we can use a cast
01837   // instead of a select to synthesize the desired value.
01838   bool IsOneZero = false;
01839   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
01840     IsOneZero = InitVal->isNullValue() && CI->isOne();
01841 
01842   while (!GV->use_empty()) {
01843     Instruction *UI = cast<Instruction>(GV->use_back());
01844     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
01845       // Change the store into a boolean store.
01846       bool StoringOther = SI->getOperand(0) == OtherVal;
01847       // Only do this if we weren't storing a loaded value.
01848       Value *StoreVal;
01849       if (StoringOther || SI->getOperand(0) == InitVal) {
01850         StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
01851                                     StoringOther);
01852       } else {
01853         // Otherwise, we are storing a previously loaded copy.  To do this,
01854         // change the copy from copying the original value to just copying the
01855         // bool.
01856         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
01857 
01858         // If we've already replaced the input, StoredVal will be a cast or
01859         // select instruction.  If not, it will be a load of the original
01860         // global.
01861         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
01862           assert(LI->getOperand(0) == GV && "Not a copy!");
01863           // Insert a new load, to preserve the saved value.
01864           StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
01865                                   LI->getOrdering(), LI->getSynchScope(), LI);
01866         } else {
01867           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
01868                  "This is not a form that we understand!");
01869           StoreVal = StoredVal->getOperand(0);
01870           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
01871         }
01872       }
01873       new StoreInst(StoreVal, NewGV, false, 0,
01874                     SI->getOrdering(), SI->getSynchScope(), SI);
01875     } else {
01876       // Change the load into a load of bool then a select.
01877       LoadInst *LI = cast<LoadInst>(UI);
01878       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
01879                                    LI->getOrdering(), LI->getSynchScope(), LI);
01880       Value *NSI;
01881       if (IsOneZero)
01882         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
01883       else
01884         NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
01885       NSI->takeName(LI);
01886       LI->replaceAllUsesWith(NSI);
01887     }
01888     UI->eraseFromParent();
01889   }
01890 
01891   // Retain the name of the old global variable. People who are debugging their
01892   // programs may expect these variables to be named the same.
01893   NewGV->takeName(GV);
01894   GV->eraseFromParent();
01895   return true;
01896 }
01897 
01898 
01899 /// ProcessGlobal - Analyze the specified global variable and optimize it if
01900 /// possible.  If we make a change, return true.
01901 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
01902                               Module::global_iterator &GVI) {
01903   if (!GV->isDiscardableIfUnused())
01904     return false;
01905 
01906   // Do more involved optimizations if the global is internal.
01907   GV->removeDeadConstantUsers();
01908 
01909   if (GV->use_empty()) {
01910     DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
01911     GV->eraseFromParent();
01912     ++NumDeleted;
01913     return true;
01914   }
01915 
01916   if (!GV->hasLocalLinkage())
01917     return false;
01918 
01919   SmallPtrSet<const PHINode*, 16> PHIUsers;
01920   GlobalStatus GS;
01921 
01922   if (AnalyzeGlobal(GV, GS, PHIUsers))
01923     return false;
01924 
01925   if (!GS.isCompared && !GV->hasUnnamedAddr()) {
01926     GV->setUnnamedAddr(true);
01927     NumUnnamed++;
01928   }
01929 
01930   if (GV->isConstant() || !GV->hasInitializer())
01931     return false;
01932 
01933   return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
01934 }
01935 
01936 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
01937 /// it if possible.  If we make a change, return true.
01938 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
01939                                       Module::global_iterator &GVI,
01940                                 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
01941                                       const GlobalStatus &GS) {
01942   // If this is a first class global and has only one accessing function
01943   // and this function is main (which we know is not recursive we can make
01944   // this global a local variable) we replace the global with a local alloca
01945   // in this function.
01946   //
01947   // NOTE: It doesn't make sense to promote non single-value types since we
01948   // are just replacing static memory to stack memory.
01949   //
01950   // If the global is in different address space, don't bring it to stack.
01951   if (!GS.HasMultipleAccessingFunctions &&
01952       GS.AccessingFunction && !GS.HasNonInstructionUser &&
01953       GV->getType()->getElementType()->isSingleValueType() &&
01954       GS.AccessingFunction->getName() == "main" &&
01955       GS.AccessingFunction->hasExternalLinkage() &&
01956       GV->getType()->getAddressSpace() == 0) {
01957     DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
01958     Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
01959                                                    ->getEntryBlock().begin());
01960     Type *ElemTy = GV->getType()->getElementType();
01961     // FIXME: Pass Global's alignment when globals have alignment
01962     AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
01963     if (!isa<UndefValue>(GV->getInitializer()))
01964       new StoreInst(GV->getInitializer(), Alloca, &FirstI);
01965 
01966     GV->replaceAllUsesWith(Alloca);
01967     GV->eraseFromParent();
01968     ++NumLocalized;
01969     return true;
01970   }
01971 
01972   // If the global is never loaded (but may be stored to), it is dead.
01973   // Delete it now.
01974   if (!GS.isLoaded) {
01975     DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
01976 
01977     bool Changed;
01978     if (isLeakCheckerRoot(GV)) {
01979       // Delete any constant stores to the global.
01980       Changed = CleanupPointerRootUsers(GV, TLI);
01981     } else {
01982       // Delete any stores we can find to the global.  We may not be able to
01983       // make it completely dead though.
01984       Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
01985     }
01986 
01987     // If the global is dead now, delete it.
01988     if (GV->use_empty()) {
01989       GV->eraseFromParent();
01990       ++NumDeleted;
01991       Changed = true;
01992     }
01993     return Changed;
01994 
01995   } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
01996     DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
01997     GV->setConstant(true);
01998 
01999     // Clean up any obviously simplifiable users now.
02000     CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
02001 
02002     // If the global is dead now, just nuke it.
02003     if (GV->use_empty()) {
02004       DEBUG(dbgs() << "   *** Marking constant allowed us to simplify "
02005             << "all users and delete global!\n");
02006       GV->eraseFromParent();
02007       ++NumDeleted;
02008     }
02009 
02010     ++NumMarked;
02011     return true;
02012   } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
02013     if (DataLayout *TD = getAnalysisIfAvailable<DataLayout>())
02014       if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
02015         GVI = FirstNewGV;  // Don't skip the newly produced globals!
02016         return true;
02017       }
02018   } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
02019     // If the initial value for the global was an undef value, and if only
02020     // one other value was stored into it, we can just change the
02021     // initializer to be the stored value, then delete all stores to the
02022     // global.  This allows us to mark it constant.
02023     if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
02024       if (isa<UndefValue>(GV->getInitializer())) {
02025         // Change the initial value here.
02026         GV->setInitializer(SOVConstant);
02027 
02028         // Clean up any obviously simplifiable users now.
02029         CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
02030 
02031         if (GV->use_empty()) {
02032           DEBUG(dbgs() << "   *** Substituting initializer allowed us to "
02033                        << "simplify all users and delete global!\n");
02034           GV->eraseFromParent();
02035           ++NumDeleted;
02036         } else {
02037           GVI = GV;
02038         }
02039         ++NumSubstitute;
02040         return true;
02041       }
02042 
02043     // Try to optimize globals based on the knowledge that only one value
02044     // (besides its initializer) is ever stored to the global.
02045     if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
02046                                  TD, TLI))
02047       return true;
02048 
02049     // Otherwise, if the global was not a boolean, we can shrink it to be a
02050     // boolean.
02051     if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
02052       if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
02053         ++NumShrunkToBool;
02054         return true;
02055       }
02056   }
02057 
02058   return false;
02059 }
02060 
02061 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
02062 /// function, changing them to FastCC.
02063 static void ChangeCalleesToFastCall(Function *F) {
02064   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
02065     if (isa<BlockAddress>(*UI))
02066       continue;
02067     CallSite User(cast<Instruction>(*UI));
02068     User.setCallingConv(CallingConv::Fast);
02069   }
02070 }
02071 
02072 static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
02073   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
02074     unsigned Index = Attrs.getSlotIndex(i);
02075     if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
02076       continue;
02077 
02078     // There can be only one.
02079     return Attrs.removeAttribute(C, Index, Attribute::Nest);
02080   }
02081 
02082   return Attrs;
02083 }
02084 
02085 static void RemoveNestAttribute(Function *F) {
02086   F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
02087   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
02088     if (isa<BlockAddress>(*UI))
02089       continue;
02090     CallSite User(cast<Instruction>(*UI));
02091     User.setAttributes(StripNest(F->getContext(), User.getAttributes()));
02092   }
02093 }
02094 
02095 bool GlobalOpt::OptimizeFunctions(Module &M) {
02096   bool Changed = false;
02097   // Optimize functions.
02098   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
02099     Function *F = FI++;
02100     // Functions without names cannot be referenced outside this module.
02101     if (!F->hasName() && !F->isDeclaration())
02102       F->setLinkage(GlobalValue::InternalLinkage);
02103     F->removeDeadConstantUsers();
02104     if (F->isDefTriviallyDead()) {
02105       F->eraseFromParent();
02106       Changed = true;
02107       ++NumFnDeleted;
02108     } else if (F->hasLocalLinkage()) {
02109       if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
02110           !F->hasAddressTaken()) {
02111         // If this function has C calling conventions, is not a varargs
02112         // function, and is only called directly, promote it to use the Fast
02113         // calling convention.
02114         F->setCallingConv(CallingConv::Fast);
02115         ChangeCalleesToFastCall(F);
02116         ++NumFastCallFns;
02117         Changed = true;
02118       }
02119 
02120       if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
02121           !F->hasAddressTaken()) {
02122         // The function is not used by a trampoline intrinsic, so it is safe
02123         // to remove the 'nest' attribute.
02124         RemoveNestAttribute(F);
02125         ++NumNestRemoved;
02126         Changed = true;
02127       }
02128     }
02129   }
02130   return Changed;
02131 }
02132 
02133 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
02134   bool Changed = false;
02135   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
02136        GVI != E; ) {
02137     GlobalVariable *GV = GVI++;
02138     // Global variables without names cannot be referenced outside this module.
02139     if (!GV->hasName() && !GV->isDeclaration())
02140       GV->setLinkage(GlobalValue::InternalLinkage);
02141     // Simplify the initializer.
02142     if (GV->hasInitializer())
02143       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
02144         Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
02145         if (New && New != CE)
02146           GV->setInitializer(New);
02147       }
02148 
02149     Changed |= ProcessGlobal(GV, GVI);
02150   }
02151   return Changed;
02152 }
02153 
02154 /// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
02155 /// initializers have an init priority of 65535.
02156 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
02157   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
02158   if (GV == 0) return 0;
02159 
02160   // Verify that the initializer is simple enough for us to handle. We are
02161   // only allowed to optimize the initializer if it is unique.
02162   if (!GV->hasUniqueInitializer()) return 0;
02163 
02164   if (isa<ConstantAggregateZero>(GV->getInitializer()))
02165     return GV;
02166   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
02167 
02168   for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
02169     if (isa<ConstantAggregateZero>(*i))
02170       continue;
02171     ConstantStruct *CS = cast<ConstantStruct>(*i);
02172     if (isa<ConstantPointerNull>(CS->getOperand(1)))
02173       continue;
02174 
02175     // Must have a function or null ptr.
02176     if (!isa<Function>(CS->getOperand(1)))
02177       return 0;
02178 
02179     // Init priority must be standard.
02180     ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
02181     if (CI->getZExtValue() != 65535)
02182       return 0;
02183   }
02184 
02185   return GV;
02186 }
02187 
02188 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
02189 /// return a list of the functions and null terminator as a vector.
02190 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
02191   if (GV->getInitializer()->isNullValue())
02192     return std::vector<Function*>();
02193   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
02194   std::vector<Function*> Result;
02195   Result.reserve(CA->getNumOperands());
02196   for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
02197     ConstantStruct *CS = cast<ConstantStruct>(*i);
02198     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
02199   }
02200   return Result;
02201 }
02202 
02203 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
02204 /// specified array, returning the new global to use.
02205 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
02206                                           const std::vector<Function*> &Ctors) {
02207   // If we made a change, reassemble the initializer list.
02208   Constant *CSVals[2];
02209   CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
02210   CSVals[1] = 0;
02211 
02212   StructType *StructTy =
02213     cast <StructType>(
02214     cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
02215 
02216   // Create the new init list.
02217   std::vector<Constant*> CAList;
02218   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
02219     if (Ctors[i]) {
02220       CSVals[1] = Ctors[i];
02221     } else {
02222       Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
02223                                           false);
02224       PointerType *PFTy = PointerType::getUnqual(FTy);
02225       CSVals[1] = Constant::getNullValue(PFTy);
02226       CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
02227                                    0x7fffffff);
02228     }
02229     CAList.push_back(ConstantStruct::get(StructTy, CSVals));
02230   }
02231 
02232   // Create the array initializer.
02233   Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
02234                                                    CAList.size()), CAList);
02235 
02236   // If we didn't change the number of elements, don't create a new GV.
02237   if (CA->getType() == GCL->getInitializer()->getType()) {
02238     GCL->setInitializer(CA);
02239     return GCL;
02240   }
02241 
02242   // Create the new global and insert it next to the existing list.
02243   GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
02244                                            GCL->getLinkage(), CA, "",
02245                                            GCL->getThreadLocalMode());
02246   GCL->getParent()->getGlobalList().insert(GCL, NGV);
02247   NGV->takeName(GCL);
02248 
02249   // Nuke the old list, replacing any uses with the new one.
02250   if (!GCL->use_empty()) {
02251     Constant *V = NGV;
02252     if (V->getType() != GCL->getType())
02253       V = ConstantExpr::getBitCast(V, GCL->getType());
02254     GCL->replaceAllUsesWith(V);
02255   }
02256   GCL->eraseFromParent();
02257 
02258   if (Ctors.size())
02259     return NGV;
02260   else
02261     return 0;
02262 }
02263 
02264 
02265 static inline bool
02266 isSimpleEnoughValueToCommit(Constant *C,
02267                             SmallPtrSet<Constant*, 8> &SimpleConstants,
02268                             const DataLayout *TD);
02269 
02270 
02271 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
02272 /// handled by the code generator.  We don't want to generate something like:
02273 ///   void *X = &X/42;
02274 /// because the code generator doesn't have a relocation that can handle that.
02275 ///
02276 /// This function should be called if C was not found (but just got inserted)
02277 /// in SimpleConstants to avoid having to rescan the same constants all the
02278 /// time.
02279 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
02280                                    SmallPtrSet<Constant*, 8> &SimpleConstants,
02281                                    const DataLayout *TD) {
02282   // Simple integer, undef, constant aggregate zero, global addresses, etc are
02283   // all supported.
02284   if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
02285       isa<GlobalValue>(C))
02286     return true;
02287 
02288   // Aggregate values are safe if all their elements are.
02289   if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
02290       isa<ConstantVector>(C)) {
02291     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
02292       Constant *Op = cast<Constant>(C->getOperand(i));
02293       if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
02294         return false;
02295     }
02296     return true;
02297   }
02298 
02299   // We don't know exactly what relocations are allowed in constant expressions,
02300   // so we allow &global+constantoffset, which is safe and uniformly supported
02301   // across targets.
02302   ConstantExpr *CE = cast<ConstantExpr>(C);
02303   switch (CE->getOpcode()) {
02304   case Instruction::BitCast:
02305     // Bitcast is fine if the casted value is fine.
02306     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
02307 
02308   case Instruction::IntToPtr:
02309   case Instruction::PtrToInt:
02310     // int <=> ptr is fine if the int type is the same size as the
02311     // pointer type.
02312     if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
02313                TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
02314       return false;
02315     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
02316 
02317   // GEP is fine if it is simple + constant offset.
02318   case Instruction::GetElementPtr:
02319     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
02320       if (!isa<ConstantInt>(CE->getOperand(i)))
02321         return false;
02322     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
02323 
02324   case Instruction::Add:
02325     // We allow simple+cst.
02326     if (!isa<ConstantInt>(CE->getOperand(1)))
02327       return false;
02328     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
02329   }
02330   return false;
02331 }
02332 
02333 static inline bool
02334 isSimpleEnoughValueToCommit(Constant *C,
02335                             SmallPtrSet<Constant*, 8> &SimpleConstants,
02336                             const DataLayout *TD) {
02337   // If we already checked this constant, we win.
02338   if (!SimpleConstants.insert(C)) return true;
02339   // Check the constant.
02340   return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
02341 }
02342 
02343 
02344 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
02345 /// enough for us to understand.  In particular, if it is a cast to anything
02346 /// other than from one pointer type to another pointer type, we punt.
02347 /// We basically just support direct accesses to globals and GEP's of
02348 /// globals.  This should be kept up to date with CommitValueTo.
02349 static bool isSimpleEnoughPointerToCommit(Constant *C) {
02350   // Conservatively, avoid aggregate types. This is because we don't
02351   // want to worry about them partially overlapping other stores.
02352   if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
02353     return false;
02354 
02355   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
02356     // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
02357     // external globals.
02358     return GV->hasUniqueInitializer();
02359 
02360   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
02361     // Handle a constantexpr gep.
02362     if (CE->getOpcode() == Instruction::GetElementPtr &&
02363         isa<GlobalVariable>(CE->getOperand(0)) &&
02364         cast<GEPOperator>(CE)->isInBounds()) {
02365       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02366       // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
02367       // external globals.
02368       if (!GV->hasUniqueInitializer())
02369         return false;
02370 
02371       // The first index must be zero.
02372       ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
02373       if (!CI || !CI->isZero()) return false;
02374 
02375       // The remaining indices must be compile-time known integers within the
02376       // notional bounds of the corresponding static array types.
02377       if (!CE->isGEPWithNoNotionalOverIndexing())
02378         return false;
02379 
02380       return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
02381 
02382     // A constantexpr bitcast from a pointer to another pointer is a no-op,
02383     // and we know how to evaluate it by moving the bitcast from the pointer
02384     // operand to the value operand.
02385     } else if (CE->getOpcode() == Instruction::BitCast &&
02386                isa<GlobalVariable>(CE->getOperand(0))) {
02387       // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
02388       // external globals.
02389       return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
02390     }
02391   }
02392 
02393   return false;
02394 }
02395 
02396 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
02397 /// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
02398 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
02399 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
02400                                    ConstantExpr *Addr, unsigned OpNo) {
02401   // Base case of the recursion.
02402   if (OpNo == Addr->getNumOperands()) {
02403     assert(Val->getType() == Init->getType() && "Type mismatch!");
02404     return Val;
02405   }
02406 
02407   SmallVector<Constant*, 32> Elts;
02408   if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
02409     // Break up the constant into its elements.
02410     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
02411       Elts.push_back(Init->getAggregateElement(i));
02412 
02413     // Replace the element that we are supposed to.
02414     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
02415     unsigned Idx = CU->getZExtValue();
02416     assert(Idx < STy->getNumElements() && "Struct index out of range!");
02417     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
02418 
02419     // Return the modified struct.
02420     return ConstantStruct::get(STy, Elts);
02421   }
02422 
02423   ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
02424   SequentialType *InitTy = cast<SequentialType>(Init->getType());
02425 
02426   uint64_t NumElts;
02427   if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
02428     NumElts = ATy->getNumElements();
02429   else
02430     NumElts = InitTy->getVectorNumElements();
02431 
02432   // Break up the array into elements.
02433   for (uint64_t i = 0, e = NumElts; i != e; ++i)
02434     Elts.push_back(Init->getAggregateElement(i));
02435 
02436   assert(CI->getZExtValue() < NumElts);
02437   Elts[CI->getZExtValue()] =
02438     EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
02439 
02440   if (Init->getType()->isArrayTy())
02441     return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
02442   return ConstantVector::get(Elts);
02443 }
02444 
02445 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
02446 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
02447 static void CommitValueTo(Constant *Val, Constant *Addr) {
02448   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
02449     assert(GV->hasInitializer());
02450     GV->setInitializer(Val);
02451     return;
02452   }
02453 
02454   ConstantExpr *CE = cast<ConstantExpr>(Addr);
02455   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02456   GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
02457 }
02458 
02459 namespace {
02460 
02461 /// Evaluator - This class evaluates LLVM IR, producing the Constant
02462 /// representing each SSA instruction.  Changes to global variables are stored
02463 /// in a mapping that can be iterated over after the evaluation is complete.
02464 /// Once an evaluation call fails, the evaluation object should not be reused.
02465 class Evaluator {
02466 public:
02467   Evaluator(const DataLayout *TD, const TargetLibraryInfo *TLI)
02468     : TD(TD), TLI(TLI) {
02469     ValueStack.push_back(new DenseMap<Value*, Constant*>);
02470   }
02471 
02472   ~Evaluator() {
02473     DeleteContainerPointers(ValueStack);
02474     while (!AllocaTmps.empty()) {
02475       GlobalVariable *Tmp = AllocaTmps.back();
02476       AllocaTmps.pop_back();
02477 
02478       // If there are still users of the alloca, the program is doing something
02479       // silly, e.g. storing the address of the alloca somewhere and using it
02480       // later.  Since this is undefined, we'll just make it be null.
02481       if (!Tmp->use_empty())
02482         Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
02483       delete Tmp;
02484     }
02485   }
02486 
02487   /// EvaluateFunction - Evaluate a call to function F, returning true if
02488   /// successful, false if we can't evaluate it.  ActualArgs contains the formal
02489   /// arguments for the function.
02490   bool EvaluateFunction(Function *F, Constant *&RetVal,
02491                         const SmallVectorImpl<Constant*> &ActualArgs);
02492 
02493   /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
02494   /// successful, false if we can't evaluate it.  NewBB returns the next BB that
02495   /// control flows into, or null upon return.
02496   bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
02497 
02498   Constant *getVal(Value *V) {
02499     if (Constant *CV = dyn_cast<Constant>(V)) return CV;
02500     Constant *R = ValueStack.back()->lookup(V);
02501     assert(R && "Reference to an uncomputed value!");
02502     return R;
02503   }
02504 
02505   void setVal(Value *V, Constant *C) {
02506     ValueStack.back()->operator[](V) = C;
02507   }
02508 
02509   const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
02510     return MutatedMemory;
02511   }
02512 
02513   const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
02514     return Invariants;
02515   }
02516 
02517 private:
02518   Constant *ComputeLoadResult(Constant *P);
02519 
02520   /// ValueStack - As we compute SSA register values, we store their contents
02521   /// here. The back of the vector contains the current function and the stack
02522   /// contains the values in the calling frames.
02523   SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
02524 
02525   /// CallStack - This is used to detect recursion.  In pathological situations
02526   /// we could hit exponential behavior, but at least there is nothing
02527   /// unbounded.
02528   SmallVector<Function*, 4> CallStack;
02529 
02530   /// MutatedMemory - For each store we execute, we update this map.  Loads
02531   /// check this to get the most up-to-date value.  If evaluation is successful,
02532   /// this state is committed to the process.
02533   DenseMap<Constant*, Constant*> MutatedMemory;
02534 
02535   /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
02536   /// to represent its body.  This vector is needed so we can delete the
02537   /// temporary globals when we are done.
02538   SmallVector<GlobalVariable*, 32> AllocaTmps;
02539 
02540   /// Invariants - These global variables have been marked invariant by the
02541   /// static constructor.
02542   SmallPtrSet<GlobalVariable*, 8> Invariants;
02543 
02544   /// SimpleConstants - These are constants we have checked and know to be
02545   /// simple enough to live in a static initializer of a global.
02546   SmallPtrSet<Constant*, 8> SimpleConstants;
02547 
02548   const DataLayout *TD;
02549   const TargetLibraryInfo *TLI;
02550 };
02551 
02552 }  // anonymous namespace
02553 
02554 /// ComputeLoadResult - Return the value that would be computed by a load from
02555 /// P after the stores reflected by 'memory' have been performed.  If we can't
02556 /// decide, return null.
02557 Constant *Evaluator::ComputeLoadResult(Constant *P) {
02558   // If this memory location has been recently stored, use the stored value: it
02559   // is the most up-to-date.
02560   DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
02561   if (I != MutatedMemory.end()) return I->second;
02562 
02563   // Access it.
02564   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
02565     if (GV->hasDefinitiveInitializer())
02566       return GV->getInitializer();
02567     return 0;
02568   }
02569 
02570   // Handle a constantexpr getelementptr.
02571   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
02572     if (CE->getOpcode() == Instruction::GetElementPtr &&
02573         isa<GlobalVariable>(CE->getOperand(0))) {
02574       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02575       if (GV->hasDefinitiveInitializer())
02576         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
02577     }
02578 
02579   return 0;  // don't know how to evaluate.
02580 }
02581 
02582 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
02583 /// successful, false if we can't evaluate it.  NewBB returns the next BB that
02584 /// control flows into, or null upon return.
02585 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
02586                               BasicBlock *&NextBB) {
02587   // This is the main evaluation loop.
02588   while (1) {
02589     Constant *InstResult = 0;
02590 
02591     DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
02592 
02593     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
02594       if (!SI->isSimple()) {
02595         DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
02596         return false;  // no volatile/atomic accesses.
02597       }
02598       Constant *Ptr = getVal(SI->getOperand(1));
02599       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
02600         DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
02601         Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
02602         DEBUG(dbgs() << "; To: " << *Ptr << "\n");
02603       }
02604       if (!isSimpleEnoughPointerToCommit(Ptr)) {
02605         // If this is too complex for us to commit, reject it.
02606         DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
02607         return false;
02608       }
02609 
02610       Constant *Val = getVal(SI->getOperand(0));
02611 
02612       // If this might be too difficult for the backend to handle (e.g. the addr
02613       // of one global variable divided by another) then we can't commit it.
02614       if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) {
02615         DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
02616               << "\n");
02617         return false;
02618       }
02619 
02620       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
02621         if (CE->getOpcode() == Instruction::BitCast) {
02622           DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
02623           // If we're evaluating a store through a bitcast, then we need
02624           // to pull the bitcast off the pointer type and push it onto the
02625           // stored value.
02626           Ptr = CE->getOperand(0);
02627 
02628           Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
02629 
02630           // In order to push the bitcast onto the stored value, a bitcast
02631           // from NewTy to Val's type must be legal.  If it's not, we can try
02632           // introspecting NewTy to find a legal conversion.
02633           while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
02634             // If NewTy is a struct, we can convert the pointer to the struct
02635             // into a pointer to its first member.
02636             // FIXME: This could be extended to support arrays as well.
02637             if (StructType *STy = dyn_cast<StructType>(NewTy)) {
02638               NewTy = STy->getTypeAtIndex(0U);
02639 
02640               IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
02641               Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
02642               Constant * const IdxList[] = {IdxZero, IdxZero};
02643 
02644               Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
02645               if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
02646                 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
02647 
02648             // If we can't improve the situation by introspecting NewTy,
02649             // we have to give up.
02650             } else {
02651               DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
02652                     "evaluate.\n");
02653               return false;
02654             }
02655           }
02656 
02657           // If we found compatible types, go ahead and push the bitcast
02658           // onto the stored value.
02659           Val = ConstantExpr::getBitCast(Val, NewTy);
02660 
02661           DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
02662         }
02663       }
02664 
02665       MutatedMemory[Ptr] = Val;
02666     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
02667       InstResult = ConstantExpr::get(BO->getOpcode(),
02668                                      getVal(BO->getOperand(0)),
02669                                      getVal(BO->getOperand(1)));
02670       DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
02671             << "\n");
02672     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
02673       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
02674                                             getVal(CI->getOperand(0)),
02675                                             getVal(CI->getOperand(1)));
02676       DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
02677             << "\n");
02678     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
02679       InstResult = ConstantExpr::getCast(CI->getOpcode(),
02680                                          getVal(CI->getOperand(0)),
02681                                          CI->getType());
02682       DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
02683             << "\n");
02684     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
02685       InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
02686                                            getVal(SI->getOperand(1)),
02687                                            getVal(SI->getOperand(2)));
02688       DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
02689             << "\n");
02690     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
02691       Constant *P = getVal(GEP->getOperand(0));
02692       SmallVector<Constant*, 8> GEPOps;
02693       for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
02694            i != e; ++i)
02695         GEPOps.push_back(getVal(*i));
02696       InstResult =
02697         ConstantExpr::getGetElementPtr(P, GEPOps,
02698                                        cast<GEPOperator>(GEP)->isInBounds());
02699       DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
02700             << "\n");
02701     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
02702 
02703       if (!LI->isSimple()) {
02704         DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
02705         return false;  // no volatile/atomic accesses.
02706       }
02707 
02708       Constant *Ptr = getVal(LI->getOperand(0));
02709       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
02710         Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
02711         DEBUG(dbgs() << "Found a constant pointer expression, constant "
02712               "folding: " << *Ptr << "\n");
02713       }
02714       InstResult = ComputeLoadResult(Ptr);
02715       if (InstResult == 0) {
02716         DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
02717               "\n");
02718         return false; // Could not evaluate load.
02719       }
02720 
02721       DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
02722     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
02723       if (AI->isArrayAllocation()) {
02724         DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
02725         return false;  // Cannot handle array allocs.
02726       }
02727       Type *Ty = AI->getType()->getElementType();
02728       AllocaTmps.push_back(new GlobalVariable(Ty, false,
02729                                               GlobalValue::InternalLinkage,
02730                                               UndefValue::get(Ty),
02731                                               AI->getName()));
02732       InstResult = AllocaTmps.back();
02733       DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
02734     } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
02735       CallSite CS(CurInst);
02736 
02737       // Debug info can safely be ignored here.
02738       if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
02739         DEBUG(dbgs() << "Ignoring debug info.\n");
02740         ++CurInst;
02741         continue;
02742       }
02743 
02744       // Cannot handle inline asm.
02745       if (isa<InlineAsm>(CS.getCalledValue())) {
02746         DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
02747         return false;
02748       }
02749 
02750       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
02751         if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
02752           if (MSI->isVolatile()) {
02753             DEBUG(dbgs() << "Can not optimize a volatile memset " <<
02754                   "intrinsic.\n");
02755             return false;
02756           }
02757           Constant *Ptr = getVal(MSI->getDest());
02758           Constant *Val = getVal(MSI->getValue());
02759           Constant *DestVal = ComputeLoadResult(getVal(Ptr));
02760           if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
02761             // This memset is a no-op.
02762             DEBUG(dbgs() << "Ignoring no-op memset.\n");
02763             ++CurInst;
02764             continue;
02765           }
02766         }
02767 
02768         if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
02769             II->getIntrinsicID() == Intrinsic::lifetime_end) {
02770           DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
02771           ++CurInst;
02772           continue;
02773         }
02774 
02775         if (II->getIntrinsicID() == Intrinsic::invariant_start) {
02776           // We don't insert an entry into Values, as it doesn't have a
02777           // meaningful return value.
02778           if (!II->use_empty()) {
02779             DEBUG(dbgs() << "Found unused invariant_start. Cant evaluate.\n");
02780             return false;
02781           }
02782           ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
02783           Value *PtrArg = getVal(II->getArgOperand(1));
02784           Value *Ptr = PtrArg->stripPointerCasts();
02785           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
02786             Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
02787             if (!Size->isAllOnesValue() &&
02788                 Size->getValue().getLimitedValue() >=
02789                 TD->getTypeStoreSize(ElemTy)) {
02790               Invariants.insert(GV);
02791               DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
02792                     << "\n");
02793             } else {
02794               DEBUG(dbgs() << "Found a global var, but can not treat it as an "
02795                     "invariant.\n");
02796             }
02797           }
02798           // Continue even if we do nothing.
02799           ++CurInst;
02800           continue;
02801         }
02802 
02803         DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
02804         return false;
02805       }
02806 
02807       // Resolve function pointers.
02808       Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
02809       if (!Callee || Callee->mayBeOverridden()) {
02810         DEBUG(dbgs() << "Can not resolve function pointer.\n");
02811         return false;  // Cannot resolve.
02812       }
02813 
02814       SmallVector<Constant*, 8> Formals;
02815       for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
02816         Formals.push_back(getVal(*i));
02817 
02818       if (Callee->isDeclaration()) {
02819         // If this is a function we can constant fold, do it.
02820         if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
02821           InstResult = C;
02822           DEBUG(dbgs() << "Constant folded function call. Result: " <<
02823                 *InstResult << "\n");
02824         } else {
02825           DEBUG(dbgs() << "Can not constant fold function call.\n");
02826           return false;
02827         }
02828       } else {
02829         if (Callee->getFunctionType()->isVarArg()) {
02830           DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
02831           return false;
02832         }
02833 
02834         Constant *RetVal = 0;
02835         // Execute the call, if successful, use the return value.
02836         ValueStack.push_back(new DenseMap<Value*, Constant*>);
02837         if (!EvaluateFunction(Callee, RetVal, Formals)) {
02838           DEBUG(dbgs() << "Failed to evaluate function.\n");
02839           return false;
02840         }
02841         delete ValueStack.pop_back_val();
02842         InstResult = RetVal;
02843 
02844         if (InstResult != NULL) {
02845           DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
02846                 InstResult << "\n\n");
02847         } else {
02848           DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
02849         }
02850       }
02851     } else if (isa<TerminatorInst>(CurInst)) {
02852       DEBUG(dbgs() << "Found a terminator instruction.\n");
02853 
02854       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
02855         if (BI->isUnconditional()) {
02856           NextBB = BI->getSuccessor(0);
02857         } else {
02858           ConstantInt *Cond =
02859             dyn_cast<ConstantInt>(getVal(BI->getCondition()));
02860           if (!Cond) return false;  // Cannot determine.
02861 
02862           NextBB = BI->getSuccessor(!Cond->getZExtValue());
02863         }
02864       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
02865         ConstantInt *Val =
02866           dyn_cast<ConstantInt>(getVal(SI->getCondition()));
02867         if (!Val) return false;  // Cannot determine.
02868         NextBB = SI->findCaseValue(Val).getCaseSuccessor();
02869       } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
02870         Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
02871         if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
02872           NextBB = BA->getBasicBlock();
02873         else
02874           return false;  // Cannot determine.
02875       } else if (isa<ReturnInst>(CurInst)) {
02876         NextBB = 0;
02877       } else {
02878         // invoke, unwind, resume, unreachable.
02879         DEBUG(dbgs() << "Can not handle terminator.");
02880         return false;  // Cannot handle this terminator.
02881       }
02882 
02883       // We succeeded at evaluating this block!
02884       DEBUG(dbgs() << "Successfully evaluated block.\n");
02885       return true;
02886     } else {
02887       // Did not know how to evaluate this!
02888       DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
02889             "\n");
02890       return false;
02891     }
02892 
02893     if (!CurInst->use_empty()) {
02894       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
02895         InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
02896 
02897       setVal(CurInst, InstResult);
02898     }
02899 
02900     // If we just processed an invoke, we finished evaluating the block.
02901     if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
02902       NextBB = II->getNormalDest();
02903       DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
02904       return true;
02905     }
02906 
02907     // Advance program counter.
02908     ++CurInst;
02909   }
02910 }
02911 
02912 /// EvaluateFunction - Evaluate a call to function F, returning true if
02913 /// successful, false if we can't evaluate it.  ActualArgs contains the formal
02914 /// arguments for the function.
02915 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
02916                                  const SmallVectorImpl<Constant*> &ActualArgs) {
02917   // Check to see if this function is already executing (recursion).  If so,
02918   // bail out.  TODO: we might want to accept limited recursion.
02919   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
02920     return false;
02921 
02922   CallStack.push_back(F);
02923 
02924   // Initialize arguments to the incoming values specified.
02925   unsigned ArgNo = 0;
02926   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
02927        ++AI, ++ArgNo)
02928     setVal(AI, ActualArgs[ArgNo]);
02929 
02930   // ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
02931   // we can only evaluate any one basic block at most once.  This set keeps
02932   // track of what we have executed so we can detect recursive cases etc.
02933   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
02934 
02935   // CurBB - The current basic block we're evaluating.
02936   BasicBlock *CurBB = F->begin();
02937 
02938   BasicBlock::iterator CurInst = CurBB->begin();
02939 
02940   while (1) {
02941     BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
02942     DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
02943 
02944     if (!EvaluateBlock(CurInst, NextBB))
02945       return false;
02946 
02947     if (NextBB == 0) {
02948       // Successfully running until there's no next block means that we found
02949       // the return.  Fill it the return value and pop the call stack.
02950       ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
02951       if (RI->getNumOperands())
02952         RetVal = getVal(RI->getOperand(0));
02953       CallStack.pop_back();
02954       return true;
02955     }
02956 
02957     // Okay, we succeeded in evaluating this control flow.  See if we have
02958     // executed the new block before.  If so, we have a looping function,
02959     // which we cannot evaluate in reasonable time.
02960     if (!ExecutedBlocks.insert(NextBB))
02961       return false;  // looped!
02962 
02963     // Okay, we have never been in this block before.  Check to see if there
02964     // are any PHI nodes.  If so, evaluate them with information about where
02965     // we came from.
02966     PHINode *PN = 0;
02967     for (CurInst = NextBB->begin();
02968          (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
02969       setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
02970 
02971     // Advance to the next block.
02972     CurBB = NextBB;
02973   }
02974 }
02975 
02976 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
02977 /// we can.  Return true if we can, false otherwise.
02978 static bool EvaluateStaticConstructor(Function *F, const DataLayout *TD,
02979                                       const TargetLibraryInfo *TLI) {
02980   // Call the function.
02981   Evaluator Eval(TD, TLI);
02982   Constant *RetValDummy;
02983   bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
02984                                            SmallVector<Constant*, 0>());
02985 
02986   if (EvalSuccess) {
02987     // We succeeded at evaluation: commit the result.
02988     DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
02989           << F->getName() << "' to " << Eval.getMutatedMemory().size()
02990           << " stores.\n");
02991     for (DenseMap<Constant*, Constant*>::const_iterator I =
02992            Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
02993          I != E; ++I)
02994       CommitValueTo(I->second, I->first);
02995     for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
02996            Eval.getInvariants().begin(), E = Eval.getInvariants().end();
02997          I != E; ++I)
02998       (*I)->setConstant(true);
02999   }
03000 
03001   return EvalSuccess;
03002 }
03003 
03004 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
03005 /// Return true if anything changed.
03006 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
03007   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
03008   bool MadeChange = false;
03009   if (Ctors.empty()) return false;
03010 
03011   // Loop over global ctors, optimizing them when we can.
03012   for (unsigned i = 0; i != Ctors.size(); ++i) {
03013     Function *F = Ctors[i];
03014     // Found a null terminator in the middle of the list, prune off the rest of
03015     // the list.
03016     if (F == 0) {
03017       if (i != Ctors.size()-1) {
03018         Ctors.resize(i+1);
03019         MadeChange = true;
03020       }
03021       break;
03022     }
03023     DEBUG(dbgs() << "Optimizing Global Constructor: " << *F << "\n");
03024 
03025     // We cannot simplify external ctor functions.
03026     if (F->empty()) continue;
03027 
03028     // If we can evaluate the ctor at compile time, do.
03029     if (EvaluateStaticConstructor(F, TD, TLI)) {
03030       Ctors.erase(Ctors.begin()+i);
03031       MadeChange = true;
03032       --i;
03033       ++NumCtorsEvaluated;
03034       continue;
03035     }
03036   }
03037 
03038   if (!MadeChange) return false;
03039 
03040   GCL = InstallGlobalCtors(GCL, Ctors);
03041   return true;
03042 }
03043 
03044 static Value::use_iterator getFirst(Value *V, SmallPtrSet<Use*, 8> &Tried) {
03045   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
03046     Use *U = &I.getUse();
03047     if (Tried.count(U))
03048       continue;
03049 
03050     User *Usr = *I;
03051     GlobalVariable *GV = dyn_cast<GlobalVariable>(Usr);
03052     if (!GV || !GV->hasName()) {
03053       Tried.insert(U);
03054       return I;
03055     }
03056 
03057     StringRef Name = GV->getName();
03058     if (Name != "llvm.used" && Name != "llvm.compiler_used") {
03059       Tried.insert(U);
03060       return I;
03061     }
03062   }
03063   return V->use_end();
03064 }
03065 
03066 static bool replaceAllNonLLVMUsedUsesWith(Constant *Old, Constant *New);
03067 
03068 static bool replaceUsesOfWithOnConstant(ConstantArray *CA, Value *From,
03069                                         Value *ToV, Use *U) {
03070   Constant *To = cast<Constant>(ToV);
03071 
03072   SmallVector<Constant*, 8> NewOps;
03073   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
03074     Constant *Op = CA->getOperand(i);
03075     NewOps.push_back(Op == From ? To : Op);
03076   }
03077 
03078   Constant *Replacement = ConstantArray::get(CA->getType(), NewOps);
03079   assert(Replacement != CA && "CA didn't contain From!");
03080 
03081   bool Ret = replaceAllNonLLVMUsedUsesWith(CA, Replacement);
03082   if (Replacement->use_empty())
03083     Replacement->destroyConstant();
03084   if (CA->use_empty())
03085     CA->destroyConstant();
03086   return Ret;
03087 }
03088 
03089 static bool replaceUsesOfWithOnConstant(ConstantExpr *CE, Value *From,
03090                                         Value *ToV, Use *U) {
03091   Constant *To = cast<Constant>(ToV);
03092   SmallVector<Constant*, 8> NewOps;
03093   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
03094     Constant *Op = CE->getOperand(i);
03095     NewOps.push_back(Op == From ? To : Op);
03096   }
03097 
03098   Constant *Replacement = CE->getWithOperands(NewOps);
03099   assert(Replacement != CE && "CE didn't contain From!");
03100 
03101   bool Ret = replaceAllNonLLVMUsedUsesWith(CE, Replacement);
03102   if (Replacement->use_empty())
03103     Replacement->destroyConstant();
03104   if (CE->use_empty())
03105     CE->destroyConstant();
03106   return Ret;
03107 }
03108 
03109 static bool replaceUsesOfWithOnConstant(Constant *C, Value *From, Value *To,
03110                                         Use *U) {
03111   if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
03112     return replaceUsesOfWithOnConstant(CA, From, To, U);
03113   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
03114     return replaceUsesOfWithOnConstant(CE, From, To, U);
03115   C->replaceUsesOfWithOnConstant(From, To, U);
03116   return true;
03117 }
03118 
03119 static bool replaceAllNonLLVMUsedUsesWith(Constant *Old, Constant *New) {
03120   SmallPtrSet<Use*, 8> Tried;
03121   bool Ret = false;
03122   for (;;) {
03123     Value::use_iterator I = getFirst(Old, Tried);
03124     if (I == Old->use_end())
03125       break;
03126     Use &U = I.getUse();
03127 
03128     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
03129     // constant because they are uniqued.
03130     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
03131       if (!isa<GlobalValue>(C)) {
03132         Ret |= replaceUsesOfWithOnConstant(C, Old, New, &U);
03133         continue;
03134       }
03135     }
03136 
03137     U.set(New);
03138     Ret = true;
03139   }
03140   return Ret;
03141 }
03142 
03143 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
03144   bool Changed = false;
03145 
03146   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
03147        I != E;) {
03148     Module::alias_iterator J = I++;
03149     // Aliases without names cannot be referenced outside this module.
03150     if (!J->hasName() && !J->isDeclaration())
03151       J->setLinkage(GlobalValue::InternalLinkage);
03152     // If the aliasee may change at link time, nothing can be done - bail out.
03153     if (J->mayBeOverridden())
03154       continue;
03155 
03156     Constant *Aliasee = J->getAliasee();
03157     GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
03158     Target->removeDeadConstantUsers();
03159     bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
03160 
03161     // Make all users of the alias use the aliasee instead.
03162     if (replaceAllNonLLVMUsedUsesWith(J, Aliasee)) {
03163       ++NumAliasesResolved;
03164       Changed = true;
03165     }
03166     if (!J->use_empty())
03167       continue;
03168 
03169     // If the alias is externally visible, we may still be able to simplify it.
03170     if (!J->hasLocalLinkage()) {
03171       // If the aliasee has internal linkage, give it the name and linkage
03172       // of the alias, and delete the alias.  This turns:
03173       //   define internal ... @f(...)
03174       //   @a = alias ... @f
03175       // into:
03176       //   define ... @a(...)
03177       if (!Target->hasLocalLinkage())
03178         continue;
03179 
03180       // Do not perform the transform if multiple aliases potentially target the
03181       // aliasee. This check also ensures that it is safe to replace the section
03182       // and other attributes of the aliasee with those of the alias.
03183       if (!hasOneUse)
03184         continue;
03185 
03186       // Give the aliasee the name, linkage and other attributes of the alias.
03187       Target->takeName(J);
03188       Target->setLinkage(J->getLinkage());
03189       Target->GlobalValue::copyAttributesFrom(J);
03190     }
03191 
03192     // Delete the alias.
03193     M.getAliasList().erase(J);
03194     ++NumAliasesRemoved;
03195     Changed = true;
03196   }
03197 
03198   return Changed;
03199 }
03200 
03201 static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
03202   if (!TLI->has(LibFunc::cxa_atexit))
03203     return 0;
03204 
03205   Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
03206 
03207   if (!Fn)
03208     return 0;
03209 
03210   FunctionType *FTy = Fn->getFunctionType();
03211 
03212   // Checking that the function has the right return type, the right number of
03213   // parameters and that they all have pointer types should be enough.
03214   if (!FTy->getReturnType()->isIntegerTy() ||
03215       FTy->getNumParams() != 3 ||
03216       !FTy->getParamType(0)->isPointerTy() ||
03217       !FTy->getParamType(1)->isPointerTy() ||
03218       !FTy->getParamType(2)->isPointerTy())
03219     return 0;
03220 
03221   return Fn;
03222 }
03223 
03224 /// cxxDtorIsEmpty - Returns whether the given function is an empty C++
03225 /// destructor and can therefore be eliminated.
03226 /// Note that we assume that other optimization passes have already simplified
03227 /// the code so we only look for a function with a single basic block, where
03228 /// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
03229 /// other side-effect free instructions.
03230 static bool cxxDtorIsEmpty(const Function &Fn,
03231                            SmallPtrSet<const Function *, 8> &CalledFunctions) {
03232   // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
03233   // nounwind, but that doesn't seem worth doing.
03234   if (Fn.isDeclaration())
03235     return false;
03236 
03237   if (++Fn.begin() != Fn.end())
03238     return false;
03239 
03240   const BasicBlock &EntryBlock = Fn.getEntryBlock();
03241   for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
03242        I != E; ++I) {
03243     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
03244       // Ignore debug intrinsics.
03245       if (isa<DbgInfoIntrinsic>(CI))
03246         continue;
03247 
03248       const Function *CalledFn = CI->getCalledFunction();
03249 
03250       if (!CalledFn)
03251         return false;
03252 
03253       SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
03254 
03255       // Don't treat recursive functions as empty.
03256       if (!NewCalledFunctions.insert(CalledFn))
03257         return false;
03258 
03259       if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
03260         return false;
03261     } else if (isa<ReturnInst>(*I))
03262       return true; // We're done.
03263     else if (I->mayHaveSideEffects())
03264       return false; // Destructor with side effects, bail.
03265   }
03266 
03267   return false;
03268 }
03269 
03270 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
03271   /// Itanium C++ ABI p3.3.5:
03272   ///
03273   ///   After constructing a global (or local static) object, that will require
03274   ///   destruction on exit, a termination function is registered as follows:
03275   ///
03276   ///   extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
03277   ///
03278   ///   This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
03279   ///   call f(p) when DSO d is unloaded, before all such termination calls
03280   ///   registered before this one. It returns zero if registration is
03281   ///   successful, nonzero on failure.
03282 
03283   // This pass will look for calls to __cxa_atexit where the function is trivial
03284   // and remove them.
03285   bool Changed = false;
03286 
03287   for (Function::use_iterator I = CXAAtExitFn->use_begin(),
03288        E = CXAAtExitFn->use_end(); I != E;) {
03289     // We're only interested in calls. Theoretically, we could handle invoke
03290     // instructions as well, but neither llvm-gcc nor clang generate invokes
03291     // to __cxa_atexit.
03292     CallInst *CI = dyn_cast<CallInst>(*I++);
03293     if (!CI)
03294       continue;
03295 
03296     Function *DtorFn =
03297       dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
03298     if (!DtorFn)
03299       continue;
03300 
03301     SmallPtrSet<const Function *, 8> CalledFunctions;
03302     if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
03303       continue;
03304 
03305     // Just remove the call.
03306     CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
03307     CI->eraseFromParent();
03308 
03309     ++NumCXXDtorsRemoved;
03310 
03311     Changed |= true;
03312   }
03313 
03314   return Changed;
03315 }
03316 
03317 bool GlobalOpt::runOnModule(Module &M) {
03318   bool Changed = false;
03319 
03320   TD = getAnalysisIfAvailable<DataLayout>();
03321   TLI = &getAnalysis<TargetLibraryInfo>();
03322 
03323   // Try to find the llvm.globalctors list.
03324   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
03325 
03326   bool LocalChange = true;
03327   while (LocalChange) {
03328     LocalChange = false;
03329 
03330     // Delete functions that are trivially dead, ccc -> fastcc
03331     LocalChange |= OptimizeFunctions(M);
03332 
03333     // Optimize global_ctors list.
03334     if (GlobalCtors)
03335       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
03336 
03337     // Optimize non-address-taken globals.
03338     LocalChange |= OptimizeGlobalVars(M);
03339 
03340     // Resolve aliases, when possible.
03341     LocalChange |= OptimizeGlobalAliases(M);
03342 
03343     // Try to remove trivial global destructors if they are not removed
03344     // already.
03345     Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
03346     if (CXAAtExitFn)
03347       LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
03348 
03349     Changed |= LocalChange;
03350   }
03351 
03352   // TODO: Move all global ctors functions to the end of the module for code
03353   // layout.
03354 
03355   return Changed;
03356 }