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