blob: b6ae4e2a22ab6227341d6447206044ebffe4bf14 [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"
36#include "llvm/Pass.h"
37#include "llvm/Instructions.h"
38#include "llvm/Analysis/AliasAnalysis.h"
39#include "llvm/Target/TargetData.h"
40#include "llvm/Support/CallSite.h"
41#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000042#include "llvm/Support/Debug.h"
43#include "llvm/ADT/DepthFirstIterator.h"
44#include "llvm/ADT/Statistic.h"
45#include "llvm/ADT/StringExtras.h"
Chris Lattner483ae012004-03-07 21:29:54 +000046#include <set>
47using namespace llvm;
48
49namespace {
50 Statistic<> NumArgumentsPromoted("argpromotion",
51 "Number of pointer arguments promoted");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000052 Statistic<> NumAggregatesPromoted("argpromotion",
53 "Number of aggregate arguments promoted");
Chris Lattner483ae012004-03-07 21:29:54 +000054 Statistic<> NumArgumentsDead("argpromotion",
55 "Number of dead pointer args eliminated");
56
57 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
58 ///
59 class ArgPromotion : public Pass {
60 // WorkList - The set of internal functions that we have yet to process. As
61 // we eliminate arguments from a function, we push all callers into this set
Chris Lattner254f8f82004-05-23 21:21:17 +000062 // so that the by-reference argument can be bubbled out as far as possible.
Chris Lattner483ae012004-03-07 21:29:54 +000063 // This set contains only internal functions.
64 std::set<Function*> WorkList;
65 public:
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<AliasAnalysis>();
68 AU.addRequired<TargetData>();
69 }
70
71 virtual bool run(Module &M);
72 private:
73 bool PromoteArguments(Function *F);
74 bool isSafeToPromoteArgument(Argument *Arg) const;
75 void DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
76 };
77
78 RegisterOpt<ArgPromotion> X("argpromotion",
79 "Promote 'by reference' arguments to scalars");
80}
81
82Pass *llvm::createArgumentPromotionPass() {
83 return new ArgPromotion();
84}
85
86bool ArgPromotion::run(Module &M) {
87 bool Changed = false;
88 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Reid Spencer83cae642004-07-18 00:23:51 +000089 if (I->hasInternalLinkage())
Chris Lattner483ae012004-03-07 21:29:54 +000090 WorkList.insert(I);
Chris Lattner483ae012004-03-07 21:29:54 +000091
92 while (!WorkList.empty()) {
93 Function *F = *WorkList.begin();
94 WorkList.erase(WorkList.begin());
95
96 if (PromoteArguments(F)) // Attempt to promote an argument.
97 Changed = true; // Remember that we changed something.
98 }
99
100 return Changed;
101}
102
Chris Lattner254f8f82004-05-23 21:21:17 +0000103/// PromoteArguments - This method checks the specified function to see if there
104/// are any promotable arguments and if it is safe to promote the function (for
105/// example, all callers are direct). If safe to promote some arguments, it
106/// calls the DoPromotion method.
107///
Chris Lattner483ae012004-03-07 21:29:54 +0000108bool ArgPromotion::PromoteArguments(Function *F) {
109 assert(F->hasInternalLinkage() && "We can only process internal functions!");
110
111 // First check: see if there are any pointer arguments! If not, quick exit.
112 std::vector<Argument*> PointerArgs;
113 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
114 if (isa<PointerType>(I->getType()))
115 PointerArgs.push_back(I);
116 if (PointerArgs.empty()) return false;
117
118 // Second check: make sure that all callers are direct callers. We can't
119 // transform functions that have indirect callers.
120 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner64b8d692004-03-07 22:43:27 +0000121 UI != E; ++UI) {
122 CallSite CS = CallSite::get(*UI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000123 if (!CS.getInstruction()) // "Taking the address" of the function
124 return false;
125
126 // Ensure that this call site is CALLING the function, not passing it as
127 // an argument.
128 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
129 AI != E; ++AI)
130 if (*AI == F) return false; // Passing the function address in!
Chris Lattner64b8d692004-03-07 22:43:27 +0000131 }
Chris Lattner483ae012004-03-07 21:29:54 +0000132
133 // Check to see which arguments are promotable. If an argument is not
134 // promotable, remove it from the PointerArgs vector.
135 for (unsigned i = 0; i != PointerArgs.size(); ++i)
136 if (!isSafeToPromoteArgument(PointerArgs[i])) {
137 std::swap(PointerArgs[i--], PointerArgs.back());
138 PointerArgs.pop_back();
139 }
140
141 // No promotable pointer arguments.
142 if (PointerArgs.empty()) return false;
143
144 // Okay, promote all of the arguments are rewrite the callees!
145 DoPromotion(F, PointerArgs);
146 return true;
147}
148
Chris Lattner254f8f82004-05-23 21:21:17 +0000149
150/// isSafeToPromoteArgument - As you might guess from the name of this method,
151/// it checks to see if it is both safe and useful to promote the argument.
152/// This method limits promotion of aggregates to only promote up to three
153/// elements of the aggregate in order to avoid exploding the number of
154/// arguments passed in.
Chris Lattner483ae012004-03-07 21:29:54 +0000155bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000156 // We can only promote this argument if all of the uses are loads, or are GEP
157 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner483ae012004-03-07 21:29:54 +0000158 std::vector<LoadInst*> Loads;
Chris Lattner1c676f72004-06-21 00:07:58 +0000159 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattner483ae012004-03-07 21:29:54 +0000160 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
161 UI != E; ++UI)
162 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
163 if (LI->isVolatile()) return false; // Don't hack volatile loads
164 Loads.push_back(LI);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000165 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
166 if (GEP->use_empty()) {
167 // Dead GEP's cause trouble later. Just remove them if we run into
168 // them.
Chris Lattner254f8f82004-05-23 21:21:17 +0000169 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000170 GEP->getParent()->getInstList().erase(GEP);
171 return isSafeToPromoteArgument(Arg);
172 }
173 // Ensure that all of the indices are constants.
Chris Lattner1c676f72004-06-21 00:07:58 +0000174 std::vector<ConstantInt*> Operands;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000175 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattner1c676f72004-06-21 00:07:58 +0000176 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000177 Operands.push_back(C);
178 else
179 return false; // Not a constant operand GEP!
180
181 // Ensure that the only users of the GEP are load instructions.
182 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
183 UI != E; ++UI)
184 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
185 if (LI->isVolatile()) return false; // Don't hack volatile loads
186 Loads.push_back(LI);
187 } else {
188 return false;
189 }
190
Chris Lattner254f8f82004-05-23 21:21:17 +0000191 // See if there is already a GEP with these indices. If not, check to
192 // make sure that we aren't promoting too many elements. If so, nothing
193 // to do.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000194 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
195 GEPIndices.end()) {
196 if (GEPIndices.size() == 3) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000197 DEBUG(std::cerr << "argpromotion disable promoting argument '"
198 << Arg->getName() << "' because it would require adding more "
199 << "than 3 arguments to the function.\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000200 // We limit aggregate promotion to only promoting up to three elements
201 // of the aggregate.
202 return false;
203 }
204 GEPIndices.push_back(Operands);
205 }
206 } else {
207 return false; // Not a load or a GEP.
208 }
Chris Lattner483ae012004-03-07 21:29:54 +0000209
Chris Lattner254f8f82004-05-23 21:21:17 +0000210 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattner483ae012004-03-07 21:29:54 +0000211
Chris Lattner254f8f82004-05-23 21:21:17 +0000212 // Okay, now we know that the argument is only used by load instructions. Use
213 // alias analysis to check to see if the pointer is guaranteed to not be
214 // modified from entry of the function to each of the load instructions.
Chris Lattner483ae012004-03-07 21:29:54 +0000215 Function &F = *Arg->getParent();
216
217 // Because there could be several/many load instructions, remember which
218 // blocks we know to be transparent to the load.
219 std::set<BasicBlock*> TranspBlocks;
220
221 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000222 TargetData &TD = getAnalysis<TargetData>();
Chris Lattner483ae012004-03-07 21:29:54 +0000223
224 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
225 // Check to see if the load is invalidated from the start of the block to
226 // the load itself.
227 LoadInst *Load = Loads[i];
228 BasicBlock *BB = Load->getParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000229
230 const PointerType *LoadTy =
231 cast<PointerType>(Load->getOperand(0)->getType());
232 unsigned LoadSize = TD.getTypeSize(LoadTy->getElementType());
233
Chris Lattner483ae012004-03-07 21:29:54 +0000234 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
235 return false; // Pointer is invalidated!
236
237 // Now check every path from the entry block to the load for transparency.
238 // To do this, we perform a depth first search on the inverse CFG from the
239 // loading block.
240 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
241 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
242 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
243 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
244 return false;
245 }
246
247 // If the path from the entry of the function to each load is free of
248 // instructions that potentially invalidate the load, we can make the
249 // transformation!
250 return true;
251}
252
Chris Lattner1c676f72004-06-21 00:07:58 +0000253namespace {
254 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
255 /// elements are instances of ConstantInt.
256 ///
257 struct GEPIdxComparator {
258 bool operator()(const std::vector<Value*> &LHS,
259 const std::vector<Value*> &RHS) const {
260 unsigned idx = 0;
261 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
262 if (LHS[idx] != RHS[idx]) {
263 return cast<ConstantInt>(LHS[idx])->getRawValue() <
264 cast<ConstantInt>(RHS[idx])->getRawValue();
265 }
266 }
267
268 // Return less than if we ran out of stuff in LHS and we didn't run out of
269 // stuff in RHS.
270 return idx == LHS.size() && idx != RHS.size();
271 }
272 };
273}
274
275
Chris Lattner254f8f82004-05-23 21:21:17 +0000276/// DoPromotion - This method actually performs the promotion of the specified
277/// arguments. At this point, we know that it's safe to do so.
Chris Lattner483ae012004-03-07 21:29:54 +0000278void ArgPromotion::DoPromotion(Function *F, std::vector<Argument*> &Args2Prom) {
279 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
280
281 // Start by computing a new prototype for the function, which is the same as
282 // the old function, but has modified arguments.
283 const FunctionType *FTy = F->getFunctionType();
284 std::vector<const Type*> Params;
285
Chris Lattner1c676f72004-06-21 00:07:58 +0000286 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
287
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000288 // ScalarizedElements - If we are promoting a pointer that has elements
289 // accessed out of it, keep track of which elements are accessed so that we
290 // can add one argument for each.
291 //
292 // Arguments that are directly loaded will have a zero element value here, to
293 // handle cases where there are both a direct load and GEP accesses.
294 //
Chris Lattner1c676f72004-06-21 00:07:58 +0000295 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000296
Chris Lattner254f8f82004-05-23 21:21:17 +0000297 // OriginalLoads - Keep track of a representative load instruction from the
298 // original function so that we can tell the alias analysis implementation
299 // what the new GEP/Load instructions we are inserting look like.
300 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
301
Chris Lattner483ae012004-03-07 21:29:54 +0000302 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
303 if (!ArgsToPromote.count(I)) {
304 Params.push_back(I->getType());
Chris Lattner254f8f82004-05-23 21:21:17 +0000305 } else if (I->use_empty()) {
306 ++NumArgumentsDead;
307 } else {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000308 // Okay, this is being promoted. Check to see if there are any GEP uses
309 // of the argument.
Chris Lattner1c676f72004-06-21 00:07:58 +0000310 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000311 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
312 ++UI) {
313 Instruction *User = cast<Instruction>(*UI);
314 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
Chris Lattner254f8f82004-05-23 21:21:17 +0000315 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
316 ArgIndices.insert(Indices);
317 LoadInst *OrigLoad;
318 if (LoadInst *L = dyn_cast<LoadInst>(User))
319 OrigLoad = L;
320 else
321 OrigLoad = cast<LoadInst>(User->use_back());
322 OriginalLoads[Indices] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000323 }
324
325 // Add a parameter to the function for each element passed in.
Chris Lattner1c676f72004-06-21 00:07:58 +0000326 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000327 E = ArgIndices.end(); SI != E; ++SI)
328 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
329
330 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
331 ++NumArgumentsPromoted;
332 else
333 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000334 }
335
336 const Type *RetTy = FTy->getReturnType();
337
338 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
339 // have zero fixed arguments.
340 bool ExtraArgHack = false;
341 if (Params.empty() && FTy->isVarArg()) {
342 ExtraArgHack = true;
343 Params.push_back(Type::IntTy);
344 }
345 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
346
347 // Create the new function body and insert it into the module...
348 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
349 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner254f8f82004-05-23 21:21:17 +0000350
351 // Get the alias analysis information that we need to update to reflect our
352 // changes.
353 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
354
Chris Lattner483ae012004-03-07 21:29:54 +0000355 // Loop over all of the callers of the function, transforming the call sites
356 // to pass in the loaded pointers.
357 //
358 std::vector<Value*> Args;
359 while (!F->use_empty()) {
360 CallSite CS = CallSite::get(F->use_back());
361 Instruction *Call = CS.getInstruction();
362
Chris Lattner254f8f82004-05-23 21:21:17 +0000363 // Make sure the caller of this function is revisited now that we promoted
364 // arguments in a callee of it.
Chris Lattner483ae012004-03-07 21:29:54 +0000365 if (Call->getParent()->getParent()->hasInternalLinkage())
366 WorkList.insert(Call->getParent()->getParent());
367
Chris Lattner254f8f82004-05-23 21:21:17 +0000368 // Loop over the operands, inserting GEP and loads in the caller as
369 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000370 CallSite::arg_iterator AI = CS.arg_begin();
371 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
372 if (!ArgsToPromote.count(I))
373 Args.push_back(*AI); // Unmodified argument
374 else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000375 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattner1c676f72004-06-21 00:07:58 +0000376 ScalarizeTable &ArgIndices = ScalarizedElements[I];
377 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000378 E = ArgIndices.end(); SI != E; ++SI) {
379 Value *V = *AI;
Chris Lattner254f8f82004-05-23 21:21:17 +0000380 LoadInst *OrigLoad = OriginalLoads[*SI];
381 if (!SI->empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000382 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
Chris Lattner254f8f82004-05-23 21:21:17 +0000383 AA.copyValue(OrigLoad->getOperand(0), V);
384 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000385 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner254f8f82004-05-23 21:21:17 +0000386 AA.copyValue(OrigLoad, Args.back());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000387 }
Chris Lattner483ae012004-03-07 21:29:54 +0000388 }
389
390 if (ExtraArgHack)
391 Args.push_back(Constant::getNullValue(Type::IntTy));
392
393 // Push any varargs arguments on the list
394 for (; AI != CS.arg_end(); ++AI)
395 Args.push_back(*AI);
396
397 Instruction *New;
398 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
399 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
400 Args, "", Call);
401 } else {
402 New = new CallInst(NF, Args, "", Call);
403 }
404 Args.clear();
405
Chris Lattner254f8f82004-05-23 21:21:17 +0000406 // Update the alias analysis implementation to know that we are replacing
407 // the old call with a new one.
408 AA.replaceWithNewValue(Call, New);
409
Chris Lattner483ae012004-03-07 21:29:54 +0000410 if (!Call->use_empty()) {
411 Call->replaceAllUsesWith(New);
412 std::string Name = Call->getName();
413 Call->setName("");
414 New->setName(Name);
415 }
416
417 // Finally, remove the old call from the program, reducing the use-count of
418 // F.
419 Call->getParent()->getInstList().erase(Call);
420 }
421
422 // Since we have now created the new function, splice the body of the old
423 // function right into the new function, leaving the old rotting hulk of the
424 // function empty.
425 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
426
427 // Loop over the argument list, transfering uses of the old arguments over to
428 // the new arguments, also transfering over the names as well.
429 //
430 for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
431 I != E; ++I)
432 if (!ArgsToPromote.count(I)) {
433 // If this is an unmodified argument, move the name and users over to the
434 // new version.
435 I->replaceAllUsesWith(I2);
436 I2->setName(I->getName());
Chris Lattner254f8f82004-05-23 21:21:17 +0000437 AA.replaceWithNewValue(I, I2);
Chris Lattner483ae012004-03-07 21:29:54 +0000438 ++I2;
Chris Lattner254f8f82004-05-23 21:21:17 +0000439 } else if (I->use_empty()) {
440 AA.deleteValue(I);
441 } else {
Chris Lattner483ae012004-03-07 21:29:54 +0000442 // Otherwise, if we promoted this argument, then all users are load
443 // instructions, and all loads should be using the new argument that we
444 // added.
Chris Lattner1c676f72004-06-21 00:07:58 +0000445 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000446
Chris Lattner483ae012004-03-07 21:29:54 +0000447 while (!I->use_empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000448 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
449 assert(ArgIndices.begin()->empty() &&
450 "Load element should sort to front!");
451 I2->setName(I->getName()+".val");
452 LI->replaceAllUsesWith(I2);
Chris Lattner254f8f82004-05-23 21:21:17 +0000453 AA.replaceWithNewValue(LI, I2);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000454 LI->getParent()->getInstList().erase(LI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000455 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
456 << "' in function '" << F->getName() << "'\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000457 } else {
458 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
459 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
460
461 unsigned ArgNo = 0;
462 Function::aiterator TheArg = I2;
Chris Lattner1c676f72004-06-21 00:07:58 +0000463 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000464 *It != Operands; ++It, ++TheArg) {
465 assert(It != ArgIndices.end() && "GEP not handled??");
466 }
467
468 std::string NewName = I->getName();
469 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
470 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
471 NewName += "."+itostr((int64_t)CI->getRawValue());
472 else
473 NewName += ".x";
474 TheArg->setName(NewName+".val");
475
476 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
477 << "' of function '" << F->getName() << "'\n");
478
479 // All of the uses must be load instructions. Replace them all with
480 // the argument specified by ArgNo.
481 while (!GEP->use_empty()) {
482 LoadInst *L = cast<LoadInst>(GEP->use_back());
483 L->replaceAllUsesWith(TheArg);
Chris Lattner254f8f82004-05-23 21:21:17 +0000484 AA.replaceWithNewValue(L, TheArg);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000485 L->getParent()->getInstList().erase(L);
486 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000487 AA.deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000488 GEP->getParent()->getInstList().erase(GEP);
489 }
Chris Lattner483ae012004-03-07 21:29:54 +0000490 }
Chris Lattnercc544e52004-03-07 22:52:53 +0000491
492 // If we inserted a new pointer type, it's possible that IT could be
Chris Lattner254f8f82004-05-23 21:21:17 +0000493 // promoted too. Also, increment I2 past all of the arguments added for
494 // this promoted pointer.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000495 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i, ++I2)
496 if (isa<PointerType>(I2->getType()))
497 WorkList.insert(NF);
Chris Lattner483ae012004-03-07 21:29:54 +0000498 }
499
Chris Lattner254f8f82004-05-23 21:21:17 +0000500 // Notify the alias analysis implementation that we inserted a new argument.
501 if (ExtraArgHack)
502 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->abegin());
503
504
505 // Tell the alias analysis that the old function is about to disappear.
506 AA.replaceWithNewValue(F, NF);
507
Chris Lattner483ae012004-03-07 21:29:54 +0000508 // Now that the old function is dead, delete it.
509 F->getParent()->getFunctionList().erase(F);
510}