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