blob: e9841697a784cb0861048a147feb34c16589e138 [file] [log] [blame]
Chris Lattner9e7cc2f2004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattnered570a72004-03-07 21:29:54 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattnered570a72004-03-07 21:29:54 +00008//===----------------------------------------------------------------------===//
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 Lattnerebeb0cb2004-09-17 03:58:39 +000012// arguments. If we can prove, through the use of alias analysis, that an
Chris Lattnered570a72004-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 Lattner9e7cc2f2004-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 Lattnered570a72004-03-07 21:29:54 +000017//
Chris Lattner9440db82004-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 Lattner9e7cc2f2004-05-23 21:21:17 +000022// operands for a large array or structure!
Chris Lattner9440db82004-03-08 01:04:36 +000023//
Chris Lattnered570a72004-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 Lattner9440db82004-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 Lattnered570a72004-03-07 21:29:54 +000028//
29//===----------------------------------------------------------------------===//
30
Chris Lattner9e7cc2f2004-05-23 21:21:17 +000031#define DEBUG_TYPE "argpromotion"
Chris Lattnered570a72004-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 Lattner5eb6f6c2004-09-18 00:34:13 +000036#include "llvm/CallGraphSCCPass.h"
Chris Lattnered570a72004-03-07 21:29:54 +000037#include "llvm/Instructions.h"
38#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000039#include "llvm/Analysis/CallGraph.h"
Chris Lattnered570a72004-03-07 21:29:54 +000040#include "llvm/Target/TargetData.h"
41#include "llvm/Support/CallSite.h"
42#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-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 Lattnered570a72004-03-07 21:29:54 +000047#include <set>
48using namespace llvm;
49
50namespace {
51 Statistic<> NumArgumentsPromoted("argpromotion",
52 "Number of pointer arguments promoted");
Chris Lattner9440db82004-03-08 01:04:36 +000053 Statistic<> NumAggregatesPromoted("argpromotion",
54 "Number of aggregate arguments promoted");
Chris Lattnered570a72004-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 Lattner5eb6f6c2004-09-18 00:34:13 +000060 struct ArgPromotion : public CallGraphSCCPass {
Chris Lattnered570a72004-03-07 21:29:54 +000061 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired<AliasAnalysis>();
63 AU.addRequired<TargetData>();
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000064 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnered570a72004-03-07 21:29:54 +000065 }
66
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000067 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Chris Lattnered570a72004-03-07 21:29:54 +000068 private:
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000069 bool PromoteArguments(CallGraphNode *CGN);
Misha Brukmanfd939082005-04-21 23:48:37 +000070 bool isSafeToPromoteArgument(Argument *Arg) const;
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000071 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
Chris Lattnered570a72004-03-07 21:29:54 +000072 };
73
Chris Lattner7f8897f2006-08-27 22:42:52 +000074 RegisterPass<ArgPromotion> X("argpromotion",
75 "Promote 'by reference' arguments to scalars");
Chris Lattnered570a72004-03-07 21:29:54 +000076}
77
Chris Lattnerb12914b2004-09-20 04:48:05 +000078ModulePass *llvm::createArgumentPromotionPass() {
Chris Lattnered570a72004-03-07 21:29:54 +000079 return new ArgPromotion();
80}
81
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000082bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
83 bool Changed = false, LocalChange;
Chris Lattnered570a72004-03-07 21:29:54 +000084
Chris Lattnerf5afcab2004-09-19 01:05:16 +000085 do { // Iterate until we stop promoting from this SCC.
Chris Lattner5eb6f6c2004-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);
Misha Brukmanfd939082005-04-21 23:48:37 +000092
Chris Lattnered570a72004-03-07 21:29:54 +000093 return Changed;
94}
95
Chris Lattner9e7cc2f2004-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 Lattner5eb6f6c2004-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 Lattnered570a72004-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;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000109 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnered570a72004-03-07 21:29:54 +0000110 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 Lattner7db5a6d2004-03-07 22:43:27 +0000117 UI != E; ++UI) {
118 CallSite CS = CallSite::get(*UI);
Chris Lattner9e7cc2f2004-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 Lattner7db5a6d2004-03-07 22:43:27 +0000127 }
Chris Lattnered570a72004-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 Lattner5eb6f6c2004-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 Lattnered570a72004-03-07 21:29:54 +0000145 return true;
146}
147
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000148/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
149/// to load.
150static bool IsAlwaysValidPointer(Value *V) {
151 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
152 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
153 return IsAlwaysValidPointer(GEP->getOperand(0));
154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
155 if (CE->getOpcode() == Instruction::GetElementPtr)
156 return IsAlwaysValidPointer(CE->getOperand(0));
157
158 return false;
159}
160
161/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
162/// all callees pass in a valid pointer for the specified function argument.
163static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
164 Function *Callee = Arg->getParent();
165
Chris Lattnere4d5c442005-03-15 04:54:21 +0000166 unsigned ArgNo = std::distance(Callee->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000167
168 // Look at all call sites of the function. At this pointer we know we only
169 // have direct callees.
170 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
171 UI != E; ++UI) {
172 CallSite CS = CallSite::get(*UI);
173 assert(CS.getInstruction() && "Should only have direct calls!");
174
175 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
176 return false;
177 }
178 return true;
179}
180
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000181
182/// isSafeToPromoteArgument - As you might guess from the name of this method,
183/// it checks to see if it is both safe and useful to promote the argument.
184/// This method limits promotion of aggregates to only promote up to three
185/// elements of the aggregate in order to avoid exploding the number of
186/// arguments passed in.
Chris Lattnered570a72004-03-07 21:29:54 +0000187bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattner9440db82004-03-08 01:04:36 +0000188 // We can only promote this argument if all of the uses are loads, or are GEP
189 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000190 bool HasLoadInEntryBlock = false;
191 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattnered570a72004-03-07 21:29:54 +0000192 std::vector<LoadInst*> Loads;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000193 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattnered570a72004-03-07 21:29:54 +0000194 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
195 UI != E; ++UI)
196 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
197 if (LI->isVolatile()) return false; // Don't hack volatile loads
198 Loads.push_back(LI);
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000199 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-03-08 01:04:36 +0000200 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
201 if (GEP->use_empty()) {
202 // Dead GEP's cause trouble later. Just remove them if we run into
203 // them.
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000204 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattner9440db82004-03-08 01:04:36 +0000205 GEP->getParent()->getInstList().erase(GEP);
206 return isSafeToPromoteArgument(Arg);
207 }
208 // Ensure that all of the indices are constants.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000209 std::vector<ConstantInt*> Operands;
Chris Lattner9440db82004-03-08 01:04:36 +0000210 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattnerbeabf452004-06-21 00:07:58 +0000211 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattner9440db82004-03-08 01:04:36 +0000212 Operands.push_back(C);
213 else
214 return false; // Not a constant operand GEP!
215
216 // Ensure that the only users of the GEP are load instructions.
217 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
218 UI != E; ++UI)
219 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
220 if (LI->isVolatile()) return false; // Don't hack volatile loads
221 Loads.push_back(LI);
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000222 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-03-08 01:04:36 +0000223 } else {
224 return false;
225 }
226
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000227 // See if there is already a GEP with these indices. If not, check to
228 // make sure that we aren't promoting too many elements. If so, nothing
229 // to do.
Chris Lattner9440db82004-03-08 01:04:36 +0000230 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
231 GEPIndices.end()) {
232 if (GEPIndices.size() == 3) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000233 DOUT << "argpromotion disable promoting argument '"
234 << Arg->getName() << "' because it would require adding more "
235 << "than 3 arguments to the function.\n";
Chris Lattner9440db82004-03-08 01:04:36 +0000236 // We limit aggregate promotion to only promoting up to three elements
237 // of the aggregate.
238 return false;
239 }
240 GEPIndices.push_back(Operands);
241 }
242 } else {
243 return false; // Not a load or a GEP.
244 }
Chris Lattnered570a72004-03-07 21:29:54 +0000245
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000246 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattnered570a72004-03-07 21:29:54 +0000247
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000248 // If we decide that we want to promote this argument, the value is going to
249 // be unconditionally loaded in all callees. This is only safe to do if the
250 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
251 // of the pointer in the entry block of the function) or if we can prove that
252 // all pointers passed in are always to legal locations (for example, no null
253 // pointers are passed in, no pointers to free'd memory, etc).
Evan Cheng99435d32006-10-03 07:26:07 +0000254 if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg))
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000255 return false; // Cannot prove that this is safe!!
256
257 // Okay, now we know that the argument is only used by load instructions and
258 // it is safe to unconditionally load the pointer. Use alias analysis to
259 // check to see if the pointer is guaranteed to not be modified from entry of
260 // the function to each of the load instructions.
Chris Lattnered570a72004-03-07 21:29:54 +0000261
262 // Because there could be several/many load instructions, remember which
263 // blocks we know to be transparent to the load.
264 std::set<BasicBlock*> TranspBlocks;
Owen Anderson46f022a2006-09-15 05:22:51 +0000265
266 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner9440db82004-03-08 01:04:36 +0000267 TargetData &TD = getAnalysis<TargetData>();
Chris Lattnered570a72004-03-07 21:29:54 +0000268
269 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
270 // Check to see if the load is invalidated from the start of the block to
271 // the load itself.
272 LoadInst *Load = Loads[i];
273 BasicBlock *BB = Load->getParent();
Chris Lattner9440db82004-03-08 01:04:36 +0000274
275 const PointerType *LoadTy =
276 cast<PointerType>(Load->getOperand(0)->getType());
Chris Lattner4d0801b2005-01-08 19:45:31 +0000277 unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType());
Chris Lattner9440db82004-03-08 01:04:36 +0000278
Chris Lattnered570a72004-03-07 21:29:54 +0000279 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
280 return false; // Pointer is invalidated!
281
282 // Now check every path from the entry block to the load for transparency.
283 // To do this, we perform a depth first search on the inverse CFG from the
284 // loading block.
285 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
286 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
287 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
288 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
289 return false;
290 }
291
292 // If the path from the entry of the function to each load is free of
293 // instructions that potentially invalidate the load, we can make the
294 // transformation!
295 return true;
296}
297
Chris Lattnerbeabf452004-06-21 00:07:58 +0000298namespace {
299 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
300 /// elements are instances of ConstantInt.
301 ///
302 struct GEPIdxComparator {
303 bool operator()(const std::vector<Value*> &LHS,
304 const std::vector<Value*> &RHS) const {
305 unsigned idx = 0;
306 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
307 if (LHS[idx] != RHS[idx]) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000308 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
309 cast<ConstantInt>(RHS[idx])->getZExtValue();
Chris Lattnerbeabf452004-06-21 00:07:58 +0000310 }
311 }
312
313 // Return less than if we ran out of stuff in LHS and we didn't run out of
314 // stuff in RHS.
315 return idx == LHS.size() && idx != RHS.size();
316 }
317 };
318}
319
320
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000321/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000322/// arguments, and returns the new function. At this point, we know that it's
323/// safe to do so.
324Function *ArgPromotion::DoPromotion(Function *F,
325 std::vector<Argument*> &Args2Prom) {
Chris Lattnered570a72004-03-07 21:29:54 +0000326 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000327
Chris Lattnered570a72004-03-07 21:29:54 +0000328 // Start by computing a new prototype for the function, which is the same as
329 // the old function, but has modified arguments.
330 const FunctionType *FTy = F->getFunctionType();
331 std::vector<const Type*> Params;
332
Chris Lattnerbeabf452004-06-21 00:07:58 +0000333 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
334
Chris Lattner9440db82004-03-08 01:04:36 +0000335 // ScalarizedElements - If we are promoting a pointer that has elements
336 // accessed out of it, keep track of which elements are accessed so that we
337 // can add one argument for each.
338 //
339 // Arguments that are directly loaded will have a zero element value here, to
340 // handle cases where there are both a direct load and GEP accesses.
341 //
Chris Lattnerbeabf452004-06-21 00:07:58 +0000342 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattner9440db82004-03-08 01:04:36 +0000343
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000344 // OriginalLoads - Keep track of a representative load instruction from the
345 // original function so that we can tell the alias analysis implementation
346 // what the new GEP/Load instructions we are inserting look like.
347 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
348
Chris Lattnere4d5c442005-03-15 04:54:21 +0000349 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnered570a72004-03-07 21:29:54 +0000350 if (!ArgsToPromote.count(I)) {
351 Params.push_back(I->getType());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000352 } else if (I->use_empty()) {
353 ++NumArgumentsDead;
354 } else {
Chris Lattner9440db82004-03-08 01:04:36 +0000355 // Okay, this is being promoted. Check to see if there are any GEP uses
356 // of the argument.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000357 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattner9440db82004-03-08 01:04:36 +0000358 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
359 ++UI) {
360 Instruction *User = cast<Instruction>(*UI);
Owen Anderson46f022a2006-09-15 05:22:51 +0000361 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
362 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
363 ArgIndices.insert(Indices);
364 LoadInst *OrigLoad;
365 if (LoadInst *L = dyn_cast<LoadInst>(User))
366 OrigLoad = L;
367 else
368 OrigLoad = cast<LoadInst>(User->use_back());
369 OriginalLoads[Indices] = OrigLoad;
Chris Lattner9440db82004-03-08 01:04:36 +0000370 }
371
372 // Add a parameter to the function for each element passed in.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000373 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000374 E = ArgIndices.end(); SI != E; ++SI)
375 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
376
377 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
378 ++NumArgumentsPromoted;
379 else
380 ++NumAggregatesPromoted;
Chris Lattnered570a72004-03-07 21:29:54 +0000381 }
382
383 const Type *RetTy = FTy->getReturnType();
384
385 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
386 // have zero fixed arguments.
387 bool ExtraArgHack = false;
388 if (Params.empty() && FTy->isVarArg()) {
389 ExtraArgHack = true;
390 Params.push_back(Type::IntTy);
391 }
392 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanfd939082005-04-21 23:48:37 +0000393
Chris Lattnered570a72004-03-07 21:29:54 +0000394 // Create the new function body and insert it into the module...
395 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000396 NF->setCallingConv(F->getCallingConv());
Chris Lattnered570a72004-03-07 21:29:54 +0000397 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000398
399 // Get the alias analysis information that we need to update to reflect our
400 // changes.
401 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
402
Chris Lattnered570a72004-03-07 21:29:54 +0000403 // Loop over all of the callers of the function, transforming the call sites
404 // to pass in the loaded pointers.
405 //
406 std::vector<Value*> Args;
407 while (!F->use_empty()) {
408 CallSite CS = CallSite::get(F->use_back());
409 Instruction *Call = CS.getInstruction();
410
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000411 // Loop over the operands, inserting GEP and loads in the caller as
412 // appropriate.
Chris Lattnered570a72004-03-07 21:29:54 +0000413 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000414 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
415 I != E; ++I, ++AI)
Chris Lattnered570a72004-03-07 21:29:54 +0000416 if (!ArgsToPromote.count(I))
417 Args.push_back(*AI); // Unmodified argument
418 else if (!I->use_empty()) {
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000419 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000420 ScalarizeTable &ArgIndices = ScalarizedElements[I];
421 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000422 E = ArgIndices.end(); SI != E; ++SI) {
423 Value *V = *AI;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000424 LoadInst *OrigLoad = OriginalLoads[*SI];
425 if (!SI->empty()) {
Chris Lattner9440db82004-03-08 01:04:36 +0000426 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000427 AA.copyValue(OrigLoad->getOperand(0), V);
428 }
Chris Lattner9440db82004-03-08 01:04:36 +0000429 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000430 AA.copyValue(OrigLoad, Args.back());
Chris Lattner9440db82004-03-08 01:04:36 +0000431 }
Chris Lattnered570a72004-03-07 21:29:54 +0000432 }
433
434 if (ExtraArgHack)
435 Args.push_back(Constant::getNullValue(Type::IntTy));
436
437 // Push any varargs arguments on the list
438 for (; AI != CS.arg_end(); ++AI)
439 Args.push_back(*AI);
440
441 Instruction *New;
442 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
443 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
444 Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000445 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattnered570a72004-03-07 21:29:54 +0000446 } else {
447 New = new CallInst(NF, Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000448 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner1430ef12005-05-06 06:46:58 +0000449 if (cast<CallInst>(Call)->isTailCall())
450 cast<CallInst>(New)->setTailCall();
Chris Lattnered570a72004-03-07 21:29:54 +0000451 }
452 Args.clear();
453
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000454 // Update the alias analysis implementation to know that we are replacing
455 // the old call with a new one.
456 AA.replaceWithNewValue(Call, New);
457
Chris Lattnered570a72004-03-07 21:29:54 +0000458 if (!Call->use_empty()) {
459 Call->replaceAllUsesWith(New);
460 std::string Name = Call->getName();
461 Call->setName("");
462 New->setName(Name);
463 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000464
Chris Lattnered570a72004-03-07 21:29:54 +0000465 // Finally, remove the old call from the program, reducing the use-count of
466 // F.
467 Call->getParent()->getInstList().erase(Call);
468 }
469
470 // Since we have now created the new function, splice the body of the old
471 // function right into the new function, leaving the old rotting hulk of the
472 // function empty.
473 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
474
475 // Loop over the argument list, transfering uses of the old arguments over to
476 // the new arguments, also transfering over the names as well.
477 //
Chris Lattnere4d5c442005-03-15 04:54:21 +0000478 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), I2 = NF->arg_begin();
Chris Lattnered570a72004-03-07 21:29:54 +0000479 I != E; ++I)
480 if (!ArgsToPromote.count(I)) {
481 // If this is an unmodified argument, move the name and users over to the
482 // new version.
483 I->replaceAllUsesWith(I2);
484 I2->setName(I->getName());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000485 AA.replaceWithNewValue(I, I2);
Chris Lattnered570a72004-03-07 21:29:54 +0000486 ++I2;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000487 } else if (I->use_empty()) {
488 AA.deleteValue(I);
489 } else {
Chris Lattnered570a72004-03-07 21:29:54 +0000490 // Otherwise, if we promoted this argument, then all users are load
491 // instructions, and all loads should be using the new argument that we
492 // added.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000493 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattner9440db82004-03-08 01:04:36 +0000494
Chris Lattnered570a72004-03-07 21:29:54 +0000495 while (!I->use_empty()) {
Chris Lattner9440db82004-03-08 01:04:36 +0000496 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
497 assert(ArgIndices.begin()->empty() &&
498 "Load element should sort to front!");
499 I2->setName(I->getName()+".val");
500 LI->replaceAllUsesWith(I2);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000501 AA.replaceWithNewValue(LI, I2);
Chris Lattner9440db82004-03-08 01:04:36 +0000502 LI->getParent()->getInstList().erase(LI);
Bill Wendling0a81aac2006-11-26 10:02:32 +0000503 DOUT << "*** Promoted load of argument '" << I->getName()
504 << "' in function '" << F->getName() << "'\n";
Chris Lattner9440db82004-03-08 01:04:36 +0000505 } else {
506 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
507 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
508
Chris Lattnere4d5c442005-03-15 04:54:21 +0000509 Function::arg_iterator TheArg = I2;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000510 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattner9440db82004-03-08 01:04:36 +0000511 *It != Operands; ++It, ++TheArg) {
512 assert(It != ArgIndices.end() && "GEP not handled??");
513 }
514
515 std::string NewName = I->getName();
516 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
517 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
Reid Spencerb83eb642006-10-20 07:07:24 +0000518 NewName += "."+itostr((int64_t)CI->getZExtValue());
Chris Lattner9440db82004-03-08 01:04:36 +0000519 else
520 NewName += ".x";
521 TheArg->setName(NewName+".val");
522
Bill Wendling0a81aac2006-11-26 10:02:32 +0000523 DOUT << "*** Promoted agg argument '" << TheArg->getName()
524 << "' of function '" << F->getName() << "'\n";
Chris Lattner9440db82004-03-08 01:04:36 +0000525
526 // All of the uses must be load instructions. Replace them all with
527 // the argument specified by ArgNo.
528 while (!GEP->use_empty()) {
529 LoadInst *L = cast<LoadInst>(GEP->use_back());
530 L->replaceAllUsesWith(TheArg);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000531 AA.replaceWithNewValue(L, TheArg);
Chris Lattner9440db82004-03-08 01:04:36 +0000532 L->getParent()->getInstList().erase(L);
533 }
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000534 AA.deleteValue(GEP);
Chris Lattner9440db82004-03-08 01:04:36 +0000535 GEP->getParent()->getInstList().erase(GEP);
536 }
Chris Lattnered570a72004-03-07 21:29:54 +0000537 }
Chris Lattner86a734b2004-03-07 22:52:53 +0000538
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000539 // Increment I2 past all of the arguments added for this promoted pointer.
540 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
541 ++I2;
Chris Lattnered570a72004-03-07 21:29:54 +0000542 }
543
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000544 // Notify the alias analysis implementation that we inserted a new argument.
545 if (ExtraArgHack)
Chris Lattnere4d5c442005-03-15 04:54:21 +0000546 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->arg_begin());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000547
548
549 // Tell the alias analysis that the old function is about to disappear.
550 AA.replaceWithNewValue(F, NF);
551
Chris Lattnered570a72004-03-07 21:29:54 +0000552 // Now that the old function is dead, delete it.
553 F->getParent()->getFunctionList().erase(F);
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000554 return NF;
Chris Lattnered570a72004-03-07 21:29:54 +0000555}