ArgumentPromotion.cpp revision e027efa21816dbd2350d137fdfa181c24cbe8c49
1//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass promotes "by reference" arguments to be "by value" arguments.  In
11// practice, this means looking for internal functions that have pointer
12// arguments.  If it can prove, through the use of alias analysis, that an
13// argument is *only* loaded, then it can pass the value into the function
14// instead of the address of the value.  This can cause recursive simplification
15// of code and lead to the elimination of allocas (especially in C++ template
16// code like the STL).
17//
18// This pass also handles aggregate arguments that are passed into a function,
19// scalarizing them if the elements of the aggregate are only loaded.  Note that
20// it refuses to scalarize aggregates which would require passing in more than
21// three operands to the function, because passing thousands of operands for a
22// large array or structure is unprofitable!
23//
24// Note that this transformation could also be done for arguments that are only
25// stored to (returning the value instead), but does not currently.  This case
26// would be best handled when and if LLVM begins supporting multiple return
27// values from functions.
28//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "argpromotion"
32#include "llvm/Transforms/IPO.h"
33#include "llvm/Constants.h"
34#include "llvm/DerivedTypes.h"
35#include "llvm/Module.h"
36#include "llvm/CallGraphSCCPass.h"
37#include "llvm/Instructions.h"
38#include "llvm/ParameterAttributes.h"
39#include "llvm/Analysis/AliasAnalysis.h"
40#include "llvm/Analysis/CallGraph.h"
41#include "llvm/Target/TargetData.h"
42#include "llvm/Support/CallSite.h"
43#include "llvm/Support/CFG.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/ADT/DepthFirstIterator.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/Support/Compiler.h"
49#include <set>
50using namespace llvm;
51
52STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
53STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
54STATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
55
56namespace {
57  /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
58  ///
59  struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
60    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61      AU.addRequired<AliasAnalysis>();
62      AU.addRequired<TargetData>();
63      CallGraphSCCPass::getAnalysisUsage(AU);
64    }
65
66    virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
67    static char ID; // Pass identification, replacement for typeid
68    ArgPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
69
70  private:
71    bool PromoteArguments(CallGraphNode *CGN);
72    bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
73    Function *DoPromotion(Function *F,
74                          SmallPtrSet<Argument*, 8> &ArgsToPromote);
75  };
76
77  char ArgPromotion::ID = 0;
78  RegisterPass<ArgPromotion> X("argpromotion",
79                               "Promote 'by reference' arguments to scalars");
80}
81
82Pass *llvm::createArgumentPromotionPass() {
83  return new ArgPromotion();
84}
85
86bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
87  bool Changed = false, LocalChange;
88
89  do {  // Iterate until we stop promoting from this SCC.
90    LocalChange = false;
91    // Attempt to promote arguments from all functions in this SCC.
92    for (unsigned i = 0, e = SCC.size(); i != e; ++i)
93      LocalChange |= PromoteArguments(SCC[i]);
94    Changed |= LocalChange;               // Remember that we changed something.
95  } while (LocalChange);
96
97  return Changed;
98}
99
100/// PromoteArguments - This method checks the specified function to see if there
101/// are any promotable arguments and if it is safe to promote the function (for
102/// example, all callers are direct).  If safe to promote some arguments, it
103/// calls the DoPromotion method.
104///
105bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
106  Function *F = CGN->getFunction();
107
108  // Make sure that it is local to this module.
109  if (!F || !F->hasInternalLinkage()) return false;
110
111  // First check: see if there are any pointer arguments!  If not, quick exit.
112  SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
113  unsigned ArgNo = 0;
114  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
115       I != E; ++I, ++ArgNo)
116    if (isa<PointerType>(I->getType()))
117      PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
118  if (PointerArgs.empty()) return false;
119
120  // Second check: make sure that all callers are direct callers.  We can't
121  // transform functions that have indirect callers.
122  for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
123       UI != E; ++UI) {
124    CallSite CS = CallSite::get(*UI);
125    if (!CS.getInstruction())       // "Taking the address" of the function
126      return false;
127
128    // Ensure that this call site is CALLING the function, not passing it as
129    // an argument.
130    if (UI.getOperandNo() != 0)
131      return false;
132  }
133
134  // Check to see which arguments are promotable.  If an argument is promotable,
135  // add it to ArgsToPromote.
136  SmallPtrSet<Argument*, 8> ArgsToPromote;
137  for (unsigned i = 0; i != PointerArgs.size(); ++i) {
138    bool isByVal = F->paramHasAttr(PointerArgs[i].second, ParamAttr::ByVal);
139    if (isSafeToPromoteArgument(PointerArgs[i].first, isByVal))
140      ArgsToPromote.insert(PointerArgs[i].first);
141  }
142
143  // No promotable pointer arguments.
144  if (ArgsToPromote.empty()) return false;
145
146  Function *NewF = DoPromotion(F, ArgsToPromote);
147
148  // Update the call graph to know that the function has been transformed.
149  getAnalysis<CallGraph>().changeFunction(F, NewF);
150  return true;
151}
152
153/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
154/// to load.
155static bool IsAlwaysValidPointer(Value *V) {
156  if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
157  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
158    return IsAlwaysValidPointer(GEP->getOperand(0));
159  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
160    if (CE->getOpcode() == Instruction::GetElementPtr)
161      return IsAlwaysValidPointer(CE->getOperand(0));
162
163  return false;
164}
165
166/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
167/// all callees pass in a valid pointer for the specified function argument.
168static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
169  Function *Callee = Arg->getParent();
170
171  unsigned ArgNo = std::distance(Callee->arg_begin(),
172                                 Function::arg_iterator(Arg));
173
174  // Look at all call sites of the function.  At this pointer we know we only
175  // have direct callees.
176  for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
177       UI != E; ++UI) {
178    CallSite CS = CallSite::get(*UI);
179    assert(CS.getInstruction() && "Should only have direct calls!");
180
181    if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
182      return false;
183  }
184  return true;
185}
186
187
188/// isSafeToPromoteArgument - As you might guess from the name of this method,
189/// it checks to see if it is both safe and useful to promote the argument.
190/// This method limits promotion of aggregates to only promote up to three
191/// elements of the aggregate in order to avoid exploding the number of
192/// arguments passed in.
193bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
194  // We can only promote this argument if all of the uses are loads, or are GEP
195  // instructions (with constant indices) that are subsequently loaded.
196
197  // We can also only promote the load if we can guarantee that it will happen.
198  // Promoting a load causes the load to be unconditionally executed in the
199  // caller, so we can't turn a conditional load into an unconditional load in
200  // general.
201  bool SafeToUnconditionallyLoad = false;
202  if (isByVal)   // ByVal arguments are always safe to load from.
203    SafeToUnconditionallyLoad = true;
204
205  BasicBlock *EntryBlock = Arg->getParent()->begin();
206  SmallVector<LoadInst*, 16> Loads;
207  std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
208  for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
209       UI != E; ++UI)
210    if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
211      if (LI->isVolatile()) return false;  // Don't hack volatile loads
212      Loads.push_back(LI);
213
214      // If this load occurs in the entry block, then the pointer is
215      // unconditionally loaded.
216      SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
217    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
218      if (GEP->use_empty()) {
219        // Dead GEP's cause trouble later.  Just remove them if we run into
220        // them.
221        getAnalysis<AliasAnalysis>().deleteValue(GEP);
222        GEP->eraseFromParent();
223        return isSafeToPromoteArgument(Arg, isByVal);
224      }
225      // Ensure that all of the indices are constants.
226      SmallVector<ConstantInt*, 8> Operands;
227      for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
228        if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
229          Operands.push_back(C);
230        else
231          return false;  // Not a constant operand GEP!
232
233      // Ensure that the only users of the GEP are load instructions.
234      for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
235           UI != E; ++UI)
236        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
237          if (LI->isVolatile()) return false;  // Don't hack volatile loads
238          Loads.push_back(LI);
239
240          // If this load occurs in the entry block, then the pointer is
241          // unconditionally loaded.
242          SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
243        } else {
244          return false;
245        }
246
247      // See if there is already a GEP with these indices.  If not, check to
248      // make sure that we aren't promoting too many elements.  If so, nothing
249      // to do.
250      if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
251          GEPIndices.end()) {
252        if (GEPIndices.size() == 3) {
253          DOUT << "argpromotion disable promoting argument '"
254               << Arg->getName() << "' because it would require adding more "
255               << "than 3 arguments to the function.\n";
256          // We limit aggregate promotion to only promoting up to three elements
257          // of the aggregate.
258          return false;
259        }
260        GEPIndices.push_back(Operands);
261      }
262    } else {
263      return false;  // Not a load or a GEP.
264    }
265
266  if (Loads.empty()) return true;  // No users, this is a dead argument.
267
268  // If we decide that we want to promote this argument, the value is going to
269  // be unconditionally loaded in all callees.  This is only safe to do if the
270  // pointer was going to be unconditionally loaded anyway (i.e. there is a load
271  // of the pointer in the entry block of the function) or if we can prove that
272  // all pointers passed in are always to legal locations (for example, no null
273  // pointers are passed in, no pointers to free'd memory, etc).
274  if (!SafeToUnconditionallyLoad &&
275      !AllCalleesPassInValidPointerForArgument(Arg))
276    return false;   // Cannot prove that this is safe!!
277
278  // Okay, now we know that the argument is only used by load instructions and
279  // it is safe to unconditionally load the pointer.  Use alias analysis to
280  // check to see if the pointer is guaranteed to not be modified from entry of
281  // the function to each of the load instructions.
282
283  // Because there could be several/many load instructions, remember which
284  // blocks we know to be transparent to the load.
285  SmallPtrSet<BasicBlock*, 16> TranspBlocks;
286
287  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
288  TargetData &TD = getAnalysis<TargetData>();
289
290  for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
291    // Check to see if the load is invalidated from the start of the block to
292    // the load itself.
293    LoadInst *Load = Loads[i];
294    BasicBlock *BB = Load->getParent();
295
296    const PointerType *LoadTy =
297      cast<PointerType>(Load->getOperand(0)->getType());
298    unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
299
300    if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
301      return false;  // Pointer is invalidated!
302
303    // Now check every path from the entry block to the load for transparency.
304    // To do this, we perform a depth first search on the inverse CFG from the
305    // loading block.
306    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
307      for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
308             I = idf_ext_begin(*PI, TranspBlocks),
309             E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
310        if (AA.canBasicBlockModify(**I, Arg, LoadSize))
311          return false;
312  }
313
314  // If the path from the entry of the function to each load is free of
315  // instructions that potentially invalidate the load, we can make the
316  // transformation!
317  return true;
318}
319
320namespace {
321  /// GEPIdxComparator - Provide a strong ordering for GEP indices.  All Value*
322  /// elements are instances of ConstantInt.
323  ///
324  struct GEPIdxComparator {
325    bool operator()(const std::vector<Value*> &LHS,
326                    const std::vector<Value*> &RHS) const {
327      unsigned idx = 0;
328      for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
329        if (LHS[idx] != RHS[idx]) {
330          return cast<ConstantInt>(LHS[idx])->getZExtValue() <
331                 cast<ConstantInt>(RHS[idx])->getZExtValue();
332        }
333      }
334
335      // Return less than if we ran out of stuff in LHS and we didn't run out of
336      // stuff in RHS.
337      return idx == LHS.size() && idx != RHS.size();
338    }
339  };
340}
341
342
343/// DoPromotion - This method actually performs the promotion of the specified
344/// arguments, and returns the new function.  At this point, we know that it's
345/// safe to do so.
346Function *ArgPromotion::DoPromotion(Function *F,
347                                    SmallPtrSet<Argument*, 8> &ArgsToPromote) {
348
349  // Start by computing a new prototype for the function, which is the same as
350  // the old function, but has modified arguments.
351  const FunctionType *FTy = F->getFunctionType();
352  std::vector<const Type*> Params;
353
354  typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
355
356  // ScalarizedElements - If we are promoting a pointer that has elements
357  // accessed out of it, keep track of which elements are accessed so that we
358  // can add one argument for each.
359  //
360  // Arguments that are directly loaded will have a zero element value here, to
361  // handle cases where there are both a direct load and GEP accesses.
362  //
363  std::map<Argument*, ScalarizeTable> ScalarizedElements;
364
365  // OriginalLoads - Keep track of a representative load instruction from the
366  // original function so that we can tell the alias analysis implementation
367  // what the new GEP/Load instructions we are inserting look like.
368  std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
369
370  // ParamAttrs - Keep track of the parameter attributes for the arguments
371  // that we are *not* promoting. For the ones that we do promote, the parameter
372  // attributes are lost
373  ParamAttrsVector ParamAttrsVec;
374  const ParamAttrsList *PAL = F->getParamAttrs();
375
376  unsigned index = 1;
377  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
378       ++I, ++index)
379    if (!ArgsToPromote.count(I)) {
380      Params.push_back(I->getType());
381      if (PAL) {
382        unsigned attrs = PAL->getParamAttrs(index);
383        if (attrs)
384          ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(),
385                                  attrs));
386      }
387    } else if (I->use_empty()) {
388      ++NumArgumentsDead;
389    } else {
390      // Okay, this is being promoted.  Check to see if there are any GEP uses
391      // of the argument.
392      ScalarizeTable &ArgIndices = ScalarizedElements[I];
393      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
394           ++UI) {
395        Instruction *User = cast<Instruction>(*UI);
396        assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
397        std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
398        ArgIndices.insert(Indices);
399        LoadInst *OrigLoad;
400        if (LoadInst *L = dyn_cast<LoadInst>(User))
401          OrigLoad = L;
402        else
403          OrigLoad = cast<LoadInst>(User->use_back());
404        OriginalLoads[Indices] = OrigLoad;
405      }
406
407      // Add a parameter to the function for each element passed in.
408      for (ScalarizeTable::iterator SI = ArgIndices.begin(),
409             E = ArgIndices.end(); SI != E; ++SI)
410        Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
411                                                           SI->begin(),
412                                                           SI->end()));
413
414      if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
415        ++NumArgumentsPromoted;
416      else
417        ++NumAggregatesPromoted;
418    }
419
420  const Type *RetTy = FTy->getReturnType();
421
422  // Recompute the parameter attributes list based on the new arguments for
423  // the function.
424  if (ParamAttrsVec.empty())
425    PAL = 0;
426  else
427    PAL = ParamAttrsList::get(ParamAttrsVec);
428
429  // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
430  // have zero fixed arguments.
431  bool ExtraArgHack = false;
432  if (Params.empty() && FTy->isVarArg()) {
433    ExtraArgHack = true;
434    Params.push_back(Type::Int32Ty);
435  }
436
437  // Construct the new function type using the new arguments.
438  FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
439
440  // Create the new function body and insert it into the module...
441  Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
442  NF->setCallingConv(F->getCallingConv());
443  NF->setParamAttrs(PAL);
444  if (F->hasCollector())
445    NF->setCollector(F->getCollector());
446  F->getParent()->getFunctionList().insert(F, NF);
447
448  // Get the alias analysis information that we need to update to reflect our
449  // changes.
450  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
451
452  // Loop over all of the callers of the function, transforming the call sites
453  // to pass in the loaded pointers.
454  //
455  std::vector<Value*> Args;
456  while (!F->use_empty()) {
457    CallSite CS = CallSite::get(F->use_back());
458    Instruction *Call = CS.getInstruction();
459
460    // Loop over the operands, inserting GEP and loads in the caller as
461    // appropriate.
462    CallSite::arg_iterator AI = CS.arg_begin();
463    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
464         I != E; ++I, ++AI)
465      if (!ArgsToPromote.count(I))
466        Args.push_back(*AI);          // Unmodified argument
467      else if (!I->use_empty()) {
468        // Non-dead argument: insert GEPs and loads as appropriate.
469        ScalarizeTable &ArgIndices = ScalarizedElements[I];
470        for (ScalarizeTable::iterator SI = ArgIndices.begin(),
471               E = ArgIndices.end(); SI != E; ++SI) {
472          Value *V = *AI;
473          LoadInst *OrigLoad = OriginalLoads[*SI];
474          if (!SI->empty()) {
475            V = new GetElementPtrInst(V, SI->begin(), SI->end(),
476                                      V->getName()+".idx", Call);
477            AA.copyValue(OrigLoad->getOperand(0), V);
478          }
479          Args.push_back(new LoadInst(V, V->getName()+".val", Call));
480          AA.copyValue(OrigLoad, Args.back());
481        }
482      }
483
484    if (ExtraArgHack)
485      Args.push_back(Constant::getNullValue(Type::Int32Ty));
486
487    // Push any varargs arguments on the list
488    for (; AI != CS.arg_end(); ++AI)
489      Args.push_back(*AI);
490
491    Instruction *New;
492    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
493      New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
494                           Args.begin(), Args.end(), "", Call);
495      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
496      cast<InvokeInst>(New)->setParamAttrs(PAL);
497    } else {
498      New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
499      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
500      cast<CallInst>(New)->setParamAttrs(PAL);
501      if (cast<CallInst>(Call)->isTailCall())
502        cast<CallInst>(New)->setTailCall();
503    }
504    Args.clear();
505
506    // Update the alias analysis implementation to know that we are replacing
507    // the old call with a new one.
508    AA.replaceWithNewValue(Call, New);
509
510    if (!Call->use_empty()) {
511      Call->replaceAllUsesWith(New);
512      New->takeName(Call);
513    }
514
515    // Finally, remove the old call from the program, reducing the use-count of
516    // F.
517    Call->eraseFromParent();
518  }
519
520  // Since we have now created the new function, splice the body of the old
521  // function right into the new function, leaving the old rotting hulk of the
522  // function empty.
523  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
524
525  // Loop over the argument list, transfering uses of the old arguments over to
526  // the new arguments, also transfering over the names as well.
527  //
528  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
529       I2 = NF->arg_begin(); I != E; ++I)
530    if (!ArgsToPromote.count(I)) {
531      // If this is an unmodified argument, move the name and users over to the
532      // new version.
533      I->replaceAllUsesWith(I2);
534      I2->takeName(I);
535      AA.replaceWithNewValue(I, I2);
536      ++I2;
537    } else if (I->use_empty()) {
538      AA.deleteValue(I);
539    } else {
540      // Otherwise, if we promoted this argument, then all users are load
541      // instructions, and all loads should be using the new argument that we
542      // added.
543      ScalarizeTable &ArgIndices = ScalarizedElements[I];
544
545      while (!I->use_empty()) {
546        if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
547          assert(ArgIndices.begin()->empty() &&
548                 "Load element should sort to front!");
549          I2->setName(I->getName()+".val");
550          LI->replaceAllUsesWith(I2);
551          AA.replaceWithNewValue(LI, I2);
552          LI->eraseFromParent();
553          DOUT << "*** Promoted load of argument '" << I->getName()
554               << "' in function '" << F->getName() << "'\n";
555        } else {
556          GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
557          std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
558
559          Function::arg_iterator TheArg = I2;
560          for (ScalarizeTable::iterator It = ArgIndices.begin();
561               *It != Operands; ++It, ++TheArg) {
562            assert(It != ArgIndices.end() && "GEP not handled??");
563          }
564
565          std::string NewName = I->getName();
566          for (unsigned i = 0, e = Operands.size(); i != e; ++i)
567            if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
568              NewName += "." + CI->getValue().toStringUnsigned(10);
569            else
570              NewName += ".x";
571          TheArg->setName(NewName+".val");
572
573          DOUT << "*** Promoted agg argument '" << TheArg->getName()
574               << "' of function '" << F->getName() << "'\n";
575
576          // All of the uses must be load instructions.  Replace them all with
577          // the argument specified by ArgNo.
578          while (!GEP->use_empty()) {
579            LoadInst *L = cast<LoadInst>(GEP->use_back());
580            L->replaceAllUsesWith(TheArg);
581            AA.replaceWithNewValue(L, TheArg);
582            L->eraseFromParent();
583          }
584          AA.deleteValue(GEP);
585          GEP->eraseFromParent();
586        }
587      }
588
589      // Increment I2 past all of the arguments added for this promoted pointer.
590      for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
591        ++I2;
592    }
593
594  // Notify the alias analysis implementation that we inserted a new argument.
595  if (ExtraArgHack)
596    AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
597
598
599  // Tell the alias analysis that the old function is about to disappear.
600  AA.replaceWithNewValue(F, NF);
601
602  // Now that the old function is dead, delete it.
603  F->eraseFromParent();
604  return NF;
605}
606