LLVM  mainline
ArgumentPromotion.cpp
Go to the documentation of this file.
00001 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
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 promotes "by reference" arguments to be "by value" arguments.  In
00011 // practice, this means looking for internal functions that have pointer
00012 // arguments.  If it can prove, through the use of alias analysis, that an
00013 // argument is *only* loaded, then it can pass the value into the function
00014 // instead of the address of the value.  This can cause recursive simplification
00015 // of code and lead to the elimination of allocas (especially in C++ template
00016 // code like the STL).
00017 //
00018 // This pass also handles aggregate arguments that are passed into a function,
00019 // scalarizing them if the elements of the aggregate are only loaded.  Note that
00020 // by default it refuses to scalarize aggregates which would require passing in
00021 // more than three operands to the function, because passing thousands of
00022 // operands for a large array or structure is unprofitable! This limit can be
00023 // configured or disabled, however.
00024 //
00025 // Note that this transformation could also be done for arguments that are only
00026 // stored to (returning the value instead), but does not currently.  This case
00027 // would be best handled when and if LLVM begins supporting multiple return
00028 // values from functions.
00029 //
00030 //===----------------------------------------------------------------------===//
00031 
00032 #include "llvm/Transforms/IPO.h"
00033 #include "llvm/ADT/DepthFirstIterator.h"
00034 #include "llvm/ADT/Statistic.h"
00035 #include "llvm/ADT/StringExtras.h"
00036 #include "llvm/Analysis/AliasAnalysis.h"
00037 #include "llvm/Analysis/AssumptionCache.h"
00038 #include "llvm/Analysis/BasicAliasAnalysis.h"
00039 #include "llvm/Analysis/CallGraph.h"
00040 #include "llvm/Analysis/CallGraphSCCPass.h"
00041 #include "llvm/Analysis/TargetLibraryInfo.h"
00042 #include "llvm/Analysis/ValueTracking.h"
00043 #include "llvm/IR/CFG.h"
00044 #include "llvm/IR/CallSite.h"
00045 #include "llvm/IR/Constants.h"
00046 #include "llvm/IR/DataLayout.h"
00047 #include "llvm/IR/DebugInfo.h"
00048 #include "llvm/IR/DerivedTypes.h"
00049 #include "llvm/IR/Instructions.h"
00050 #include "llvm/IR/LLVMContext.h"
00051 #include "llvm/IR/Module.h"
00052 #include "llvm/Support/Debug.h"
00053 #include "llvm/Support/raw_ostream.h"
00054 #include <set>
00055 using namespace llvm;
00056 
00057 #define DEBUG_TYPE "argpromotion"
00058 
00059 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
00060 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
00061 STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
00062 STATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
00063 
00064 namespace {
00065   /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
00066   ///
00067   struct ArgPromotion : public CallGraphSCCPass {
00068     void getAnalysisUsage(AnalysisUsage &AU) const override {
00069       AU.addRequired<AssumptionCacheTracker>();
00070       AU.addRequired<TargetLibraryInfoWrapperPass>();
00071       CallGraphSCCPass::getAnalysisUsage(AU);
00072     }
00073 
00074     bool runOnSCC(CallGraphSCC &SCC) override;
00075     static char ID; // Pass identification, replacement for typeid
00076     explicit ArgPromotion(unsigned maxElements = 3)
00077         : CallGraphSCCPass(ID), maxElements(maxElements) {
00078       initializeArgPromotionPass(*PassRegistry::getPassRegistry());
00079     }
00080 
00081     /// A vector used to hold the indices of a single GEP instruction
00082     typedef std::vector<uint64_t> IndicesVector;
00083 
00084   private:
00085     bool isDenselyPacked(Type *type, const DataLayout &DL);
00086     bool canPaddingBeAccessed(Argument *Arg);
00087     CallGraphNode *PromoteArguments(CallGraphNode *CGN);
00088     bool isSafeToPromoteArgument(Argument *Arg, bool isByVal,
00089                                  AAResults &AAR) const;
00090     CallGraphNode *DoPromotion(Function *F,
00091                               SmallPtrSetImpl<Argument*> &ArgsToPromote,
00092                               SmallPtrSetImpl<Argument*> &ByValArgsToTransform);
00093     
00094     using llvm::Pass::doInitialization;
00095     bool doInitialization(CallGraph &CG) override;
00096     /// The maximum number of elements to expand, or 0 for unlimited.
00097     unsigned maxElements;
00098   };
00099 }
00100 
00101 char ArgPromotion::ID = 0;
00102 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
00103                 "Promote 'by reference' arguments to scalars", false, false)
00104 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00105 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
00106 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00107 INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
00108                 "Promote 'by reference' arguments to scalars", false, false)
00109 
00110 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
00111   return new ArgPromotion(maxElements);
00112 }
00113 
00114 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
00115   bool Changed = false, LocalChange;
00116 
00117   do {  // Iterate until we stop promoting from this SCC.
00118     LocalChange = false;
00119     // Attempt to promote arguments from all functions in this SCC.
00120     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
00121       if (CallGraphNode *CGN = PromoteArguments(*I)) {
00122         LocalChange = true;
00123         SCC.ReplaceNode(*I, CGN);
00124       }
00125     }
00126     Changed |= LocalChange;               // Remember that we changed something.
00127   } while (LocalChange);
00128   
00129   return Changed;
00130 }
00131 
00132 /// \brief Checks if a type could have padding bytes.
00133 bool ArgPromotion::isDenselyPacked(Type *type, const DataLayout &DL) {
00134 
00135   // There is no size information, so be conservative.
00136   if (!type->isSized())
00137     return false;
00138 
00139   // If the alloc size is not equal to the storage size, then there are padding
00140   // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
00141   if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
00142     return false;
00143 
00144   if (!isa<CompositeType>(type))
00145     return true;
00146 
00147   // For homogenous sequential types, check for padding within members.
00148   if (SequentialType *seqTy = dyn_cast<SequentialType>(type))
00149     return isa<PointerType>(seqTy) ||
00150            isDenselyPacked(seqTy->getElementType(), DL);
00151 
00152   // Check for padding within and between elements of a struct.
00153   StructType *StructTy = cast<StructType>(type);
00154   const StructLayout *Layout = DL.getStructLayout(StructTy);
00155   uint64_t StartPos = 0;
00156   for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
00157     Type *ElTy = StructTy->getElementType(i);
00158     if (!isDenselyPacked(ElTy, DL))
00159       return false;
00160     if (StartPos != Layout->getElementOffsetInBits(i))
00161       return false;
00162     StartPos += DL.getTypeAllocSizeInBits(ElTy);
00163   }
00164 
00165   return true;
00166 }
00167 
00168 /// \brief Checks if the padding bytes of an argument could be accessed.
00169 bool ArgPromotion::canPaddingBeAccessed(Argument *arg) {
00170 
00171   assert(arg->hasByValAttr());
00172 
00173   // Track all the pointers to the argument to make sure they are not captured.
00174   SmallPtrSet<Value *, 16> PtrValues;
00175   PtrValues.insert(arg);
00176 
00177   // Track all of the stores.
00178   SmallVector<StoreInst *, 16> Stores;
00179 
00180   // Scan through the uses recursively to make sure the pointer is always used
00181   // sanely.
00182   SmallVector<Value *, 16> WorkList;
00183   WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end());
00184   while (!WorkList.empty()) {
00185     Value *V = WorkList.back();
00186     WorkList.pop_back();
00187     if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
00188       if (PtrValues.insert(V).second)
00189         WorkList.insert(WorkList.end(), V->user_begin(), V->user_end());
00190     } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
00191       Stores.push_back(Store);
00192     } else if (!isa<LoadInst>(V)) {
00193       return true;
00194     }
00195   }
00196 
00197 // Check to make sure the pointers aren't captured
00198   for (StoreInst *Store : Stores)
00199     if (PtrValues.count(Store->getValueOperand()))
00200       return true;
00201 
00202   return false;
00203 }
00204 
00205 /// PromoteArguments - This method checks the specified function to see if there
00206 /// are any promotable arguments and if it is safe to promote the function (for
00207 /// example, all callers are direct).  If safe to promote some arguments, it
00208 /// calls the DoPromotion method.
00209 ///
00210 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
00211   Function *F = CGN->getFunction();
00212 
00213   // Make sure that it is local to this module.
00214   if (!F || !F->hasLocalLinkage()) return nullptr;
00215 
00216   // Don't promote arguments for variadic functions. Adding, removing, or
00217   // changing non-pack parameters can change the classification of pack
00218   // parameters. Frontends encode that classification at the call site in the
00219   // IR, while in the callee the classification is determined dynamically based
00220   // on the number of registers consumed so far.
00221   if (F->isVarArg()) return nullptr;
00222 
00223   // First check: see if there are any pointer arguments!  If not, quick exit.
00224   SmallVector<Argument*, 16> PointerArgs;
00225   for (Argument &I : F->args())
00226     if (I.getType()->isPointerTy())
00227       PointerArgs.push_back(&I);
00228   if (PointerArgs.empty()) return nullptr;
00229 
00230   // Second check: make sure that all callers are direct callers.  We can't
00231   // transform functions that have indirect callers.  Also see if the function
00232   // is self-recursive.
00233   bool isSelfRecursive = false;
00234   for (Use &U : F->uses()) {
00235     CallSite CS(U.getUser());
00236     // Must be a direct call.
00237     if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr;
00238     
00239     if (CS.getInstruction()->getParent()->getParent() == F)
00240       isSelfRecursive = true;
00241   }
00242   
00243   const DataLayout &DL = F->getParent()->getDataLayout();
00244 
00245   // We need to manually construct BasicAA directly in order to disable its use
00246   // of other function analyses.
00247   BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
00248 
00249   // Construct our own AA results for this function. We do this manually to
00250   // work around the limitations of the legacy pass manager.
00251   AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
00252 
00253   // Check to see which arguments are promotable.  If an argument is promotable,
00254   // add it to ArgsToPromote.
00255   SmallPtrSet<Argument*, 8> ArgsToPromote;
00256   SmallPtrSet<Argument*, 8> ByValArgsToTransform;
00257   for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) {
00258     Argument *PtrArg = PointerArgs[i];
00259     Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
00260 
00261     // Replace sret attribute with noalias. This reduces register pressure by
00262     // avoiding a register copy.
00263     if (PtrArg->hasStructRetAttr()) {
00264       unsigned ArgNo = PtrArg->getArgNo();
00265       F->setAttributes(
00266           F->getAttributes()
00267               .removeAttribute(F->getContext(), ArgNo + 1, Attribute::StructRet)
00268               .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
00269       for (Use &U : F->uses()) {
00270         CallSite CS(U.getUser());
00271         CS.setAttributes(
00272             CS.getAttributes()
00273                 .removeAttribute(F->getContext(), ArgNo + 1,
00274                                  Attribute::StructRet)
00275                 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
00276       }
00277     }
00278 
00279     // If this is a byval argument, and if the aggregate type is small, just
00280     // pass the elements, which is always safe, if the passed value is densely
00281     // packed or if we can prove the padding bytes are never accessed. This does
00282     // not apply to inalloca.
00283     bool isSafeToPromote =
00284         PtrArg->hasByValAttr() &&
00285         (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg));
00286     if (isSafeToPromote) {
00287       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
00288         if (maxElements > 0 && STy->getNumElements() > maxElements) {
00289           DEBUG(dbgs() << "argpromotion disable promoting argument '"
00290                 << PtrArg->getName() << "' because it would require adding more"
00291                 << " than " << maxElements << " arguments to the function.\n");
00292           continue;
00293         }
00294         
00295         // If all the elements are single-value types, we can promote it.
00296         bool AllSimple = true;
00297         for (const auto *EltTy : STy->elements()) {
00298           if (!EltTy->isSingleValueType()) {
00299             AllSimple = false;
00300             break;
00301           }
00302         }
00303 
00304         // Safe to transform, don't even bother trying to "promote" it.
00305         // Passing the elements as a scalar will allow scalarrepl to hack on
00306         // the new alloca we introduce.
00307         if (AllSimple) {
00308           ByValArgsToTransform.insert(PtrArg);
00309           continue;
00310         }
00311       }
00312     }
00313 
00314     // If the argument is a recursive type and we're in a recursive
00315     // function, we could end up infinitely peeling the function argument.
00316     if (isSelfRecursive) {
00317       if (StructType *STy = dyn_cast<StructType>(AgTy)) {
00318         bool RecursiveType = false;
00319         for (const auto *EltTy : STy->elements()) {
00320           if (EltTy == PtrArg->getType()) {
00321             RecursiveType = true;
00322             break;
00323           }
00324         }
00325         if (RecursiveType)
00326           continue;
00327       }
00328     }
00329     
00330     // Otherwise, see if we can promote the pointer to its value.
00331     if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr(), AAR))
00332       ArgsToPromote.insert(PtrArg);
00333   }
00334 
00335   // No promotable pointer arguments.
00336   if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 
00337     return nullptr;
00338 
00339   return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
00340 }
00341 
00342 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that
00343 /// all callees pass in a valid pointer for the specified function argument.
00344 static bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
00345   Function *Callee = Arg->getParent();
00346   const DataLayout &DL = Callee->getParent()->getDataLayout();
00347 
00348   unsigned ArgNo = Arg->getArgNo();
00349 
00350   // Look at all call sites of the function.  At this pointer we know we only
00351   // have direct callees.
00352   for (User *U : Callee->users()) {
00353     CallSite CS(U);
00354     assert(CS && "Should only have direct calls!");
00355 
00356     if (!isDereferenceablePointer(CS.getArgument(ArgNo), DL))
00357       return false;
00358   }
00359   return true;
00360 }
00361 
00362 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size
00363 /// that is greater than or equal to the size of prefix, and each of the
00364 /// elements in Prefix is the same as the corresponding elements in Longer.
00365 ///
00366 /// This means it also returns true when Prefix and Longer are equal!
00367 static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
00368                      const ArgPromotion::IndicesVector &Longer) {
00369   if (Prefix.size() > Longer.size())
00370     return false;
00371   return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
00372 }
00373 
00374 
00375 /// Checks if Indices, or a prefix of Indices, is in Set.
00376 static bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
00377                      std::set<ArgPromotion::IndicesVector> &Set) {
00378     std::set<ArgPromotion::IndicesVector>::iterator Low;
00379     Low = Set.upper_bound(Indices);
00380     if (Low != Set.begin())
00381       Low--;
00382     // Low is now the last element smaller than or equal to Indices. This means
00383     // it points to a prefix of Indices (possibly Indices itself), if such
00384     // prefix exists.
00385     //
00386     // This load is safe if any prefix of its operands is safe to load.
00387     return Low != Set.end() && IsPrefix(*Low, Indices);
00388 }
00389 
00390 /// Mark the given indices (ToMark) as safe in the given set of indices
00391 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
00392 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe
00393 /// already. Furthermore, any indices that Indices is itself a prefix of, are
00394 /// removed from Safe (since they are implicitely safe because of Indices now).
00395 static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
00396                             std::set<ArgPromotion::IndicesVector> &Safe) {
00397   std::set<ArgPromotion::IndicesVector>::iterator Low;
00398   Low = Safe.upper_bound(ToMark);
00399   // Guard against the case where Safe is empty
00400   if (Low != Safe.begin())
00401     Low--;
00402   // Low is now the last element smaller than or equal to Indices. This
00403   // means it points to a prefix of Indices (possibly Indices itself), if
00404   // such prefix exists.
00405   if (Low != Safe.end()) {
00406     if (IsPrefix(*Low, ToMark))
00407       // If there is already a prefix of these indices (or exactly these
00408       // indices) marked a safe, don't bother adding these indices
00409       return;
00410 
00411     // Increment Low, so we can use it as a "insert before" hint
00412     ++Low;
00413   }
00414   // Insert
00415   Low = Safe.insert(Low, ToMark);
00416   ++Low;
00417   // If there we're a prefix of longer index list(s), remove those
00418   std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
00419   while (Low != End && IsPrefix(ToMark, *Low)) {
00420     std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
00421     ++Low;
00422     Safe.erase(Remove);
00423   }
00424 }
00425 
00426 /// isSafeToPromoteArgument - As you might guess from the name of this method,
00427 /// it checks to see if it is both safe and useful to promote the argument.
00428 /// This method limits promotion of aggregates to only promote up to three
00429 /// elements of the aggregate in order to avoid exploding the number of
00430 /// arguments passed in.
00431 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg,
00432                                            bool isByValOrInAlloca,
00433                                            AAResults &AAR) const {
00434   typedef std::set<IndicesVector> GEPIndicesSet;
00435 
00436   // Quick exit for unused arguments
00437   if (Arg->use_empty())
00438     return true;
00439 
00440   // We can only promote this argument if all of the uses are loads, or are GEP
00441   // instructions (with constant indices) that are subsequently loaded.
00442   //
00443   // Promoting the argument causes it to be loaded in the caller
00444   // unconditionally. This is only safe if we can prove that either the load
00445   // would have happened in the callee anyway (ie, there is a load in the entry
00446   // block) or the pointer passed in at every call site is guaranteed to be
00447   // valid.
00448   // In the former case, invalid loads can happen, but would have happened
00449   // anyway, in the latter case, invalid loads won't happen. This prevents us
00450   // from introducing an invalid load that wouldn't have happened in the
00451   // original code.
00452   //
00453   // This set will contain all sets of indices that are loaded in the entry
00454   // block, and thus are safe to unconditionally load in the caller.
00455   //
00456   // This optimization is also safe for InAlloca parameters, because it verifies
00457   // that the address isn't captured.
00458   GEPIndicesSet SafeToUnconditionallyLoad;
00459 
00460   // This set contains all the sets of indices that we are planning to promote.
00461   // This makes it possible to limit the number of arguments added.
00462   GEPIndicesSet ToPromote;
00463 
00464   // If the pointer is always valid, any load with first index 0 is valid.
00465   if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg))
00466     SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
00467 
00468   // First, iterate the entry block and mark loads of (geps of) arguments as
00469   // safe.
00470   BasicBlock &EntryBlock = Arg->getParent()->front();
00471   // Declare this here so we can reuse it
00472   IndicesVector Indices;
00473   for (Instruction &I : EntryBlock)
00474     if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
00475       Value *V = LI->getPointerOperand();
00476       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
00477         V = GEP->getPointerOperand();
00478         if (V == Arg) {
00479           // This load actually loads (part of) Arg? Check the indices then.
00480           Indices.reserve(GEP->getNumIndices());
00481           for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
00482                II != IE; ++II)
00483             if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
00484               Indices.push_back(CI->getSExtValue());
00485             else
00486               // We found a non-constant GEP index for this argument? Bail out
00487               // right away, can't promote this argument at all.
00488               return false;
00489 
00490           // Indices checked out, mark them as safe
00491           MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
00492           Indices.clear();
00493         }
00494       } else if (V == Arg) {
00495         // Direct loads are equivalent to a GEP with a single 0 index.
00496         MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
00497       }
00498     }
00499 
00500   // Now, iterate all uses of the argument to see if there are any uses that are
00501   // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
00502   SmallVector<LoadInst*, 16> Loads;
00503   IndicesVector Operands;
00504   for (Use &U : Arg->uses()) {
00505     User *UR = U.getUser();
00506     Operands.clear();
00507     if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
00508       // Don't hack volatile/atomic loads
00509       if (!LI->isSimple()) return false;
00510       Loads.push_back(LI);
00511       // Direct loads are equivalent to a GEP with a zero index and then a load.
00512       Operands.push_back(0);
00513     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
00514       if (GEP->use_empty()) {
00515         // Dead GEP's cause trouble later.  Just remove them if we run into
00516         // them.
00517         GEP->eraseFromParent();
00518         // TODO: This runs the above loop over and over again for dead GEPs
00519         // Couldn't we just do increment the UI iterator earlier and erase the
00520         // use?
00521         return isSafeToPromoteArgument(Arg, isByValOrInAlloca, AAR);
00522       }
00523 
00524       // Ensure that all of the indices are constants.
00525       for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
00526         i != e; ++i)
00527         if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
00528           Operands.push_back(C->getSExtValue());
00529         else
00530           return false;  // Not a constant operand GEP!
00531 
00532       // Ensure that the only users of the GEP are load instructions.
00533       for (User *GEPU : GEP->users())
00534         if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
00535           // Don't hack volatile/atomic loads
00536           if (!LI->isSimple()) return false;
00537           Loads.push_back(LI);
00538         } else {
00539           // Other uses than load?
00540           return false;
00541         }
00542     } else {
00543       return false;  // Not a load or a GEP.
00544     }
00545 
00546     // Now, see if it is safe to promote this load / loads of this GEP. Loading
00547     // is safe if Operands, or a prefix of Operands, is marked as safe.
00548     if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
00549       return false;
00550 
00551     // See if we are already promoting a load with these indices. If not, check
00552     // to make sure that we aren't promoting too many elements.  If so, nothing
00553     // to do.
00554     if (ToPromote.find(Operands) == ToPromote.end()) {
00555       if (maxElements > 0 && ToPromote.size() == maxElements) {
00556         DEBUG(dbgs() << "argpromotion not promoting argument '"
00557               << Arg->getName() << "' because it would require adding more "
00558               << "than " << maxElements << " arguments to the function.\n");
00559         // We limit aggregate promotion to only promoting up to a fixed number
00560         // of elements of the aggregate.
00561         return false;
00562       }
00563       ToPromote.insert(std::move(Operands));
00564     }
00565   }
00566 
00567   if (Loads.empty()) return true;  // No users, this is a dead argument.
00568 
00569   // Okay, now we know that the argument is only used by load instructions and
00570   // it is safe to unconditionally perform all of them. Use alias analysis to
00571   // check to see if the pointer is guaranteed to not be modified from entry of
00572   // the function to each of the load instructions.
00573 
00574   // Because there could be several/many load instructions, remember which
00575   // blocks we know to be transparent to the load.
00576   SmallPtrSet<BasicBlock*, 16> TranspBlocks;
00577 
00578   for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
00579     // Check to see if the load is invalidated from the start of the block to
00580     // the load itself.
00581     LoadInst *Load = Loads[i];
00582     BasicBlock *BB = Load->getParent();
00583 
00584     MemoryLocation Loc = MemoryLocation::get(Load);
00585     if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, MRI_Mod))
00586       return false;  // Pointer is invalidated!
00587 
00588     // Now check every path from the entry block to the load for transparency.
00589     // To do this, we perform a depth first search on the inverse CFG from the
00590     // loading block.
00591     for (BasicBlock *P : predecessors(BB)) {
00592       for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
00593         if (AAR.canBasicBlockModify(*TranspBB, Loc))
00594           return false;
00595     }
00596   }
00597 
00598   // If the path from the entry of the function to each load is free of
00599   // instructions that potentially invalidate the load, we can make the
00600   // transformation!
00601   return true;
00602 }
00603 
00604 /// DoPromotion - This method actually performs the promotion of the specified
00605 /// arguments, and returns the new function.  At this point, we know that it's
00606 /// safe to do so.
00607 CallGraphNode *ArgPromotion::DoPromotion(Function *F,
00608                              SmallPtrSetImpl<Argument*> &ArgsToPromote,
00609                              SmallPtrSetImpl<Argument*> &ByValArgsToTransform) {
00610 
00611   // Start by computing a new prototype for the function, which is the same as
00612   // the old function, but has modified arguments.
00613   FunctionType *FTy = F->getFunctionType();
00614   std::vector<Type*> Params;
00615 
00616   typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable;
00617 
00618   // ScalarizedElements - If we are promoting a pointer that has elements
00619   // accessed out of it, keep track of which elements are accessed so that we
00620   // can add one argument for each.
00621   //
00622   // Arguments that are directly loaded will have a zero element value here, to
00623   // handle cases where there are both a direct load and GEP accesses.
00624   //
00625   std::map<Argument*, ScalarizeTable> ScalarizedElements;
00626 
00627   // OriginalLoads - Keep track of a representative load instruction from the
00628   // original function so that we can tell the alias analysis implementation
00629   // what the new GEP/Load instructions we are inserting look like.
00630   // We need to keep the original loads for each argument and the elements
00631   // of the argument that are accessed.
00632   std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads;
00633 
00634   // Attribute - Keep track of the parameter attributes for the arguments
00635   // that we are *not* promoting. For the ones that we do promote, the parameter
00636   // attributes are lost
00637   SmallVector<AttributeSet, 8> AttributesVec;
00638   const AttributeSet &PAL = F->getAttributes();
00639 
00640   // Add any return attributes.
00641   if (PAL.hasAttributes(AttributeSet::ReturnIndex))
00642     AttributesVec.push_back(AttributeSet::get(F->getContext(),
00643                                               PAL.getRetAttributes()));
00644 
00645   // First, determine the new argument list
00646   unsigned ArgIndex = 1;
00647   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
00648        ++I, ++ArgIndex) {
00649     if (ByValArgsToTransform.count(&*I)) {
00650       // Simple byval argument? Just add all the struct element types.
00651       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
00652       StructType *STy = cast<StructType>(AgTy);
00653       Params.insert(Params.end(), STy->element_begin(), STy->element_end());
00654       ++NumByValArgsPromoted;
00655     } else if (!ArgsToPromote.count(&*I)) {
00656       // Unchanged argument
00657       Params.push_back(I->getType());
00658       AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
00659       if (attrs.hasAttributes(ArgIndex)) {
00660         AttrBuilder B(attrs, ArgIndex);
00661         AttributesVec.
00662           push_back(AttributeSet::get(F->getContext(), Params.size(), B));
00663       }
00664     } else if (I->use_empty()) {
00665       // Dead argument (which are always marked as promotable)
00666       ++NumArgumentsDead;
00667     } else {
00668       // Okay, this is being promoted. This means that the only uses are loads
00669       // or GEPs which are only used by loads
00670 
00671       // In this table, we will track which indices are loaded from the argument
00672       // (where direct loads are tracked as no indices).
00673       ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
00674       for (User *U : I->users()) {
00675         Instruction *UI = cast<Instruction>(U);
00676         Type *SrcTy;
00677         if (LoadInst *L = dyn_cast<LoadInst>(UI))
00678           SrcTy = L->getType();
00679         else
00680           SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
00681         IndicesVector Indices;
00682         Indices.reserve(UI->getNumOperands() - 1);
00683         // Since loads will only have a single operand, and GEPs only a single
00684         // non-index operand, this will record direct loads without any indices,
00685         // and gep+loads with the GEP indices.
00686         for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
00687              II != IE; ++II)
00688           Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
00689         // GEPs with a single 0 index can be merged with direct loads
00690         if (Indices.size() == 1 && Indices.front() == 0)
00691           Indices.clear();
00692         ArgIndices.insert(std::make_pair(SrcTy, Indices));
00693         LoadInst *OrigLoad;
00694         if (LoadInst *L = dyn_cast<LoadInst>(UI))
00695           OrigLoad = L;
00696         else
00697           // Take any load, we will use it only to update Alias Analysis
00698           OrigLoad = cast<LoadInst>(UI->user_back());
00699         OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
00700       }
00701 
00702       // Add a parameter to the function for each element passed in.
00703       for (ScalarizeTable::iterator SI = ArgIndices.begin(),
00704              E = ArgIndices.end(); SI != E; ++SI) {
00705         // not allowed to dereference ->begin() if size() is 0
00706         Params.push_back(GetElementPtrInst::getIndexedType(
00707             cast<PointerType>(I->getType()->getScalarType())->getElementType(),
00708             SI->second));
00709         assert(Params.back());
00710       }
00711 
00712       if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
00713         ++NumArgumentsPromoted;
00714       else
00715         ++NumAggregatesPromoted;
00716     }
00717   }
00718 
00719   // Add any function attributes.
00720   if (PAL.hasAttributes(AttributeSet::FunctionIndex))
00721     AttributesVec.push_back(AttributeSet::get(FTy->getContext(),
00722                                               PAL.getFnAttributes()));
00723 
00724   Type *RetTy = FTy->getReturnType();
00725 
00726   // Construct the new function type using the new arguments.
00727   FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
00728 
00729   // Create the new function body and insert it into the module.
00730   Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
00731   NF->copyAttributesFrom(F);
00732 
00733   // Patch the pointer to LLVM function in debug info descriptor.
00734   NF->setSubprogram(F->getSubprogram());
00735   F->setSubprogram(nullptr);
00736 
00737   DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
00738         << "From: " << *F);
00739   
00740   // Recompute the parameter attributes list based on the new arguments for
00741   // the function.
00742   NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
00743   AttributesVec.clear();
00744 
00745   F->getParent()->getFunctionList().insert(F->getIterator(), NF);
00746   NF->takeName(F);
00747 
00748   // Get the callgraph information that we need to update to reflect our
00749   // changes.
00750   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
00751 
00752   // Get a new callgraph node for NF.
00753   CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
00754 
00755   // Loop over all of the callers of the function, transforming the call sites
00756   // to pass in the loaded pointers.
00757   //
00758   SmallVector<Value*, 16> Args;
00759   while (!F->use_empty()) {
00760     CallSite CS(F->user_back());
00761     assert(CS.getCalledFunction() == F);
00762     Instruction *Call = CS.getInstruction();
00763     const AttributeSet &CallPAL = CS.getAttributes();
00764 
00765     // Add any return attributes.
00766     if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
00767       AttributesVec.push_back(AttributeSet::get(F->getContext(),
00768                                                 CallPAL.getRetAttributes()));
00769 
00770     // Loop over the operands, inserting GEP and loads in the caller as
00771     // appropriate.
00772     CallSite::arg_iterator AI = CS.arg_begin();
00773     ArgIndex = 1;
00774     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00775          I != E; ++I, ++AI, ++ArgIndex)
00776       if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
00777         Args.push_back(*AI);          // Unmodified argument
00778 
00779         if (CallPAL.hasAttributes(ArgIndex)) {
00780           AttrBuilder B(CallPAL, ArgIndex);
00781           AttributesVec.
00782             push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00783         }
00784       } else if (ByValArgsToTransform.count(&*I)) {
00785         // Emit a GEP and load for each element of the struct.
00786         Type *AgTy = cast<PointerType>(I->getType())->getElementType();
00787         StructType *STy = cast<StructType>(AgTy);
00788         Value *Idxs[2] = {
00789               ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
00790         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00791           Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
00792           Value *Idx = GetElementPtrInst::Create(
00793               STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call);
00794           // TODO: Tell AA about the new values?
00795           Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
00796         }
00797       } else if (!I->use_empty()) {
00798         // Non-dead argument: insert GEPs and loads as appropriate.
00799         ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
00800         // Store the Value* version of the indices in here, but declare it now
00801         // for reuse.
00802         std::vector<Value*> Ops;
00803         for (ScalarizeTable::iterator SI = ArgIndices.begin(),
00804                E = ArgIndices.end(); SI != E; ++SI) {
00805           Value *V = *AI;
00806           LoadInst *OrigLoad = OriginalLoads[std::make_pair(&*I, SI->second)];
00807           if (!SI->second.empty()) {
00808             Ops.reserve(SI->second.size());
00809             Type *ElTy = V->getType();
00810             for (IndicesVector::const_iterator II = SI->second.begin(),
00811                                                IE = SI->second.end();
00812                  II != IE; ++II) {
00813               // Use i32 to index structs, and i64 for others (pointers/arrays).
00814               // This satisfies GEP constraints.
00815               Type *IdxTy = (ElTy->isStructTy() ?
00816                     Type::getInt32Ty(F->getContext()) : 
00817                     Type::getInt64Ty(F->getContext()));
00818               Ops.push_back(ConstantInt::get(IdxTy, *II));
00819               // Keep track of the type we're currently indexing.
00820               ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
00821             }
00822             // And create a GEP to extract those indices.
00823             V = GetElementPtrInst::Create(SI->first, V, Ops,
00824                                           V->getName() + ".idx", Call);
00825             Ops.clear();
00826           }
00827           // Since we're replacing a load make sure we take the alignment
00828           // of the previous load.
00829           LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
00830           newLoad->setAlignment(OrigLoad->getAlignment());
00831           // Transfer the AA info too.
00832           AAMDNodes AAInfo;
00833           OrigLoad->getAAMetadata(AAInfo);
00834           newLoad->setAAMetadata(AAInfo);
00835 
00836           Args.push_back(newLoad);
00837         }
00838       }
00839 
00840     // Push any varargs arguments on the list.
00841     for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
00842       Args.push_back(*AI);
00843       if (CallPAL.hasAttributes(ArgIndex)) {
00844         AttrBuilder B(CallPAL, ArgIndex);
00845         AttributesVec.
00846           push_back(AttributeSet::get(F->getContext(), Args.size(), B));
00847       }
00848     }
00849 
00850     // Add any function attributes.
00851     if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
00852       AttributesVec.push_back(AttributeSet::get(Call->getContext(),
00853                                                 CallPAL.getFnAttributes()));
00854 
00855     Instruction *New;
00856     if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
00857       New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
00858                                Args, "", Call);
00859       cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
00860       cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(),
00861                                                             AttributesVec));
00862     } else {
00863       New = CallInst::Create(NF, Args, "", Call);
00864       cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
00865       cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(),
00866                                                           AttributesVec));
00867       if (cast<CallInst>(Call)->isTailCall())
00868         cast<CallInst>(New)->setTailCall();
00869     }
00870     New->setDebugLoc(Call->getDebugLoc());
00871     Args.clear();
00872     AttributesVec.clear();
00873 
00874     // Update the callgraph to know that the callsite has been transformed.
00875     CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
00876     CalleeNode->replaceCallEdge(CS, CallSite(New), NF_CGN);
00877 
00878     if (!Call->use_empty()) {
00879       Call->replaceAllUsesWith(New);
00880       New->takeName(Call);
00881     }
00882 
00883     // Finally, remove the old call from the program, reducing the use-count of
00884     // F.
00885     Call->eraseFromParent();
00886   }
00887 
00888   // Since we have now created the new function, splice the body of the old
00889   // function right into the new function, leaving the old rotting hulk of the
00890   // function empty.
00891   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
00892 
00893   // Loop over the argument list, transferring uses of the old arguments over to
00894   // the new arguments, also transferring over the names as well.
00895   //
00896   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
00897        I2 = NF->arg_begin(); I != E; ++I) {
00898     if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
00899       // If this is an unmodified argument, move the name and users over to the
00900       // new version.
00901       I->replaceAllUsesWith(&*I2);
00902       I2->takeName(&*I);
00903       ++I2;
00904       continue;
00905     }
00906 
00907     if (ByValArgsToTransform.count(&*I)) {
00908       // In the callee, we create an alloca, and store each of the new incoming
00909       // arguments into the alloca.
00910       Instruction *InsertPt = &NF->begin()->front();
00911 
00912       // Just add all the struct element types.
00913       Type *AgTy = cast<PointerType>(I->getType())->getElementType();
00914       Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
00915       StructType *STy = cast<StructType>(AgTy);
00916       Value *Idxs[2] = {
00917             ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr };
00918 
00919       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00920         Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
00921         Value *Idx = GetElementPtrInst::Create(
00922             AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
00923             InsertPt);
00924         I2->setName(I->getName()+"."+Twine(i));
00925         new StoreInst(&*I2++, Idx, InsertPt);
00926       }
00927 
00928       // Anything that used the arg should now use the alloca.
00929       I->replaceAllUsesWith(TheAlloca);
00930       TheAlloca->takeName(&*I);
00931 
00932       // If the alloca is used in a call, we must clear the tail flag since
00933       // the callee now uses an alloca from the caller.
00934       for (User *U : TheAlloca->users()) {
00935         CallInst *Call = dyn_cast<CallInst>(U);
00936         if (!Call)
00937           continue;
00938         Call->setTailCall(false);
00939       }
00940       continue;
00941     }
00942 
00943     if (I->use_empty())
00944       continue;
00945 
00946     // Otherwise, if we promoted this argument, then all users are load
00947     // instructions (or GEPs with only load users), and all loads should be
00948     // using the new argument that we added.
00949     ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
00950 
00951     while (!I->use_empty()) {
00952       if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
00953         assert(ArgIndices.begin()->second.empty() &&
00954                "Load element should sort to front!");
00955         I2->setName(I->getName()+".val");
00956         LI->replaceAllUsesWith(&*I2);
00957         LI->eraseFromParent();
00958         DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
00959               << "' in function '" << F->getName() << "'\n");
00960       } else {
00961         GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
00962         IndicesVector Operands;
00963         Operands.reserve(GEP->getNumIndices());
00964         for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
00965              II != IE; ++II)
00966           Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
00967 
00968         // GEPs with a single 0 index can be merged with direct loads
00969         if (Operands.size() == 1 && Operands.front() == 0)
00970           Operands.clear();
00971 
00972         Function::arg_iterator TheArg = I2;
00973         for (ScalarizeTable::iterator It = ArgIndices.begin();
00974              It->second != Operands; ++It, ++TheArg) {
00975           assert(It != ArgIndices.end() && "GEP not handled??");
00976         }
00977 
00978         std::string NewName = I->getName();
00979         for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
00980             NewName += "." + utostr(Operands[i]);
00981         }
00982         NewName += ".val";
00983         TheArg->setName(NewName);
00984 
00985         DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
00986               << "' of function '" << NF->getName() << "'\n");
00987 
00988         // All of the uses must be load instructions.  Replace them all with
00989         // the argument specified by ArgNo.
00990         while (!GEP->use_empty()) {
00991           LoadInst *L = cast<LoadInst>(GEP->user_back());
00992           L->replaceAllUsesWith(&*TheArg);
00993           L->eraseFromParent();
00994         }
00995         GEP->eraseFromParent();
00996       }
00997     }
00998 
00999     // Increment I2 past all of the arguments added for this promoted pointer.
01000     std::advance(I2, ArgIndices.size());
01001   }
01002 
01003   NF_CGN->stealCalledFunctionsFrom(CG[F]);
01004   
01005   // Now that the old function is dead, delete it.  If there is a dangling
01006   // reference to the CallgraphNode, just leave the dead function around for
01007   // someone else to nuke.
01008   CallGraphNode *CGN = CG[F];
01009   if (CGN->getNumReferences() == 0)
01010     delete CG.removeFunctionFromModule(CGN);
01011   else
01012     F->setLinkage(Function::ExternalLinkage);
01013   
01014   return NF_CGN;
01015 }
01016 
01017 bool ArgPromotion::doInitialization(CallGraph &CG) {
01018   return CallGraphSCCPass::doInitialization(CG);
01019 }