blob: a929df05d887c1a4388ab8c001b0de6a94d9892a [file] [log] [blame]
Chris Lattner254f8f82004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner483ae012004-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner483ae012004-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 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 Lattnerc597b8a2006-01-22 23:32:06 +000047#include <iostream>
Chris Lattner483ae012004-03-07 21:29:54 +000048#include <set>
49using namespace llvm;
50
51namespace {
52 Statistic<> NumArgumentsPromoted("argpromotion",
53 "Number of pointer arguments promoted");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000054 Statistic<> NumAggregatesPromoted("argpromotion",
55 "Number of aggregate arguments promoted");
Chris Lattner483ae012004-03-07 21:29:54 +000056 Statistic<> NumArgumentsDead("argpromotion",
57 "Number of dead pointer args eliminated");
58
59 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
60 ///
Chris Lattner37b6c4f2004-09-18 00:34:13 +000061 struct ArgPromotion : public CallGraphSCCPass {
Chris Lattner483ae012004-03-07 21:29:54 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<AliasAnalysis>();
64 AU.addRequired<TargetData>();
Chris Lattner37b6c4f2004-09-18 00:34:13 +000065 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattner483ae012004-03-07 21:29:54 +000066 }
67
Chris Lattner37b6c4f2004-09-18 00:34:13 +000068 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Chris Lattner483ae012004-03-07 21:29:54 +000069 private:
Chris Lattner37b6c4f2004-09-18 00:34:13 +000070 bool PromoteArguments(CallGraphNode *CGN);
Misha Brukmanb1c93172005-04-21 23:48:37 +000071 bool isSafeToPromoteArgument(Argument *Arg) const;
Chris Lattner37b6c4f2004-09-18 00:34:13 +000072 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
Chris Lattner483ae012004-03-07 21:29:54 +000073 };
74
Chris Lattnerc2d3d312006-08-27 22:42:52 +000075 RegisterPass<ArgPromotion> X("argpromotion",
76 "Promote 'by reference' arguments to scalars");
Chris Lattner483ae012004-03-07 21:29:54 +000077}
78
Chris Lattner4f2cf032004-09-20 04:48:05 +000079ModulePass *llvm::createArgumentPromotionPass() {
Chris Lattner483ae012004-03-07 21:29:54 +000080 return new ArgPromotion();
81}
82
Chris Lattner37b6c4f2004-09-18 00:34:13 +000083bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
84 bool Changed = false, LocalChange;
Chris Lattner483ae012004-03-07 21:29:54 +000085
Chris Lattner9864df92004-09-19 01:05:16 +000086 do { // Iterate until we stop promoting from this SCC.
Chris Lattner37b6c4f2004-09-18 00:34:13 +000087 LocalChange = false;
88 // Attempt to promote arguments from all functions in this SCC.
89 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
90 LocalChange |= PromoteArguments(SCC[i]);
91 Changed |= LocalChange; // Remember that we changed something.
92 } while (LocalChange);
Misha Brukmanb1c93172005-04-21 23:48:37 +000093
Chris Lattner483ae012004-03-07 21:29:54 +000094 return Changed;
95}
96
Chris Lattner254f8f82004-05-23 21:21:17 +000097/// PromoteArguments - This method checks the specified function to see if there
98/// are any promotable arguments and if it is safe to promote the function (for
99/// example, all callers are direct). If safe to promote some arguments, it
100/// calls the DoPromotion method.
101///
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000102bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
103 Function *F = CGN->getFunction();
104
105 // Make sure that it is local to this module.
106 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattner483ae012004-03-07 21:29:54 +0000107
108 // First check: see if there are any pointer arguments! If not, quick exit.
109 std::vector<Argument*> PointerArgs;
Chris Lattner531f9e92005-03-15 04:54:21 +0000110 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner483ae012004-03-07 21:29:54 +0000111 if (isa<PointerType>(I->getType()))
112 PointerArgs.push_back(I);
113 if (PointerArgs.empty()) return false;
114
115 // Second check: make sure that all callers are direct callers. We can't
116 // transform functions that have indirect callers.
117 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner64b8d692004-03-07 22:43:27 +0000118 UI != E; ++UI) {
119 CallSite CS = CallSite::get(*UI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000120 if (!CS.getInstruction()) // "Taking the address" of the function
121 return false;
122
123 // Ensure that this call site is CALLING the function, not passing it as
124 // an argument.
125 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
126 AI != E; ++AI)
127 if (*AI == F) return false; // Passing the function address in!
Chris Lattner64b8d692004-03-07 22:43:27 +0000128 }
Chris Lattner483ae012004-03-07 21:29:54 +0000129
130 // Check to see which arguments are promotable. If an argument is not
131 // promotable, remove it from the PointerArgs vector.
132 for (unsigned i = 0; i != PointerArgs.size(); ++i)
133 if (!isSafeToPromoteArgument(PointerArgs[i])) {
134 std::swap(PointerArgs[i--], PointerArgs.back());
135 PointerArgs.pop_back();
136 }
137
138 // No promotable pointer arguments.
139 if (PointerArgs.empty()) return false;
140
141 // Okay, promote all of the arguments are rewrite the callees!
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000142 Function *NewF = DoPromotion(F, PointerArgs);
143
144 // Update the call graph to know that the old function is gone.
145 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattner483ae012004-03-07 21:29:54 +0000146 return true;
147}
148
Chris Lattner244031d2004-11-13 23:31:34 +0000149/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
150/// to load.
151static bool IsAlwaysValidPointer(Value *V) {
152 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
153 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
154 return IsAlwaysValidPointer(GEP->getOperand(0));
155 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
156 if (CE->getOpcode() == Instruction::GetElementPtr)
157 return IsAlwaysValidPointer(CE->getOperand(0));
158
159 return false;
160}
161
162/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
163/// all callees pass in a valid pointer for the specified function argument.
164static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
165 Function *Callee = Arg->getParent();
166
Chris Lattner531f9e92005-03-15 04:54:21 +0000167 unsigned ArgNo = std::distance(Callee->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner244031d2004-11-13 23:31:34 +0000168
169 // Look at all call sites of the function. At this pointer we know we only
170 // have direct callees.
171 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
172 UI != E; ++UI) {
173 CallSite CS = CallSite::get(*UI);
174 assert(CS.getInstruction() && "Should only have direct calls!");
175
176 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
177 return false;
178 }
179 return true;
180}
181
Owen Andersonedadd3f2006-09-15 05:22:51 +0000182/// AccessOccursOnPath - Returns true if and only if a load or GEP instruction
183/// on Pointer occurs in Path, or in every control-flow path that succeeds it.
184bool AccessOccursOnPath(Argument* Arg) {
185 std::vector<BasicBlock*> Worklist;
186 Worklist.push_back(Arg->getParent()->begin());
187
188 std::set<BasicBlock*> Visited;
189
190 while (!Worklist.empty()) {
191 BasicBlock* BB = Worklist.back();
192 Worklist.pop_back();
193 Visited.insert(BB);
194
195 bool ContainsAccess = false;
196 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
197 if (isa<LoadInst>(I) || isa<GetElementPtrInst>(I)) {
198 ContainsAccess = true;
199 break;
200 }
201
202 if (ContainsAccess) continue;
203
204 TerminatorInst* TI = BB->getTerminator();
205 if (isa<BranchInst>(TI) || isa<SwitchInst>(TI)) {
206 for (unsigned i = 0; i < TI->getNumSuccessors(); ++i)
207 if (!Visited.count(TI->getSuccessor(i)))
208 Worklist.push_back(TI->getSuccessor(i));
209 } else {
210 return false;
211 }
212 }
213
214 return true;
215}
Chris Lattner254f8f82004-05-23 21:21:17 +0000216
217/// isSafeToPromoteArgument - As you might guess from the name of this method,
218/// it checks to see if it is both safe and useful to promote the argument.
219/// This method limits promotion of aggregates to only promote up to three
220/// elements of the aggregate in order to avoid exploding the number of
221/// arguments passed in.
Chris Lattner483ae012004-03-07 21:29:54 +0000222bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000223 // We can only promote this argument if all of the uses are loads, or are GEP
224 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner244031d2004-11-13 23:31:34 +0000225 bool HasLoadInEntryBlock = false;
226 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattner483ae012004-03-07 21:29:54 +0000227 std::vector<LoadInst*> Loads;
Chris Lattner1c676f72004-06-21 00:07:58 +0000228 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattner483ae012004-03-07 21:29:54 +0000229 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
230 UI != E; ++UI)
231 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
232 if (LI->isVolatile()) return false; // Don't hack volatile loads
233 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000234 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000235 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
236 if (GEP->use_empty()) {
237 // Dead GEP's cause trouble later. Just remove them if we run into
238 // them.
Chris Lattner254f8f82004-05-23 21:21:17 +0000239 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000240 GEP->getParent()->getInstList().erase(GEP);
241 return isSafeToPromoteArgument(Arg);
242 }
243 // Ensure that all of the indices are constants.
Chris Lattner1c676f72004-06-21 00:07:58 +0000244 std::vector<ConstantInt*> Operands;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000245 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattner1c676f72004-06-21 00:07:58 +0000246 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000247 Operands.push_back(C);
248 else
249 return false; // Not a constant operand GEP!
250
251 // Ensure that the only users of the GEP are load instructions.
252 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
253 UI != E; ++UI)
254 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
255 if (LI->isVolatile()) return false; // Don't hack volatile loads
256 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000257 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000258 } else {
259 return false;
260 }
261
Chris Lattner254f8f82004-05-23 21:21:17 +0000262 // See if there is already a GEP with these indices. If not, check to
263 // make sure that we aren't promoting too many elements. If so, nothing
264 // to do.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000265 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
266 GEPIndices.end()) {
267 if (GEPIndices.size() == 3) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000268 DEBUG(std::cerr << "argpromotion disable promoting argument '"
269 << Arg->getName() << "' because it would require adding more "
270 << "than 3 arguments to the function.\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000271 // We limit aggregate promotion to only promoting up to three elements
272 // of the aggregate.
273 return false;
274 }
275 GEPIndices.push_back(Operands);
276 }
277 } else {
278 return false; // Not a load or a GEP.
279 }
Chris Lattner483ae012004-03-07 21:29:54 +0000280
Chris Lattner254f8f82004-05-23 21:21:17 +0000281 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattner483ae012004-03-07 21:29:54 +0000282
Chris Lattner244031d2004-11-13 23:31:34 +0000283 // If we decide that we want to promote this argument, the value is going to
284 // be unconditionally loaded in all callees. This is only safe to do if the
285 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
286 // of the pointer in the entry block of the function) or if we can prove that
287 // all pointers passed in are always to legal locations (for example, no null
288 // pointers are passed in, no pointers to free'd memory, etc).
Owen Andersonedadd3f2006-09-15 05:22:51 +0000289 if (!AccessOccursOnPath(Arg) && !AllCalleesPassInValidPointerForArgument(Arg))
Chris Lattner244031d2004-11-13 23:31:34 +0000290 return false; // Cannot prove that this is safe!!
291
292 // Okay, now we know that the argument is only used by load instructions and
293 // it is safe to unconditionally load the pointer. Use alias analysis to
294 // check to see if the pointer is guaranteed to not be modified from entry of
295 // the function to each of the load instructions.
Chris Lattner483ae012004-03-07 21:29:54 +0000296 Function &F = *Arg->getParent();
297
298 // Because there could be several/many load instructions, remember which
299 // blocks we know to be transparent to the load.
300 std::set<BasicBlock*> TranspBlocks;
Owen Andersonedadd3f2006-09-15 05:22:51 +0000301
302 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000303 TargetData &TD = getAnalysis<TargetData>();
Chris Lattner483ae012004-03-07 21:29:54 +0000304
305 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
306 // Check to see if the load is invalidated from the start of the block to
307 // the load itself.
308 LoadInst *Load = Loads[i];
309 BasicBlock *BB = Load->getParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000310
311 const PointerType *LoadTy =
312 cast<PointerType>(Load->getOperand(0)->getType());
Chris Lattner46fa04b2005-01-08 19:45:31 +0000313 unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000314
Chris Lattner483ae012004-03-07 21:29:54 +0000315 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
316 return false; // Pointer is invalidated!
317
318 // Now check every path from the entry block to the load for transparency.
319 // To do this, we perform a depth first search on the inverse CFG from the
320 // loading block.
321 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
322 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
323 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
324 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
325 return false;
326 }
327
328 // If the path from the entry of the function to each load is free of
329 // instructions that potentially invalidate the load, we can make the
330 // transformation!
331 return true;
332}
333
Chris Lattner1c676f72004-06-21 00:07:58 +0000334namespace {
335 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
336 /// elements are instances of ConstantInt.
337 ///
338 struct GEPIdxComparator {
339 bool operator()(const std::vector<Value*> &LHS,
340 const std::vector<Value*> &RHS) const {
341 unsigned idx = 0;
342 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
343 if (LHS[idx] != RHS[idx]) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000344 return cast<ConstantInt>(LHS[idx])->getRawValue() <
Chris Lattner1c676f72004-06-21 00:07:58 +0000345 cast<ConstantInt>(RHS[idx])->getRawValue();
346 }
347 }
348
349 // Return less than if we ran out of stuff in LHS and we didn't run out of
350 // stuff in RHS.
351 return idx == LHS.size() && idx != RHS.size();
352 }
353 };
354}
355
356
Chris Lattner254f8f82004-05-23 21:21:17 +0000357/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000358/// arguments, and returns the new function. At this point, we know that it's
359/// safe to do so.
360Function *ArgPromotion::DoPromotion(Function *F,
361 std::vector<Argument*> &Args2Prom) {
Chris Lattner483ae012004-03-07 21:29:54 +0000362 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000363
Chris Lattner483ae012004-03-07 21:29:54 +0000364 // Start by computing a new prototype for the function, which is the same as
365 // the old function, but has modified arguments.
366 const FunctionType *FTy = F->getFunctionType();
367 std::vector<const Type*> Params;
368
Chris Lattner1c676f72004-06-21 00:07:58 +0000369 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
370
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000371 // ScalarizedElements - If we are promoting a pointer that has elements
372 // accessed out of it, keep track of which elements are accessed so that we
373 // can add one argument for each.
374 //
375 // Arguments that are directly loaded will have a zero element value here, to
376 // handle cases where there are both a direct load and GEP accesses.
377 //
Chris Lattner1c676f72004-06-21 00:07:58 +0000378 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000379
Chris Lattner254f8f82004-05-23 21:21:17 +0000380 // OriginalLoads - Keep track of a representative load instruction from the
381 // original function so that we can tell the alias analysis implementation
382 // what the new GEP/Load instructions we are inserting look like.
383 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
384
Chris Lattner531f9e92005-03-15 04:54:21 +0000385 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner483ae012004-03-07 21:29:54 +0000386 if (!ArgsToPromote.count(I)) {
387 Params.push_back(I->getType());
Chris Lattner254f8f82004-05-23 21:21:17 +0000388 } else if (I->use_empty()) {
389 ++NumArgumentsDead;
390 } else {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000391 // Okay, this is being promoted. Check to see if there are any GEP uses
392 // of the argument.
Chris Lattner1c676f72004-06-21 00:07:58 +0000393 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000394 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
395 ++UI) {
396 Instruction *User = cast<Instruction>(*UI);
Owen Andersonedadd3f2006-09-15 05:22:51 +0000397 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
398 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
399 ArgIndices.insert(Indices);
400 LoadInst *OrigLoad;
401 if (LoadInst *L = dyn_cast<LoadInst>(User))
402 OrigLoad = L;
403 else
404 OrigLoad = cast<LoadInst>(User->use_back());
405 OriginalLoads[Indices] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000406 }
407
408 // Add a parameter to the function for each element passed in.
Chris Lattner1c676f72004-06-21 00:07:58 +0000409 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000410 E = ArgIndices.end(); SI != E; ++SI)
411 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
412
413 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
414 ++NumArgumentsPromoted;
415 else
416 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000417 }
418
419 const Type *RetTy = FTy->getReturnType();
420
421 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
422 // have zero fixed arguments.
423 bool ExtraArgHack = false;
424 if (Params.empty() && FTy->isVarArg()) {
425 ExtraArgHack = true;
426 Params.push_back(Type::IntTy);
427 }
428 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000429
Chris Lattner483ae012004-03-07 21:29:54 +0000430 // Create the new function body and insert it into the module...
431 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000432 NF->setCallingConv(F->getCallingConv());
Chris Lattner483ae012004-03-07 21:29:54 +0000433 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner254f8f82004-05-23 21:21:17 +0000434
435 // Get the alias analysis information that we need to update to reflect our
436 // changes.
437 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
438
Chris Lattner483ae012004-03-07 21:29:54 +0000439 // Loop over all of the callers of the function, transforming the call sites
440 // to pass in the loaded pointers.
441 //
442 std::vector<Value*> Args;
443 while (!F->use_empty()) {
444 CallSite CS = CallSite::get(F->use_back());
445 Instruction *Call = CS.getInstruction();
446
Chris Lattner254f8f82004-05-23 21:21:17 +0000447 // Loop over the operands, inserting GEP and loads in the caller as
448 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000449 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerd0525a22005-05-09 01:05:50 +0000450 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
451 I != E; ++I, ++AI)
Chris Lattner483ae012004-03-07 21:29:54 +0000452 if (!ArgsToPromote.count(I))
453 Args.push_back(*AI); // Unmodified argument
454 else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000455 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattner1c676f72004-06-21 00:07:58 +0000456 ScalarizeTable &ArgIndices = ScalarizedElements[I];
457 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000458 E = ArgIndices.end(); SI != E; ++SI) {
459 Value *V = *AI;
Chris Lattner254f8f82004-05-23 21:21:17 +0000460 LoadInst *OrigLoad = OriginalLoads[*SI];
461 if (!SI->empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000462 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
Chris Lattner254f8f82004-05-23 21:21:17 +0000463 AA.copyValue(OrigLoad->getOperand(0), V);
464 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000465 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner254f8f82004-05-23 21:21:17 +0000466 AA.copyValue(OrigLoad, Args.back());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000467 }
Chris Lattner483ae012004-03-07 21:29:54 +0000468 }
469
470 if (ExtraArgHack)
471 Args.push_back(Constant::getNullValue(Type::IntTy));
472
473 // Push any varargs arguments on the list
474 for (; AI != CS.arg_end(); ++AI)
475 Args.push_back(*AI);
476
477 Instruction *New;
478 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
479 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
480 Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000481 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner483ae012004-03-07 21:29:54 +0000482 } else {
483 New = new CallInst(NF, Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000484 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner324d2ee2005-05-06 06:46:58 +0000485 if (cast<CallInst>(Call)->isTailCall())
486 cast<CallInst>(New)->setTailCall();
Chris Lattner483ae012004-03-07 21:29:54 +0000487 }
488 Args.clear();
489
Chris Lattner254f8f82004-05-23 21:21:17 +0000490 // Update the alias analysis implementation to know that we are replacing
491 // the old call with a new one.
492 AA.replaceWithNewValue(Call, New);
493
Chris Lattner483ae012004-03-07 21:29:54 +0000494 if (!Call->use_empty()) {
495 Call->replaceAllUsesWith(New);
496 std::string Name = Call->getName();
497 Call->setName("");
498 New->setName(Name);
499 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000500
Chris Lattner483ae012004-03-07 21:29:54 +0000501 // Finally, remove the old call from the program, reducing the use-count of
502 // F.
503 Call->getParent()->getInstList().erase(Call);
504 }
505
506 // Since we have now created the new function, splice the body of the old
507 // function right into the new function, leaving the old rotting hulk of the
508 // function empty.
509 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
510
511 // Loop over the argument list, transfering uses of the old arguments over to
512 // the new arguments, also transfering over the names as well.
513 //
Chris Lattner531f9e92005-03-15 04:54:21 +0000514 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), I2 = NF->arg_begin();
Chris Lattner483ae012004-03-07 21:29:54 +0000515 I != E; ++I)
516 if (!ArgsToPromote.count(I)) {
517 // If this is an unmodified argument, move the name and users over to the
518 // new version.
519 I->replaceAllUsesWith(I2);
520 I2->setName(I->getName());
Chris Lattner254f8f82004-05-23 21:21:17 +0000521 AA.replaceWithNewValue(I, I2);
Chris Lattner483ae012004-03-07 21:29:54 +0000522 ++I2;
Chris Lattner254f8f82004-05-23 21:21:17 +0000523 } else if (I->use_empty()) {
524 AA.deleteValue(I);
525 } else {
Chris Lattner483ae012004-03-07 21:29:54 +0000526 // Otherwise, if we promoted this argument, then all users are load
527 // instructions, and all loads should be using the new argument that we
528 // added.
Chris Lattner1c676f72004-06-21 00:07:58 +0000529 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000530
Chris Lattner483ae012004-03-07 21:29:54 +0000531 while (!I->use_empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000532 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
533 assert(ArgIndices.begin()->empty() &&
534 "Load element should sort to front!");
535 I2->setName(I->getName()+".val");
536 LI->replaceAllUsesWith(I2);
Chris Lattner254f8f82004-05-23 21:21:17 +0000537 AA.replaceWithNewValue(LI, I2);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000538 LI->getParent()->getInstList().erase(LI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000539 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
540 << "' in function '" << F->getName() << "'\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000541 } else {
542 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
543 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
544
545 unsigned ArgNo = 0;
Chris Lattner531f9e92005-03-15 04:54:21 +0000546 Function::arg_iterator TheArg = I2;
Chris Lattner1c676f72004-06-21 00:07:58 +0000547 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000548 *It != Operands; ++It, ++TheArg) {
549 assert(It != ArgIndices.end() && "GEP not handled??");
550 }
551
552 std::string NewName = I->getName();
553 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
554 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
555 NewName += "."+itostr((int64_t)CI->getRawValue());
556 else
557 NewName += ".x";
558 TheArg->setName(NewName+".val");
559
560 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
561 << "' of function '" << F->getName() << "'\n");
562
563 // All of the uses must be load instructions. Replace them all with
564 // the argument specified by ArgNo.
565 while (!GEP->use_empty()) {
566 LoadInst *L = cast<LoadInst>(GEP->use_back());
567 L->replaceAllUsesWith(TheArg);
Chris Lattner254f8f82004-05-23 21:21:17 +0000568 AA.replaceWithNewValue(L, TheArg);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000569 L->getParent()->getInstList().erase(L);
570 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000571 AA.deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000572 GEP->getParent()->getInstList().erase(GEP);
573 }
Chris Lattner483ae012004-03-07 21:29:54 +0000574 }
Chris Lattnercc544e52004-03-07 22:52:53 +0000575
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000576 // Increment I2 past all of the arguments added for this promoted pointer.
577 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
578 ++I2;
Chris Lattner483ae012004-03-07 21:29:54 +0000579 }
580
Chris Lattner254f8f82004-05-23 21:21:17 +0000581 // Notify the alias analysis implementation that we inserted a new argument.
582 if (ExtraArgHack)
Chris Lattner531f9e92005-03-15 04:54:21 +0000583 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->arg_begin());
Chris Lattner254f8f82004-05-23 21:21:17 +0000584
585
586 // Tell the alias analysis that the old function is about to disappear.
587 AA.replaceWithNewValue(F, NF);
588
Chris Lattner483ae012004-03-07 21:29:54 +0000589 // Now that the old function is dead, delete it.
590 F->getParent()->getFunctionList().erase(F);
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000591 return NF;
Chris Lattner483ae012004-03-07 21:29:54 +0000592}