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