blob: 7b5def4284d839caa1e40ba93b71e2bb610ebf19 [file] [log] [blame]
Chris Lattner254f8f82004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Chris Lattner483ae012004-03-07 21:29:54 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
Chris Lattner5065b242004-09-17 03:58:39 +000012// arguments. If we can prove, through the use of alias analysis, that an
Chris Lattner483ae012004-03-07 21:29:54 +000013// argument is *only* loaded, then we can pass the value into the function
14// instead of the address of the value. This can cause recursive simplification
Chris Lattner254f8f82004-05-23 21:21:17 +000015// of code and lead to the elimination of allocas (especially in C++ template
16// code like the STL).
Chris Lattner483ae012004-03-07 21:29:54 +000017//
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000018// 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// we refuse to scalarize aggregates which would require passing in more than
21// three operands to the function, because we don't want to pass thousands of
Chris Lattner254f8f82004-05-23 21:21:17 +000022// operands for a large array or structure!
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000023//
Chris Lattner483ae012004-03-07 21:29:54 +000024// Note that this transformation could also be done for arguments that are only
25// stored to (returning the value instead), but we do not currently handle that
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000026// case. This case would be best handled when and if we start supporting
27// multiple return values from functions.
Chris Lattner483ae012004-03-07 21:29:54 +000028//
29//===----------------------------------------------------------------------===//
30
Chris Lattner254f8f82004-05-23 21:21:17 +000031#define DEBUG_TYPE "argpromotion"
Chris Lattner483ae012004-03-07 21:29:54 +000032#include "llvm/Transforms/IPO.h"
33#include "llvm/Constants.h"
34#include "llvm/DerivedTypes.h"
35#include "llvm/Module.h"
Chris Lattner37b6c4f2004-09-18 00:34:13 +000036#include "llvm/CallGraphSCCPass.h"
Chris Lattner483ae012004-03-07 21:29:54 +000037#include "llvm/Instructions.h"
38#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner37b6c4f2004-09-18 00:34:13 +000039#include "llvm/Analysis/CallGraph.h"
Chris Lattner483ae012004-03-07 21:29:54 +000040#include "llvm/Target/TargetData.h"
41#include "llvm/Support/CallSite.h"
42#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000043#include "llvm/Support/Debug.h"
44#include "llvm/ADT/DepthFirstIterator.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/ADT/StringExtras.h"
Chris Lattner483ae012004-03-07 21:29:54 +000047#include <set>
48using namespace llvm;
49
50namespace {
51 Statistic<> NumArgumentsPromoted("argpromotion",
52 "Number of pointer arguments promoted");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000053 Statistic<> NumAggregatesPromoted("argpromotion",
54 "Number of aggregate arguments promoted");
Chris Lattner483ae012004-03-07 21:29:54 +000055 Statistic<> NumArgumentsDead("argpromotion",
56 "Number of dead pointer args eliminated");
57
58 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59 ///
Chris Lattner37b6c4f2004-09-18 00:34:13 +000060 struct ArgPromotion : public CallGraphSCCPass {
Chris Lattner483ae012004-03-07 21:29:54 +000061 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired<AliasAnalysis>();
63 AU.addRequired<TargetData>();
Chris Lattner37b6c4f2004-09-18 00:34:13 +000064 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattner483ae012004-03-07 21:29:54 +000065 }
66
Chris Lattner37b6c4f2004-09-18 00:34:13 +000067 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Chris Lattner483ae012004-03-07 21:29:54 +000068 private:
Chris Lattner37b6c4f2004-09-18 00:34:13 +000069 bool PromoteArguments(CallGraphNode *CGN);
Chris Lattner483ae012004-03-07 21:29:54 +000070 bool isSafeToPromoteArgument(Argument *Arg) const;
Chris Lattner37b6c4f2004-09-18 00:34:13 +000071 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
Chris Lattner483ae012004-03-07 21:29:54 +000072 };
73
74 RegisterOpt<ArgPromotion> X("argpromotion",
75 "Promote 'by reference' arguments to scalars");
76}
77
78Pass *llvm::createArgumentPromotionPass() {
79 return new ArgPromotion();
80}
81
Chris Lattner37b6c4f2004-09-18 00:34:13 +000082bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
83 bool Changed = false, LocalChange;
Chris Lattner483ae012004-03-07 21:29:54 +000084
Chris Lattner9864df92004-09-19 01:05:16 +000085 do { // Iterate until we stop promoting from this SCC.
Chris Lattner37b6c4f2004-09-18 00:34:13 +000086 LocalChange = false;
87 // Attempt to promote arguments from all functions in this SCC.
88 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
89 LocalChange |= PromoteArguments(SCC[i]);
90 Changed |= LocalChange; // Remember that we changed something.
91 } while (LocalChange);
Chris Lattner483ae012004-03-07 21:29:54 +000092
93 return Changed;
94}
95
Chris Lattner254f8f82004-05-23 21:21:17 +000096/// PromoteArguments - This method checks the specified function to see if there
97/// are any promotable arguments and if it is safe to promote the function (for
98/// example, all callers are direct). If safe to promote some arguments, it
99/// calls the DoPromotion method.
100///
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000101bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
102 Function *F = CGN->getFunction();
103
104 // Make sure that it is local to this module.
105 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattner483ae012004-03-07 21:29:54 +0000106
107 // First check: see if there are any pointer arguments! If not, quick exit.
108 std::vector<Argument*> PointerArgs;
109 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
110 if (isa<PointerType>(I->getType()))
111 PointerArgs.push_back(I);
112 if (PointerArgs.empty()) return false;
113
114 // Second check: make sure that all callers are direct callers. We can't
115 // transform functions that have indirect callers.
116 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner64b8d692004-03-07 22:43:27 +0000117 UI != E; ++UI) {
118 CallSite CS = CallSite::get(*UI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000119 if (!CS.getInstruction()) // "Taking the address" of the function
120 return false;
121
122 // Ensure that this call site is CALLING the function, not passing it as
123 // an argument.
124 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
125 AI != E; ++AI)
126 if (*AI == F) return false; // Passing the function address in!
Chris Lattner64b8d692004-03-07 22:43:27 +0000127 }
Chris Lattner483ae012004-03-07 21:29:54 +0000128
129 // Check to see which arguments are promotable. If an argument is not
130 // promotable, remove it from the PointerArgs vector.
131 for (unsigned i = 0; i != PointerArgs.size(); ++i)
132 if (!isSafeToPromoteArgument(PointerArgs[i])) {
133 std::swap(PointerArgs[i--], PointerArgs.back());
134 PointerArgs.pop_back();
135 }
136
137 // No promotable pointer arguments.
138 if (PointerArgs.empty()) return false;
139
140 // Okay, promote all of the arguments are rewrite the callees!
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000141 Function *NewF = DoPromotion(F, PointerArgs);
142
143 // Update the call graph to know that the old function is gone.
144 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattner483ae012004-03-07 21:29:54 +0000145 return true;
146}
147
Chris Lattner254f8f82004-05-23 21:21:17 +0000148
149/// isSafeToPromoteArgument - As you might guess from the name of this method,
150/// it checks to see if it is both safe and useful to promote the argument.
151/// This method limits promotion of aggregates to only promote up to three
152/// elements of the aggregate in order to avoid exploding the number of
153/// arguments passed in.
Chris Lattner483ae012004-03-07 21:29:54 +0000154bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000155 // We can only promote this argument if all of the uses are loads, or are GEP
156 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner483ae012004-03-07 21:29:54 +0000157 std::vector<LoadInst*> Loads;
Chris Lattner1c676f72004-06-21 00:07:58 +0000158 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattner483ae012004-03-07 21:29:54 +0000159 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
160 UI != E; ++UI)
161 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
162 if (LI->isVolatile()) return false; // Don't hack volatile loads
163 Loads.push_back(LI);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000164 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
165 if (GEP->use_empty()) {
166 // Dead GEP's cause trouble later. Just remove them if we run into
167 // them.
Chris Lattner254f8f82004-05-23 21:21:17 +0000168 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000169 GEP->getParent()->getInstList().erase(GEP);
170 return isSafeToPromoteArgument(Arg);
171 }
172 // Ensure that all of the indices are constants.
Chris Lattner1c676f72004-06-21 00:07:58 +0000173 std::vector<ConstantInt*> Operands;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000174 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattner1c676f72004-06-21 00:07:58 +0000175 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000176 Operands.push_back(C);
177 else
178 return false; // Not a constant operand GEP!
179
180 // Ensure that the only users of the GEP are load instructions.
181 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
182 UI != E; ++UI)
183 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
184 if (LI->isVolatile()) return false; // Don't hack volatile loads
185 Loads.push_back(LI);
186 } else {
187 return false;
188 }
189
Chris Lattner254f8f82004-05-23 21:21:17 +0000190 // See if there is already a GEP with these indices. If not, check to
191 // make sure that we aren't promoting too many elements. If so, nothing
192 // to do.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000193 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
194 GEPIndices.end()) {
195 if (GEPIndices.size() == 3) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000196 DEBUG(std::cerr << "argpromotion disable promoting argument '"
197 << Arg->getName() << "' because it would require adding more "
198 << "than 3 arguments to the function.\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000199 // We limit aggregate promotion to only promoting up to three elements
200 // of the aggregate.
201 return false;
202 }
203 GEPIndices.push_back(Operands);
204 }
205 } else {
206 return false; // Not a load or a GEP.
207 }
Chris Lattner483ae012004-03-07 21:29:54 +0000208
Chris Lattner254f8f82004-05-23 21:21:17 +0000209 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattner483ae012004-03-07 21:29:54 +0000210
Chris Lattner254f8f82004-05-23 21:21:17 +0000211 // Okay, now we know that the argument is only used by load instructions. Use
212 // alias analysis to check to see if the pointer is guaranteed to not be
213 // modified from entry of the function to each of the load instructions.
Chris Lattner483ae012004-03-07 21:29:54 +0000214 Function &F = *Arg->getParent();
215
216 // Because there could be several/many load instructions, remember which
217 // blocks we know to be transparent to the load.
218 std::set<BasicBlock*> TranspBlocks;
219
220 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000221 TargetData &TD = getAnalysis<TargetData>();
Chris Lattner483ae012004-03-07 21:29:54 +0000222
223 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
224 // Check to see if the load is invalidated from the start of the block to
225 // the load itself.
226 LoadInst *Load = Loads[i];
227 BasicBlock *BB = Load->getParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000228
229 const PointerType *LoadTy =
230 cast<PointerType>(Load->getOperand(0)->getType());
231 unsigned LoadSize = TD.getTypeSize(LoadTy->getElementType());
232
Chris Lattner483ae012004-03-07 21:29:54 +0000233 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
234 return false; // Pointer is invalidated!
235
236 // Now check every path from the entry block to the load for transparency.
237 // To do this, we perform a depth first search on the inverse CFG from the
238 // loading block.
239 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
240 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
241 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
242 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
243 return false;
244 }
245
246 // If the path from the entry of the function to each load is free of
247 // instructions that potentially invalidate the load, we can make the
248 // transformation!
249 return true;
250}
251
Chris Lattner1c676f72004-06-21 00:07:58 +0000252namespace {
253 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
254 /// elements are instances of ConstantInt.
255 ///
256 struct GEPIdxComparator {
257 bool operator()(const std::vector<Value*> &LHS,
258 const std::vector<Value*> &RHS) const {
259 unsigned idx = 0;
260 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
261 if (LHS[idx] != RHS[idx]) {
262 return cast<ConstantInt>(LHS[idx])->getRawValue() <
263 cast<ConstantInt>(RHS[idx])->getRawValue();
264 }
265 }
266
267 // Return less than if we ran out of stuff in LHS and we didn't run out of
268 // stuff in RHS.
269 return idx == LHS.size() && idx != RHS.size();
270 }
271 };
272}
273
274
Chris Lattner254f8f82004-05-23 21:21:17 +0000275/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000276/// arguments, and returns the new function. At this point, we know that it's
277/// safe to do so.
278Function *ArgPromotion::DoPromotion(Function *F,
279 std::vector<Argument*> &Args2Prom) {
Chris Lattner483ae012004-03-07 21:29:54 +0000280 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
281
282 // Start by computing a new prototype for the function, which is the same as
283 // the old function, but has modified arguments.
284 const FunctionType *FTy = F->getFunctionType();
285 std::vector<const Type*> Params;
286
Chris Lattner1c676f72004-06-21 00:07:58 +0000287 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
288
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000289 // ScalarizedElements - If we are promoting a pointer that has elements
290 // accessed out of it, keep track of which elements are accessed so that we
291 // can add one argument for each.
292 //
293 // Arguments that are directly loaded will have a zero element value here, to
294 // handle cases where there are both a direct load and GEP accesses.
295 //
Chris Lattner1c676f72004-06-21 00:07:58 +0000296 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000297
Chris Lattner254f8f82004-05-23 21:21:17 +0000298 // OriginalLoads - Keep track of a representative load instruction from the
299 // original function so that we can tell the alias analysis implementation
300 // what the new GEP/Load instructions we are inserting look like.
301 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
302
Chris Lattner483ae012004-03-07 21:29:54 +0000303 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
304 if (!ArgsToPromote.count(I)) {
305 Params.push_back(I->getType());
Chris Lattner254f8f82004-05-23 21:21:17 +0000306 } else if (I->use_empty()) {
307 ++NumArgumentsDead;
308 } else {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000309 // Okay, this is being promoted. Check to see if there are any GEP uses
310 // of the argument.
Chris Lattner1c676f72004-06-21 00:07:58 +0000311 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000312 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
313 ++UI) {
314 Instruction *User = cast<Instruction>(*UI);
315 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
Chris Lattner254f8f82004-05-23 21:21:17 +0000316 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
317 ArgIndices.insert(Indices);
318 LoadInst *OrigLoad;
319 if (LoadInst *L = dyn_cast<LoadInst>(User))
320 OrigLoad = L;
321 else
322 OrigLoad = cast<LoadInst>(User->use_back());
323 OriginalLoads[Indices] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000324 }
325
326 // Add a parameter to the function for each element passed in.
Chris Lattner1c676f72004-06-21 00:07:58 +0000327 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000328 E = ArgIndices.end(); SI != E; ++SI)
329 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
330
331 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
332 ++NumArgumentsPromoted;
333 else
334 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000335 }
336
337 const Type *RetTy = FTy->getReturnType();
338
339 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
340 // have zero fixed arguments.
341 bool ExtraArgHack = false;
342 if (Params.empty() && FTy->isVarArg()) {
343 ExtraArgHack = true;
344 Params.push_back(Type::IntTy);
345 }
346 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
347
348 // Create the new function body and insert it into the module...
349 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
350 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner254f8f82004-05-23 21:21:17 +0000351
352 // Get the alias analysis information that we need to update to reflect our
353 // changes.
354 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
355
Chris Lattner483ae012004-03-07 21:29:54 +0000356 // Loop over all of the callers of the function, transforming the call sites
357 // to pass in the loaded pointers.
358 //
359 std::vector<Value*> Args;
360 while (!F->use_empty()) {
361 CallSite CS = CallSite::get(F->use_back());
362 Instruction *Call = CS.getInstruction();
363
Chris Lattner254f8f82004-05-23 21:21:17 +0000364 // Loop over the operands, inserting GEP and loads in the caller as
365 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000366 CallSite::arg_iterator AI = CS.arg_begin();
367 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
368 if (!ArgsToPromote.count(I))
369 Args.push_back(*AI); // Unmodified argument
370 else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000371 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattner1c676f72004-06-21 00:07:58 +0000372 ScalarizeTable &ArgIndices = ScalarizedElements[I];
373 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000374 E = ArgIndices.end(); SI != E; ++SI) {
375 Value *V = *AI;
Chris Lattner254f8f82004-05-23 21:21:17 +0000376 LoadInst *OrigLoad = OriginalLoads[*SI];
377 if (!SI->empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000378 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
Chris Lattner254f8f82004-05-23 21:21:17 +0000379 AA.copyValue(OrigLoad->getOperand(0), V);
380 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000381 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner254f8f82004-05-23 21:21:17 +0000382 AA.copyValue(OrigLoad, Args.back());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000383 }
Chris Lattner483ae012004-03-07 21:29:54 +0000384 }
385
386 if (ExtraArgHack)
387 Args.push_back(Constant::getNullValue(Type::IntTy));
388
389 // Push any varargs arguments on the list
390 for (; AI != CS.arg_end(); ++AI)
391 Args.push_back(*AI);
392
393 Instruction *New;
394 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
395 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
396 Args, "", Call);
397 } else {
398 New = new CallInst(NF, Args, "", Call);
399 }
400 Args.clear();
401
Chris Lattner254f8f82004-05-23 21:21:17 +0000402 // Update the alias analysis implementation to know that we are replacing
403 // the old call with a new one.
404 AA.replaceWithNewValue(Call, New);
405
Chris Lattner483ae012004-03-07 21:29:54 +0000406 if (!Call->use_empty()) {
407 Call->replaceAllUsesWith(New);
408 std::string Name = Call->getName();
409 Call->setName("");
410 New->setName(Name);
411 }
412
413 // Finally, remove the old call from the program, reducing the use-count of
414 // F.
415 Call->getParent()->getInstList().erase(Call);
416 }
417
418 // Since we have now created the new function, splice the body of the old
419 // function right into the new function, leaving the old rotting hulk of the
420 // function empty.
421 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
422
423 // Loop over the argument list, transfering uses of the old arguments over to
424 // the new arguments, also transfering over the names as well.
425 //
426 for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
427 I != E; ++I)
428 if (!ArgsToPromote.count(I)) {
429 // If this is an unmodified argument, move the name and users over to the
430 // new version.
431 I->replaceAllUsesWith(I2);
432 I2->setName(I->getName());
Chris Lattner254f8f82004-05-23 21:21:17 +0000433 AA.replaceWithNewValue(I, I2);
Chris Lattner483ae012004-03-07 21:29:54 +0000434 ++I2;
Chris Lattner254f8f82004-05-23 21:21:17 +0000435 } else if (I->use_empty()) {
436 AA.deleteValue(I);
437 } else {
Chris Lattner483ae012004-03-07 21:29:54 +0000438 // Otherwise, if we promoted this argument, then all users are load
439 // instructions, and all loads should be using the new argument that we
440 // added.
Chris Lattner1c676f72004-06-21 00:07:58 +0000441 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000442
Chris Lattner483ae012004-03-07 21:29:54 +0000443 while (!I->use_empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000444 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
445 assert(ArgIndices.begin()->empty() &&
446 "Load element should sort to front!");
447 I2->setName(I->getName()+".val");
448 LI->replaceAllUsesWith(I2);
Chris Lattner254f8f82004-05-23 21:21:17 +0000449 AA.replaceWithNewValue(LI, I2);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000450 LI->getParent()->getInstList().erase(LI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000451 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
452 << "' in function '" << F->getName() << "'\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000453 } else {
454 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
455 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
456
457 unsigned ArgNo = 0;
458 Function::aiterator TheArg = I2;
Chris Lattner1c676f72004-06-21 00:07:58 +0000459 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000460 *It != Operands; ++It, ++TheArg) {
461 assert(It != ArgIndices.end() && "GEP not handled??");
462 }
463
464 std::string NewName = I->getName();
465 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
466 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
467 NewName += "."+itostr((int64_t)CI->getRawValue());
468 else
469 NewName += ".x";
470 TheArg->setName(NewName+".val");
471
472 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
473 << "' of function '" << F->getName() << "'\n");
474
475 // All of the uses must be load instructions. Replace them all with
476 // the argument specified by ArgNo.
477 while (!GEP->use_empty()) {
478 LoadInst *L = cast<LoadInst>(GEP->use_back());
479 L->replaceAllUsesWith(TheArg);
Chris Lattner254f8f82004-05-23 21:21:17 +0000480 AA.replaceWithNewValue(L, TheArg);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000481 L->getParent()->getInstList().erase(L);
482 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000483 AA.deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000484 GEP->getParent()->getInstList().erase(GEP);
485 }
Chris Lattner483ae012004-03-07 21:29:54 +0000486 }
Chris Lattnercc544e52004-03-07 22:52:53 +0000487
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000488 // Increment I2 past all of the arguments added for this promoted pointer.
489 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
490 ++I2;
Chris Lattner483ae012004-03-07 21:29:54 +0000491 }
492
Chris Lattner254f8f82004-05-23 21:21:17 +0000493 // Notify the alias analysis implementation that we inserted a new argument.
494 if (ExtraArgHack)
495 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->abegin());
496
497
498 // Tell the alias analysis that the old function is about to disappear.
499 AA.replaceWithNewValue(F, NF);
500
Chris Lattner483ae012004-03-07 21:29:54 +0000501 // Now that the old function is dead, delete it.
502 F->getParent()->getFunctionList().erase(F);
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000503 return NF;
Chris Lattner483ae012004-03-07 21:29:54 +0000504}