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