1894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//
3894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//                     The LLVM Compiler Infrastructure
4894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//
5894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// This file is distributed under the University of Illinois Open Source
6894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// License. See LICENSE.TXT for details.
7894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//
8894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//===----------------------------------------------------------------------===//
9894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//
10894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// This pass promotes "by reference" arguments to be "by value" arguments.  In
11894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// practice, this means looking for internal functions that have pointer
12894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// arguments.  If it can prove, through the use of alias analysis, that an
13894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// argument is *only* loaded, then it can pass the value into the function
14894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// instead of the address of the value.  This can cause recursive simplification
15894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// of code and lead to the elimination of allocas (especially in C++ template
16894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// code like the STL).
17894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//
18894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// This pass also handles aggregate arguments that are passed into a function,
19894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// scalarizing them if the elements of the aggregate are only loaded.  Note that
20894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// by default it refuses to scalarize aggregates which would require passing in
21894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// more than three operands to the function, because passing thousands of
22894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// operands for a large array or structure is unprofitable! This limit can be
23894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// configured or disabled, however.
24894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//
25894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// Note that this transformation could also be done for arguments that are only
26894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// stored to (returning the value instead), but does not currently.  This case
27894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// would be best handled when and if LLVM begins supporting multiple return
28894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman// values from functions.
29894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//
30894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman//===----------------------------------------------------------------------===//
31894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
32894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#define DEBUG_TYPE "argpromotion"
33894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Transforms/IPO.h"
34894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Constants.h"
35894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/DerivedTypes.h"
36894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Module.h"
37894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/CallGraphSCCPass.h"
38894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Instructions.h"
39894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/LLVMContext.h"
40894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Analysis/AliasAnalysis.h"
41894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Analysis/CallGraph.h"
42894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Support/CallSite.h"
43894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Support/CFG.h"
44894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Support/Debug.h"
45894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/Support/raw_ostream.h"
46894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/ADT/DepthFirstIterator.h"
47894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/ADT/Statistic.h"
48894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include "llvm/ADT/StringExtras.h"
49894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman#include <set>
50894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumanusing namespace llvm;
51894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
52894018228b0e0bdbd7aa7e8f47d4a9458789ca82John BaumanSTATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
53894018228b0e0bdbd7aa7e8f47d4a9458789ca82John BaumanSTATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
54894018228b0e0bdbd7aa7e8f47d4a9458789ca82John BaumanSTATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
55894018228b0e0bdbd7aa7e8f47d4a9458789ca82John BaumanSTATISTIC(NumArgumentsDead     , "Number of dead pointer args eliminated");
56894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
57894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumannamespace {
58894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  ///
60894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  struct ArgPromotion : public CallGraphSCCPass {
61894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      AU.addRequired<AliasAnalysis>();
63894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      CallGraphSCCPass::getAnalysisUsage(AU);
64894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
65894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
66894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    virtual bool runOnSCC(CallGraphSCC &SCC);
67894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    static char ID; // Pass identification, replacement for typeid
68894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    explicit ArgPromotion(unsigned maxElements = 3)
6919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        : CallGraphSCCPass(ID), maxElements(maxElements) {
7019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      initializeArgPromotionPass(*PassRegistry::getPassRegistry());
7119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    }
72894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
73894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    /// A vector used to hold the indices of a single GEP instruction
74894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    typedef std::vector<uint64_t> IndicesVector;
75894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
76894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  private:
77894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    CallGraphNode *PromoteArguments(CallGraphNode *CGN);
78894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
79894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    CallGraphNode *DoPromotion(Function *F,
80894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                               SmallPtrSet<Argument*, 8> &ArgsToPromote,
81894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                               SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
82894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    /// The maximum number of elements to expand, or 0 for unlimited.
83894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    unsigned maxElements;
84894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  };
85894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
86894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
87894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumanchar ArgPromotion::ID = 0;
8819bac1e08be200c31efd26f0f5fd144c9b3eefd3John BaumanINITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
8919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman                "Promote 'by reference' arguments to scalars", false, false)
9019bac1e08be200c31efd26f0f5fd144c9b3eefd3John BaumanINITIALIZE_AG_DEPENDENCY(AliasAnalysis)
9119bac1e08be200c31efd26f0f5fd144c9b3eefd3John BaumanINITIALIZE_AG_DEPENDENCY(CallGraph)
9219bac1e08be200c31efd26f0f5fd144c9b3eefd3John BaumanINITIALIZE_PASS_END(ArgPromotion, "argpromotion",
9319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman                "Promote 'by reference' arguments to scalars", false, false)
94894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
95894018228b0e0bdbd7aa7e8f47d4a9458789ca82John BaumanPass *llvm::createArgumentPromotionPass(unsigned maxElements) {
96894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  return new ArgPromotion(maxElements);
97894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
98894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
99894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumanbool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
100894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  bool Changed = false, LocalChange;
101894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
102894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  do {  // Iterate until we stop promoting from this SCC.
103894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    LocalChange = false;
104894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Attempt to promote arguments from all functions in this SCC.
105894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
106894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (CallGraphNode *CGN = PromoteArguments(*I)) {
107894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        LocalChange = true;
108894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        SCC.ReplaceNode(*I, CGN);
109894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
110894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
111894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Changed |= LocalChange;               // Remember that we changed something.
112894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  } while (LocalChange);
113894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
114894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  return Changed;
115894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
116894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
117894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// PromoteArguments - This method checks the specified function to see if there
118894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// are any promotable arguments and if it is safe to promote the function (for
119894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// example, all callers are direct).  If safe to promote some arguments, it
120894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// calls the DoPromotion method.
121894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman///
122894018228b0e0bdbd7aa7e8f47d4a9458789ca82John BaumanCallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
123894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  Function *F = CGN->getFunction();
124894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
125894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Make sure that it is local to this module.
126894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (!F || !F->hasLocalLinkage()) return 0;
127894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
128894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // First check: see if there are any pointer arguments!  If not, quick exit.
129894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
130894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  unsigned ArgNo = 0;
131894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
132894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman       I != E; ++I, ++ArgNo)
133894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (I->getType()->isPointerTy())
134894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
135894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (PointerArgs.empty()) return 0;
136894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
137894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Second check: make sure that all callers are direct callers.  We can't
13819bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  // transform functions that have indirect callers.  Also see if the function
13919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  // is self-recursive.
14019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  bool isSelfRecursive = false;
14119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
14219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman       UI != E; ++UI) {
14319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    CallSite CS(*UI);
14419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    // Must be a direct call.
14519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    if (CS.getInstruction() == 0 || !CS.isCallee(UI)) return 0;
14619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman
14719bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    if (CS.getInstruction()->getParent()->getParent() == F)
14819bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      isSelfRecursive = true;
14919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  }
15019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman
151894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Check to see which arguments are promotable.  If an argument is promotable,
152894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // add it to ArgsToPromote.
153894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  SmallPtrSet<Argument*, 8> ArgsToPromote;
154894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  SmallPtrSet<Argument*, 8> ByValArgsToTransform;
155894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (unsigned i = 0; i != PointerArgs.size(); ++i) {
156894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    bool isByVal = F->paramHasAttr(PointerArgs[i].second+1, Attribute::ByVal);
15719bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    Argument *PtrArg = PointerArgs[i].first;
15819bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
159894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
160894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // If this is a byval argument, and if the aggregate type is small, just
161894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // pass the elements, which is always safe.
162894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (isByVal) {
16319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      if (StructType *STy = dyn_cast<StructType>(AgTy)) {
164894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (maxElements > 0 && STy->getNumElements() > maxElements) {
165894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          DEBUG(dbgs() << "argpromotion disable promoting argument '"
166894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                << PtrArg->getName() << "' because it would require adding more"
167894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                << " than " << maxElements << " arguments to the function.\n");
16819bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          continue;
16919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        }
17019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman
17119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        // If all the elements are single-value types, we can promote it.
17219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        bool AllSimple = true;
17319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
17419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          if (!STy->getElementType(i)->isSingleValueType()) {
17519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman            AllSimple = false;
17619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman            break;
177894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          }
178894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
17919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman
18019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        // Safe to transform, don't even bother trying to "promote" it.
18119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        // Passing the elements as a scalar will allow scalarrepl to hack on
18219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        // the new alloca we introduce.
18319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        if (AllSimple) {
18419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          ByValArgsToTransform.insert(PtrArg);
18519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          continue;
18619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        }
187894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
188894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
189894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
19019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    // If the argument is a recursive type and we're in a recursive
19119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    // function, we could end up infinitely peeling the function argument.
19219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    if (isSelfRecursive) {
19319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      if (StructType *STy = dyn_cast<StructType>(AgTy)) {
19419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        bool RecursiveType = false;
19519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
19619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          if (STy->getElementType(i) == PtrArg->getType()) {
19719bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman            RecursiveType = true;
19819bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman            break;
19919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          }
20019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        }
20119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        if (RecursiveType)
20219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          continue;
20319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      }
20419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    }
20519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman
206894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Otherwise, see if we can promote the pointer to its value.
207894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (isSafeToPromoteArgument(PtrArg, isByVal))
208894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      ArgsToPromote.insert(PtrArg);
209894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
210894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
211894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // No promotable pointer arguments.
212894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
213894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    return 0;
214894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
215894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  return DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
216894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
217894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
21819bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman/// AllCallersPassInValidPointerForArgument - Return true if we can prove that
219894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// all callees pass in a valid pointer for the specified function argument.
22019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Baumanstatic bool AllCallersPassInValidPointerForArgument(Argument *Arg) {
221894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  Function *Callee = Arg->getParent();
222894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
223894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  unsigned ArgNo = std::distance(Callee->arg_begin(),
224894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                 Function::arg_iterator(Arg));
225894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
226894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Look at all call sites of the function.  At this pointer we know we only
227894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // have direct callees.
228894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
229894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman       UI != E; ++UI) {
230894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    CallSite CS(*UI);
231894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    assert(CS && "Should only have direct calls!");
232894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
23319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    if (!CS.getArgument(ArgNo)->isDereferenceablePointer())
234894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      return false;
235894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
236894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  return true;
237894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
238894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
239894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// Returns true if Prefix is a prefix of longer. That means, Longer has a size
240894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// that is greater than or equal to the size of prefix, and each of the
241894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// elements in Prefix is the same as the corresponding elements in Longer.
242894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman///
243894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// This means it also returns true when Prefix and Longer are equal!
244894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumanstatic bool IsPrefix(const ArgPromotion::IndicesVector &Prefix,
245894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                     const ArgPromotion::IndicesVector &Longer) {
246894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Prefix.size() > Longer.size())
247894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    return false;
248894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (unsigned i = 0, e = Prefix.size(); i != e; ++i)
249894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (Prefix[i] != Longer[i])
250894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      return false;
251894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  return true;
252894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
253894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
254894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
255894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// Checks if Indices, or a prefix of Indices, is in Set.
256894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumanstatic bool PrefixIn(const ArgPromotion::IndicesVector &Indices,
257894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                     std::set<ArgPromotion::IndicesVector> &Set) {
258894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    std::set<ArgPromotion::IndicesVector>::iterator Low;
259894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Low = Set.upper_bound(Indices);
260894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (Low != Set.begin())
261894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Low--;
262894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Low is now the last element smaller than or equal to Indices. This means
263894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // it points to a prefix of Indices (possibly Indices itself), if such
264894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // prefix exists.
265894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    //
266894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // This load is safe if any prefix of its operands is safe to load.
267894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    return Low != Set.end() && IsPrefix(*Low, Indices);
268894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
269894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
270894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// Mark the given indices (ToMark) as safe in the given set of indices
271894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
272894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// is already a prefix of Indices in Safe, Indices are implicitely marked safe
273894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// already. Furthermore, any indices that Indices is itself a prefix of, are
274894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// removed from Safe (since they are implicitely safe because of Indices now).
275894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumanstatic void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark,
276894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                            std::set<ArgPromotion::IndicesVector> &Safe) {
277894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  std::set<ArgPromotion::IndicesVector>::iterator Low;
278894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  Low = Safe.upper_bound(ToMark);
279894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Guard against the case where Safe is empty
280894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Low != Safe.begin())
281894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Low--;
282894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Low is now the last element smaller than or equal to Indices. This
283894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // means it points to a prefix of Indices (possibly Indices itself), if
284894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // such prefix exists.
285894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Low != Safe.end()) {
286894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (IsPrefix(*Low, ToMark))
287894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // If there is already a prefix of these indices (or exactly these
288894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // indices) marked a safe, don't bother adding these indices
289894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      return;
290894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
291894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Increment Low, so we can use it as a "insert before" hint
292894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    ++Low;
293894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
294894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Insert
295894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  Low = Safe.insert(Low, ToMark);
296894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  ++Low;
297894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // If there we're a prefix of longer index list(s), remove those
298894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end();
299894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  while (Low != End && IsPrefix(ToMark, *Low)) {
300894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    std::set<ArgPromotion::IndicesVector>::iterator Remove = Low;
301894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    ++Low;
302894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Safe.erase(Remove);
303894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
304894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
305894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
306894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// isSafeToPromoteArgument - As you might guess from the name of this method,
307894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// it checks to see if it is both safe and useful to promote the argument.
308894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// This method limits promotion of aggregates to only promote up to three
309894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// elements of the aggregate in order to avoid exploding the number of
310894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// arguments passed in.
311894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Baumanbool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
312894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  typedef std::set<IndicesVector> GEPIndicesSet;
313894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
314894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Quick exit for unused arguments
315894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Arg->use_empty())
316894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    return true;
317894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
318894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // We can only promote this argument if all of the uses are loads, or are GEP
319894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // instructions (with constant indices) that are subsequently loaded.
320894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  //
321894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Promoting the argument causes it to be loaded in the caller
322894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // unconditionally. This is only safe if we can prove that either the load
323894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // would have happened in the callee anyway (ie, there is a load in the entry
324894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // block) or the pointer passed in at every call site is guaranteed to be
325894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // valid.
326894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // In the former case, invalid loads can happen, but would have happened
327894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // anyway, in the latter case, invalid loads won't happen. This prevents us
328894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // from introducing an invalid load that wouldn't have happened in the
329894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // original code.
330894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  //
331894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // This set will contain all sets of indices that are loaded in the entry
332894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // block, and thus are safe to unconditionally load in the caller.
333894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  GEPIndicesSet SafeToUnconditionallyLoad;
334894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
335894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // This set contains all the sets of indices that we are planning to promote.
336894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // This makes it possible to limit the number of arguments added.
337894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  GEPIndicesSet ToPromote;
338894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
339894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // If the pointer is always valid, any load with first index 0 is valid.
34019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  if (isByVal || AllCallersPassInValidPointerForArgument(Arg))
341894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
342894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
343894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // First, iterate the entry block and mark loads of (geps of) arguments as
344894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // safe.
345894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  BasicBlock *EntryBlock = Arg->getParent()->begin();
346894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Declare this here so we can reuse it
347894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  IndicesVector Indices;
348894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end();
349894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman       I != E; ++I)
350894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
351894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Value *V = LI->getPointerOperand();
352894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
353894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        V = GEP->getPointerOperand();
354894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (V == Arg) {
355894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          // This load actually loads (part of) Arg? Check the indices then.
356894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Indices.reserve(GEP->getNumIndices());
357894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
358894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman               II != IE; ++II)
359894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
360894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              Indices.push_back(CI->getSExtValue());
361894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            else
362894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              // We found a non-constant GEP index for this argument? Bail out
363894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              // right away, can't promote this argument at all.
364894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              return false;
365894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
366894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          // Indices checked out, mark them as safe
367894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          MarkIndicesSafe(Indices, SafeToUnconditionallyLoad);
368894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Indices.clear();
369894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
370894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      } else if (V == Arg) {
371894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // Direct loads are equivalent to a GEP with a single 0 index.
372894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
373894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
374894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
375894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
376894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Now, iterate all uses of the argument to see if there are any uses that are
377894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
378894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  SmallVector<LoadInst*, 16> Loads;
379894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  IndicesVector Operands;
380894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
381894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman       UI != E; ++UI) {
382894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    User *U = *UI;
383894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Operands.clear();
384894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
38519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      // Don't hack volatile/atomic loads
38619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      if (!LI->isSimple()) return false;
387894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Loads.push_back(LI);
388894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Direct loads are equivalent to a GEP with a zero index and then a load.
389894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Operands.push_back(0);
390894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
391894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (GEP->use_empty()) {
392894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // Dead GEP's cause trouble later.  Just remove them if we run into
393894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // them.
394894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        getAnalysis<AliasAnalysis>().deleteValue(GEP);
395894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        GEP->eraseFromParent();
396894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // TODO: This runs the above loop over and over again for dead GEPs
397894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // Couldn't we just do increment the UI iterator earlier and erase the
398894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // use?
399894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        return isSafeToPromoteArgument(Arg, isByVal);
400894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
401894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
402894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Ensure that all of the indices are constants.
403894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end();
404894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        i != e; ++i)
405894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
406894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Operands.push_back(C->getSExtValue());
407894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        else
408894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          return false;  // Not a constant operand GEP!
409894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
410894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Ensure that the only users of the GEP are load instructions.
411894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
412894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman           UI != E; ++UI)
413894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
41419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          // Don't hack volatile/atomic loads
41519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          if (!LI->isSimple()) return false;
416894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Loads.push_back(LI);
417894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        } else {
418894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          // Other uses than load?
419894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          return false;
420894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
421894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    } else {
422894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      return false;  // Not a load or a GEP.
423894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
424894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
425894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Now, see if it is safe to promote this load / loads of this GEP. Loading
426894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // is safe if Operands, or a prefix of Operands, is marked as safe.
427894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (!PrefixIn(Operands, SafeToUnconditionallyLoad))
428894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      return false;
429894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
430894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // See if we are already promoting a load with these indices. If not, check
431894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // to make sure that we aren't promoting too many elements.  If so, nothing
432894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // to do.
433894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (ToPromote.find(Operands) == ToPromote.end()) {
434894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (maxElements > 0 && ToPromote.size() == maxElements) {
435894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        DEBUG(dbgs() << "argpromotion not promoting argument '"
436894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              << Arg->getName() << "' because it would require adding more "
437894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              << "than " << maxElements << " arguments to the function.\n");
438894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // We limit aggregate promotion to only promoting up to a fixed number
439894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // of elements of the aggregate.
440894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        return false;
441894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
442894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      ToPromote.insert(Operands);
443894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
444894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
445894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
446894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Loads.empty()) return true;  // No users, this is a dead argument.
447894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
448894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Okay, now we know that the argument is only used by load instructions and
449894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // it is safe to unconditionally perform all of them. Use alias analysis to
450894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // check to see if the pointer is guaranteed to not be modified from entry of
451894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // the function to each of the load instructions.
452894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
453894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Because there could be several/many load instructions, remember which
454894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // blocks we know to be transparent to the load.
455894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  SmallPtrSet<BasicBlock*, 16> TranspBlocks;
456894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
457894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
458894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
459894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
460894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Check to see if the load is invalidated from the start of the block to
461894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // the load itself.
462894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    LoadInst *Load = Loads[i];
463894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    BasicBlock *BB = Load->getParent();
464894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
46519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    AliasAnalysis::Location Loc = AA.getLocation(Load);
46619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman    if (AA.canInstructionRangeModify(BB->front(), *Load, Loc))
467894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      return false;  // Pointer is invalidated!
468894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
469894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Now check every path from the entry block to the load for transparency.
470894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // To do this, we perform a depth first search on the inverse CFG from the
471894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // loading block.
472894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
473894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      BasicBlock *P = *PI;
474894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
475894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman             I = idf_ext_begin(P, TranspBlocks),
476894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman             E = idf_ext_end(P, TranspBlocks); I != E; ++I)
47719bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        if (AA.canBasicBlockModify(**I, Loc))
478894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          return false;
479894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
480894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
481894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
482894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // If the path from the entry of the function to each load is free of
483894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // instructions that potentially invalidate the load, we can make the
484894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // transformation!
485894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  return true;
486894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
487894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
488894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// DoPromotion - This method actually performs the promotion of the specified
489894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// arguments, and returns the new function.  At this point, we know that it's
490894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman/// safe to do so.
491894018228b0e0bdbd7aa7e8f47d4a9458789ca82John BaumanCallGraphNode *ArgPromotion::DoPromotion(Function *F,
492894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                               SmallPtrSet<Argument*, 8> &ArgsToPromote,
493894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                              SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
494894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
495894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Start by computing a new prototype for the function, which is the same as
496894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // the old function, but has modified arguments.
49719bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  FunctionType *FTy = F->getFunctionType();
49819bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  std::vector<Type*> Params;
499894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
500894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  typedef std::set<IndicesVector> ScalarizeTable;
501894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
502894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // ScalarizedElements - If we are promoting a pointer that has elements
503894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // accessed out of it, keep track of which elements are accessed so that we
504894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // can add one argument for each.
505894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  //
506894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Arguments that are directly loaded will have a zero element value here, to
507894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // handle cases where there are both a direct load and GEP accesses.
508894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  //
509894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  std::map<Argument*, ScalarizeTable> ScalarizedElements;
510894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
511894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // OriginalLoads - Keep track of a representative load instruction from the
512894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // original function so that we can tell the alias analysis implementation
513894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // what the new GEP/Load instructions we are inserting look like.
514894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  std::map<IndicesVector, LoadInst*> OriginalLoads;
515894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
516894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Attributes - Keep track of the parameter attributes for the arguments
517894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // that we are *not* promoting. For the ones that we do promote, the parameter
518894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // attributes are lost
519894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  SmallVector<AttributeWithIndex, 8> AttributesVec;
520894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  const AttrListPtr &PAL = F->getAttributes();
521894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
522894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Add any return attributes.
523894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Attributes attrs = PAL.getRetAttributes())
524894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
525894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
526894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // First, determine the new argument list
527894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  unsigned ArgIndex = 1;
528894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
529894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman       ++I, ++ArgIndex) {
530894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (ByValArgsToTransform.count(I)) {
531894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Simple byval argument? Just add all the struct element types.
53219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      Type *AgTy = cast<PointerType>(I->getType())->getElementType();
53319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      StructType *STy = cast<StructType>(AgTy);
534894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
535894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Params.push_back(STy->getElementType(i));
536894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      ++NumByValArgsPromoted;
537894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    } else if (!ArgsToPromote.count(I)) {
538894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Unchanged argument
539894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Params.push_back(I->getType());
540894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (Attributes attrs = PAL.getParamAttributes(ArgIndex))
541894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        AttributesVec.push_back(AttributeWithIndex::get(Params.size(), attrs));
542894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    } else if (I->use_empty()) {
543894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Dead argument (which are always marked as promotable)
544894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      ++NumArgumentsDead;
545894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    } else {
546894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Okay, this is being promoted. This means that the only uses are loads
547894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // or GEPs which are only used by loads
548894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
549894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // In this table, we will track which indices are loaded from the argument
550894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // (where direct loads are tracked as no indices).
551894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      ScalarizeTable &ArgIndices = ScalarizedElements[I];
552894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
553894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman           ++UI) {
554894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Instruction *User = cast<Instruction>(*UI);
555894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
556894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        IndicesVector Indices;
557894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Indices.reserve(User->getNumOperands() - 1);
558894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // Since loads will only have a single operand, and GEPs only a single
559894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // non-index operand, this will record direct loads without any indices,
560894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // and gep+loads with the GEP indices.
561894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        for (User::op_iterator II = User->op_begin() + 1, IE = User->op_end();
562894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman             II != IE; ++II)
563894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
564894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // GEPs with a single 0 index can be merged with direct loads
565894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (Indices.size() == 1 && Indices.front() == 0)
566894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Indices.clear();
567894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        ArgIndices.insert(Indices);
568894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        LoadInst *OrigLoad;
569894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (LoadInst *L = dyn_cast<LoadInst>(User))
570894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          OrigLoad = L;
571894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        else
572894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          // Take any load, we will use it only to update Alias Analysis
573894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          OrigLoad = cast<LoadInst>(User->use_back());
574894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        OriginalLoads[Indices] = OrigLoad;
575894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
576894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
577894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Add a parameter to the function for each element passed in.
578894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      for (ScalarizeTable::iterator SI = ArgIndices.begin(),
579894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman             E = ArgIndices.end(); SI != E; ++SI) {
580894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // not allowed to dereference ->begin() if size() is 0
58119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
582894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        assert(Params.back());
583894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
584894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
585894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
586894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        ++NumArgumentsPromoted;
587894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      else
588894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        ++NumAggregatesPromoted;
589894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
590894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
591894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
592894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Add any function attributes.
593894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Attributes attrs = PAL.getFnAttributes())
594894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
595894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
59619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  Type *RetTy = FTy->getReturnType();
597894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
598894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
599894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // have zero fixed arguments.
600894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  bool ExtraArgHack = false;
601894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (Params.empty() && FTy->isVarArg()) {
602894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    ExtraArgHack = true;
603894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Params.push_back(Type::getInt32Ty(F->getContext()));
604894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
605894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
606894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Construct the new function type using the new arguments.
607894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
608894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
609894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Create the new function body and insert it into the module.
610894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
611894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  NF->copyAttributesFrom(F);
612894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
613894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
614894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  DEBUG(dbgs() << "ARG PROMOTION:  Promoting to:" << *NF << "\n"
615894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        << "From: " << *F);
616894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
617894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Recompute the parameter attributes list based on the new arguments for
618894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // the function.
619894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  NF->setAttributes(AttrListPtr::get(AttributesVec.begin(),
620894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                     AttributesVec.end()));
621894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  AttributesVec.clear();
622894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
623894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  F->getParent()->getFunctionList().insert(F, NF);
624894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  NF->takeName(F);
625894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
626894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Get the alias analysis information that we need to update to reflect our
627894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // changes.
628894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
629894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
630894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Get the callgraph information that we need to update to reflect our
631894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // changes.
632894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  CallGraph &CG = getAnalysis<CallGraph>();
633894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
634894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Get a new callgraph node for NF.
635894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
636894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
637894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Loop over all of the callers of the function, transforming the call sites
638894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // to pass in the loaded pointers.
639894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  //
640894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  SmallVector<Value*, 16> Args;
641894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  while (!F->use_empty()) {
642894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    CallSite CS(F->use_back());
643894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    assert(CS.getCalledFunction() == F);
644894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Instruction *Call = CS.getInstruction();
645894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    const AttrListPtr &CallPAL = CS.getAttributes();
646894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
647894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Add any return attributes.
648894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (Attributes attrs = CallPAL.getRetAttributes())
649894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
650894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
651894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Loop over the operands, inserting GEP and loads in the caller as
652894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // appropriate.
653894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    CallSite::arg_iterator AI = CS.arg_begin();
654894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    ArgIndex = 1;
655894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
656894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman         I != E; ++I, ++AI, ++ArgIndex)
657894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
658894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Args.push_back(*AI);          // Unmodified argument
659894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
660894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (Attributes Attrs = CallPAL.getParamAttributes(ArgIndex))
661894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
662894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
663894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      } else if (ByValArgsToTransform.count(I)) {
664894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // Emit a GEP and load for each element of the struct.
66519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        Type *AgTy = cast<PointerType>(I->getType())->getElementType();
66619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman        StructType *STy = cast<StructType>(AgTy);
667894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Value *Idxs[2] = {
668894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
669894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
670894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
67119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          Value *Idx = GetElementPtrInst::Create(*AI, Idxs,
672894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                                 (*AI)->getName()+"."+utostr(i),
673894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                                 Call);
674894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          // TODO: Tell AA about the new values?
675894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
676894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
677894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      } else if (!I->use_empty()) {
678894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // Non-dead argument: insert GEPs and loads as appropriate.
679894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        ScalarizeTable &ArgIndices = ScalarizedElements[I];
680894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // Store the Value* version of the indices in here, but declare it now
681894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // for reuse.
682894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        std::vector<Value*> Ops;
683894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        for (ScalarizeTable::iterator SI = ArgIndices.begin(),
684894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman               E = ArgIndices.end(); SI != E; ++SI) {
685894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Value *V = *AI;
686894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          LoadInst *OrigLoad = OriginalLoads[*SI];
687894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          if (!SI->empty()) {
688894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            Ops.reserve(SI->size());
68919bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman            Type *ElTy = V->getType();
690894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            for (IndicesVector::const_iterator II = SI->begin(),
691894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                 IE = SI->end(); II != IE; ++II) {
692894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              // Use i32 to index structs, and i64 for others (pointers/arrays).
693894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              // This satisfies GEP constraints.
69419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman              Type *IdxTy = (ElTy->isStructTy() ?
695894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                    Type::getInt32Ty(F->getContext()) :
696894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                    Type::getInt64Ty(F->getContext()));
697894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              Ops.push_back(ConstantInt::get(IdxTy, *II));
698894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              // Keep track of the type we're currently indexing.
699894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II);
700894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            }
701894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            // And create a GEP to extract those indices.
70219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman            V = GetElementPtrInst::Create(V, Ops, V->getName()+".idx", Call);
703894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            Ops.clear();
704894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            AA.copyValue(OrigLoad->getOperand(0), V);
705894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          }
706894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          // Since we're replacing a load make sure we take the alignment
707894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          // of the previous load.
708894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call);
709894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          newLoad->setAlignment(OrigLoad->getAlignment());
71019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          // Transfer the TBAA info too.
71119bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          newLoad->setMetadata(LLVMContext::MD_tbaa,
71219bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman                               OrigLoad->getMetadata(LLVMContext::MD_tbaa));
713894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Args.push_back(newLoad);
714894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          AA.copyValue(OrigLoad, Args.back());
715894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
716894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
717894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
718894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (ExtraArgHack)
719894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Args.push_back(Constant::getNullValue(Type::getInt32Ty(F->getContext())));
720894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
721894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Push any varargs arguments on the list.
722894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
723894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Args.push_back(*AI);
724894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (Attributes Attrs = CallPAL.getParamAttributes(ArgIndex))
725894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        AttributesVec.push_back(AttributeWithIndex::get(Args.size(), Attrs));
726894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
727894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
728894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Add any function attributes.
729894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (Attributes attrs = CallPAL.getFnAttributes())
730894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
731894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
732894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Instruction *New;
733894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
734894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
73519bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman                               Args, "", Call);
736894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
737894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      cast<InvokeInst>(New)->setAttributes(AttrListPtr::get(AttributesVec.begin(),
738894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                                          AttributesVec.end()));
739894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    } else {
74019bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      New = CallInst::Create(NF, Args, "", Call);
741894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
742894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      cast<CallInst>(New)->setAttributes(AttrListPtr::get(AttributesVec.begin(),
743894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                                        AttributesVec.end()));
744894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (cast<CallInst>(Call)->isTailCall())
745894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        cast<CallInst>(New)->setTailCall();
746894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
747894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Args.clear();
748894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    AttributesVec.clear();
749894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
750894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Update the alias analysis implementation to know that we are replacing
751894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // the old call with a new one.
752894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    AA.replaceWithNewValue(Call, New);
753894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
754894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Update the callgraph to know that the callsite has been transformed.
755894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
756894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    CalleeNode->replaceCallEdge(Call, New, NF_CGN);
757894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
758894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (!Call->use_empty()) {
759894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Call->replaceAllUsesWith(New);
760894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      New->takeName(Call);
761894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
762894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
763894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Finally, remove the old call from the program, reducing the use-count of
764894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // F.
765894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    Call->eraseFromParent();
766894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
767894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
768894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Since we have now created the new function, splice the body of the old
769894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // function right into the new function, leaving the old rotting hulk of the
770894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // function empty.
771894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
772894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
77319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  // Loop over the argument list, transferring uses of the old arguments over to
77419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman  // the new arguments, also transferring over the names as well.
775894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  //
776894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
777894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman       I2 = NF->arg_begin(); I != E; ++I) {
778894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
779894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // If this is an unmodified argument, move the name and users over to the
780894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // new version.
781894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      I->replaceAllUsesWith(I2);
782894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      I2->takeName(I);
783894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      AA.replaceWithNewValue(I, I2);
784894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      ++I2;
785894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      continue;
786894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
787894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
788894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (ByValArgsToTransform.count(I)) {
789894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // In the callee, we create an alloca, and store each of the new incoming
790894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // arguments into the alloca.
791894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Instruction *InsertPt = NF->begin()->begin();
792894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
793894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Just add all the struct element types.
79419bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      Type *AgTy = cast<PointerType>(I->getType())->getElementType();
795894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
79619bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman      StructType *STy = cast<StructType>(AgTy);
797894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      Value *Idxs[2] = {
798894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 0 };
799894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
800894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
801894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
802894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Value *Idx =
80319bac1e08be200c31efd26f0f5fd144c9b3eefd3John Bauman          GetElementPtrInst::Create(TheAlloca, Idxs,
804894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                    TheAlloca->getName()+"."+Twine(i),
805894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                                    InsertPt);
806894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        I2->setName(I->getName()+"."+Twine(i));
807894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        new StoreInst(I2++, Idx, InsertPt);
808894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
809894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
810894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      // Anything that used the arg should now use the alloca.
811894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      I->replaceAllUsesWith(TheAlloca);
812894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      TheAlloca->takeName(I);
813894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      AA.replaceWithNewValue(I, TheAlloca);
814894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      continue;
815894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
816894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
817894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    if (I->use_empty()) {
818894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      AA.deleteValue(I);
819894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      continue;
820894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
821894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
822894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Otherwise, if we promoted this argument, then all users are load
823894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // instructions (or GEPs with only load users), and all loads should be
824894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // using the new argument that we added.
825894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    ScalarizeTable &ArgIndices = ScalarizedElements[I];
826894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
827894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    while (!I->use_empty()) {
828894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
829894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        assert(ArgIndices.begin()->empty() &&
830894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman               "Load element should sort to front!");
831894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        I2->setName(I->getName()+".val");
832894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        LI->replaceAllUsesWith(I2);
833894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        AA.replaceWithNewValue(LI, I2);
834894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        LI->eraseFromParent();
835894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
836894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              << "' in function '" << F->getName() << "'\n");
837894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      } else {
838894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
839894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        IndicesVector Operands;
840894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Operands.reserve(GEP->getNumIndices());
841894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
842894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman             II != IE; ++II)
843894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
844894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
845894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // GEPs with a single 0 index can be merged with direct loads
846894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        if (Operands.size() == 1 && Operands.front() == 0)
847894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          Operands.clear();
848894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
849894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        Function::arg_iterator TheArg = I2;
850894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        for (ScalarizeTable::iterator It = ArgIndices.begin();
851894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman             *It != Operands; ++It, ++TheArg) {
852894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          assert(It != ArgIndices.end() && "GEP not handled??");
853894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
854894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
855894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        std::string NewName = I->getName();
856894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
857894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman            NewName += "." + utostr(Operands[i]);
858894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
859894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        NewName += ".val";
860894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        TheArg->setName(NewName);
861894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
862894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
863894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman              << "' of function '" << NF->getName() << "'\n");
864894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
865894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // All of the uses must be load instructions.  Replace them all with
866894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        // the argument specified by ArgNo.
867894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        while (!GEP->use_empty()) {
868894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          LoadInst *L = cast<LoadInst>(GEP->use_back());
869894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          L->replaceAllUsesWith(TheArg);
870894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          AA.replaceWithNewValue(L, TheArg);
871894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman          L->eraseFromParent();
872894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        }
873894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        AA.deleteValue(GEP);
874894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman        GEP->eraseFromParent();
875894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      }
876894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    }
877894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
878894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    // Increment I2 past all of the arguments added for this promoted pointer.
879894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
880894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman      ++I2;
881894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  }
882894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
883894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Notify the alias analysis implementation that we inserted a new argument.
884894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (ExtraArgHack)
885894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    AA.copyValue(Constant::getNullValue(Type::getInt32Ty(F->getContext())),
886894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman                 NF->arg_begin());
887894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
888894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
889894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Tell the alias analysis that the old function is about to disappear.
890894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  AA.replaceWithNewValue(F, NF);
891894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
892894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
893894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  NF_CGN->stealCalledFunctionsFrom(CG[F]);
894894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
895894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // Now that the old function is dead, delete it.  If there is a dangling
896894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // reference to the CallgraphNode, just leave the dead function around for
897894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  // someone else to nuke.
898894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  CallGraphNode *CGN = CG[F];
899894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  if (CGN->getNumReferences() == 0)
900894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    delete CG.removeFunctionFromModule(CGN);
901894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  else
902894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman    F->setLinkage(Function::ExternalLinkage);
903894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman
904894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman  return NF_CGN;
905894018228b0e0bdbd7aa7e8f47d4a9458789ca82John Bauman}
906