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