LLVM API Documentation

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