blob: 0876a2bde312840b725181c937c827a7bd067d21 [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//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000012// arguments. If it can prove, through the use of alias analysis, that an
13// argument is *only* loaded, then it can pass the value into the function
Chris Lattner483ae012004-03-07 21:29:54 +000014// 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
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000020// it refuses to scalarize aggregates which would require passing in more than
21// three operands to the function, because passing thousands of operands for a
22// large array or structure is unprofitable!
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
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000025// stored to (returning the value instead), but does not currently. This case
26// would be best handled when and if LLVM begins supporting multiple return
27// 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"
Duncan Sandsad0ea2d2007-11-27 13:23:08 +000038#include "llvm/ParameterAttributes.h"
Chris Lattner483ae012004-03-07 21:29:54 +000039#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner37b6c4f2004-09-18 00:34:13 +000040#include "llvm/Analysis/CallGraph.h"
Chris Lattner483ae012004-03-07 21:29:54 +000041#include "llvm/Target/TargetData.h"
42#include "llvm/Support/CallSite.h"
43#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000044#include "llvm/Support/Debug.h"
45#include "llvm/ADT/DepthFirstIterator.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/StringExtras.h"
Reid Spencer557ab152007-02-05 23:32:05 +000048#include "llvm/Support/Compiler.h"
Chris Lattner483ae012004-03-07 21:29:54 +000049#include <set>
50using namespace llvm;
51
Chris Lattner1631bcb2006-12-19 22:09:18 +000052STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
53STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
54STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
Chris Lattner483ae012004-03-07 21:29:54 +000055
Chris Lattner1631bcb2006-12-19 22:09:18 +000056namespace {
Chris Lattner483ae012004-03-07 21:29:54 +000057 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
58 ///
Reid Spencer557ab152007-02-05 23:32:05 +000059 struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
Chris Lattner483ae012004-03-07 21:29:54 +000060 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<AliasAnalysis>();
62 AU.addRequired<TargetData>();
Chris Lattner37b6c4f2004-09-18 00:34:13 +000063 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattner483ae012004-03-07 21:29:54 +000064 }
65
Chris Lattner37b6c4f2004-09-18 00:34:13 +000066 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Nick Lewyckye7da2d62007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +000068 ArgPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
69
Chris Lattner483ae012004-03-07 21:29:54 +000070 private:
Chris Lattner37b6c4f2004-09-18 00:34:13 +000071 bool PromoteArguments(CallGraphNode *CGN);
Misha Brukmanb1c93172005-04-21 23:48:37 +000072 bool isSafeToPromoteArgument(Argument *Arg) const;
Chris Lattnera8ba28f2008-01-11 18:43:58 +000073 Function *DoPromotion(Function *F,
74 SmallVectorImpl<Argument*> &ArgsToPromote);
Chris Lattner483ae012004-03-07 21:29:54 +000075 };
76
Devang Patel8c78a0b2007-05-03 01:11:54 +000077 char ArgPromotion::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +000078 RegisterPass<ArgPromotion> X("argpromotion",
79 "Promote 'by reference' arguments to scalars");
Chris Lattner483ae012004-03-07 21:29:54 +000080}
81
Devang Patel13058a52007-01-26 00:47:38 +000082Pass *llvm::createArgumentPromotionPass() {
Chris Lattner483ae012004-03-07 21:29:54 +000083 return new ArgPromotion();
84}
85
Chris Lattner37b6c4f2004-09-18 00:34:13 +000086bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
87 bool Changed = false, LocalChange;
Chris Lattner483ae012004-03-07 21:29:54 +000088
Chris Lattner9864df92004-09-19 01:05:16 +000089 do { // Iterate until we stop promoting from this SCC.
Chris Lattner37b6c4f2004-09-18 00:34:13 +000090 LocalChange = false;
91 // Attempt to promote arguments from all functions in this SCC.
92 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
93 LocalChange |= PromoteArguments(SCC[i]);
94 Changed |= LocalChange; // Remember that we changed something.
95 } while (LocalChange);
Misha Brukmanb1c93172005-04-21 23:48:37 +000096
Chris Lattner483ae012004-03-07 21:29:54 +000097 return Changed;
98}
99
Chris Lattner254f8f82004-05-23 21:21:17 +0000100/// PromoteArguments - This method checks the specified function to see if there
101/// are any promotable arguments and if it is safe to promote the function (for
102/// example, all callers are direct). If safe to promote some arguments, it
103/// calls the DoPromotion method.
104///
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000105bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
106 Function *F = CGN->getFunction();
107
108 // Make sure that it is local to this module.
109 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattner483ae012004-03-07 21:29:54 +0000110
111 // First check: see if there are any pointer arguments! If not, quick exit.
Chris Lattnera8ba28f2008-01-11 18:43:58 +0000112 SmallVector<Argument*, 16> PointerArgs;
Chris Lattner531f9e92005-03-15 04:54:21 +0000113 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner483ae012004-03-07 21:29:54 +0000114 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
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000144 // Okay, promote all of the arguments and rewrite the callees!
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000145 Function *NewF = DoPromotion(F, PointerArgs);
146
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000147 // Update the call graph to know that the function has been transformed.
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000148 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattner483ae012004-03-07 21:29:54 +0000149 return true;
150}
151
Chris Lattner244031d2004-11-13 23:31:34 +0000152/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
153/// to load.
154static bool IsAlwaysValidPointer(Value *V) {
155 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
156 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
157 return IsAlwaysValidPointer(GEP->getOperand(0));
158 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
159 if (CE->getOpcode() == Instruction::GetElementPtr)
160 return IsAlwaysValidPointer(CE->getOperand(0));
161
162 return false;
163}
164
165/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
166/// all callees pass in a valid pointer for the specified function argument.
167static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
168 Function *Callee = Arg->getParent();
169
Chris Lattnera06a8fd2007-02-13 02:10:56 +0000170 unsigned ArgNo = std::distance(Callee->arg_begin(),
171 Function::arg_iterator(Arg));
Chris Lattner244031d2004-11-13 23:31:34 +0000172
173 // Look at all call sites of the function. At this pointer we know we only
174 // have direct callees.
175 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
176 UI != E; ++UI) {
177 CallSite CS = CallSite::get(*UI);
178 assert(CS.getInstruction() && "Should only have direct calls!");
179
180 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
181 return false;
182 }
183 return true;
184}
185
Chris Lattner254f8f82004-05-23 21:21:17 +0000186
187/// isSafeToPromoteArgument - As you might guess from the name of this method,
188/// it checks to see if it is both safe and useful to promote the argument.
189/// This method limits promotion of aggregates to only promote up to three
190/// elements of the aggregate in order to avoid exploding the number of
191/// arguments passed in.
Chris Lattner483ae012004-03-07 21:29:54 +0000192bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000193 // We can only promote this argument if all of the uses are loads, or are GEP
194 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner244031d2004-11-13 23:31:34 +0000195 bool HasLoadInEntryBlock = false;
196 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattnera8ba28f2008-01-11 18:43:58 +0000197 SmallVector<LoadInst*, 16> Loads;
198 std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
Chris Lattner483ae012004-03-07 21:29:54 +0000199 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
200 UI != E; ++UI)
201 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
202 if (LI->isVolatile()) return false; // Don't hack volatile loads
203 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000204 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000205 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
206 if (GEP->use_empty()) {
207 // Dead GEP's cause trouble later. Just remove them if we run into
208 // them.
Chris Lattner254f8f82004-05-23 21:21:17 +0000209 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000210 GEP->getParent()->getInstList().erase(GEP);
211 return isSafeToPromoteArgument(Arg);
212 }
213 // Ensure that all of the indices are constants.
Chris Lattnera8ba28f2008-01-11 18:43:58 +0000214 SmallVector<ConstantInt*, 8> Operands;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000215 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattner1c676f72004-06-21 00:07:58 +0000216 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000217 Operands.push_back(C);
218 else
219 return false; // Not a constant operand GEP!
220
221 // Ensure that the only users of the GEP are load instructions.
222 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
223 UI != E; ++UI)
224 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
225 if (LI->isVolatile()) return false; // Don't hack volatile loads
226 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000227 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000228 } else {
229 return false;
230 }
231
Chris Lattner254f8f82004-05-23 21:21:17 +0000232 // See if there is already a GEP with these indices. If not, check to
233 // make sure that we aren't promoting too many elements. If so, nothing
234 // to do.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000235 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
236 GEPIndices.end()) {
237 if (GEPIndices.size() == 3) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000238 DOUT << "argpromotion disable promoting argument '"
239 << Arg->getName() << "' because it would require adding more "
240 << "than 3 arguments to the function.\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000241 // We limit aggregate promotion to only promoting up to three elements
242 // of the aggregate.
243 return false;
244 }
245 GEPIndices.push_back(Operands);
246 }
247 } else {
248 return false; // Not a load or a GEP.
249 }
Chris Lattner483ae012004-03-07 21:29:54 +0000250
Chris Lattner254f8f82004-05-23 21:21:17 +0000251 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattner483ae012004-03-07 21:29:54 +0000252
Chris Lattner244031d2004-11-13 23:31:34 +0000253 // If we decide that we want to promote this argument, the value is going to
254 // be unconditionally loaded in all callees. This is only safe to do if the
255 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
256 // of the pointer in the entry block of the function) or if we can prove that
257 // all pointers passed in are always to legal locations (for example, no null
258 // pointers are passed in, no pointers to free'd memory, etc).
Evan Chengff510a52006-10-03 07:26:07 +0000259 if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg))
Chris Lattner244031d2004-11-13 23:31:34 +0000260 return false; // Cannot prove that this is safe!!
261
262 // Okay, now we know that the argument is only used by load instructions and
263 // it is safe to unconditionally load the pointer. Use alias analysis to
264 // check to see if the pointer is guaranteed to not be modified from entry of
265 // the function to each of the load instructions.
Chris Lattner483ae012004-03-07 21:29:54 +0000266
267 // Because there could be several/many load instructions, remember which
268 // blocks we know to be transparent to the load.
269 std::set<BasicBlock*> TranspBlocks;
Owen Andersonedadd3f2006-09-15 05:22:51 +0000270
271 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000272 TargetData &TD = getAnalysis<TargetData>();
Chris Lattner483ae012004-03-07 21:29:54 +0000273
274 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
275 // Check to see if the load is invalidated from the start of the block to
276 // the load itself.
277 LoadInst *Load = Loads[i];
278 BasicBlock *BB = Load->getParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000279
280 const PointerType *LoadTy =
281 cast<PointerType>(Load->getOperand(0)->getType());
Duncan Sands44b87212007-11-01 20:53:16 +0000282 unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000283
Chris Lattner483ae012004-03-07 21:29:54 +0000284 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
285 return false; // Pointer is invalidated!
286
287 // Now check every path from the entry block to the load for transparency.
288 // To do this, we perform a depth first search on the inverse CFG from the
289 // loading block.
290 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
291 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
292 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
293 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
294 return false;
295 }
296
297 // If the path from the entry of the function to each load is free of
298 // instructions that potentially invalidate the load, we can make the
299 // transformation!
300 return true;
301}
302
Chris Lattner1c676f72004-06-21 00:07:58 +0000303namespace {
304 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
305 /// elements are instances of ConstantInt.
306 ///
307 struct GEPIdxComparator {
308 bool operator()(const std::vector<Value*> &LHS,
309 const std::vector<Value*> &RHS) const {
310 unsigned idx = 0;
311 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
312 if (LHS[idx] != RHS[idx]) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000313 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
314 cast<ConstantInt>(RHS[idx])->getZExtValue();
Chris Lattner1c676f72004-06-21 00:07:58 +0000315 }
316 }
317
318 // Return less than if we ran out of stuff in LHS and we didn't run out of
319 // stuff in RHS.
320 return idx == LHS.size() && idx != RHS.size();
321 }
322 };
323}
324
325
Chris Lattner254f8f82004-05-23 21:21:17 +0000326/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000327/// arguments, and returns the new function. At this point, we know that it's
328/// safe to do so.
329Function *ArgPromotion::DoPromotion(Function *F,
Chris Lattnera8ba28f2008-01-11 18:43:58 +0000330 SmallVectorImpl<Argument*> &Args2Prom) {
Chris Lattner483ae012004-03-07 21:29:54 +0000331 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000332
Chris Lattner483ae012004-03-07 21:29:54 +0000333 // Start by computing a new prototype for the function, which is the same as
334 // the old function, but has modified arguments.
335 const FunctionType *FTy = F->getFunctionType();
336 std::vector<const Type*> Params;
337
Chris Lattner1c676f72004-06-21 00:07:58 +0000338 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
339
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000340 // ScalarizedElements - If we are promoting a pointer that has elements
341 // accessed out of it, keep track of which elements are accessed so that we
342 // can add one argument for each.
343 //
344 // Arguments that are directly loaded will have a zero element value here, to
345 // handle cases where there are both a direct load and GEP accesses.
346 //
Chris Lattner1c676f72004-06-21 00:07:58 +0000347 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000348
Chris Lattner254f8f82004-05-23 21:21:17 +0000349 // OriginalLoads - Keep track of a representative load instruction from the
350 // original function so that we can tell the alias analysis implementation
351 // what the new GEP/Load instructions we are inserting look like.
352 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
353
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000354 // ParamAttrs - Keep track of the parameter attributes for the arguments
355 // that we are *not* promoting. For the ones that we do promote, the parameter
356 // attributes are lost
357 ParamAttrsVector ParamAttrsVec;
358 const ParamAttrsList *PAL = F->getParamAttrs();
359
360 unsigned index = 1;
361 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
362 ++I, ++index)
Chris Lattner483ae012004-03-07 21:29:54 +0000363 if (!ArgsToPromote.count(I)) {
364 Params.push_back(I->getType());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000365 if (PAL) {
366 unsigned attrs = PAL->getParamAttrs(index);
367 if (attrs)
368 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(),
369 attrs));
370 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000371 } else if (I->use_empty()) {
372 ++NumArgumentsDead;
373 } else {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000374 // Okay, this is being promoted. Check to see if there are any GEP uses
375 // of the argument.
Chris Lattner1c676f72004-06-21 00:07:58 +0000376 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000377 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
378 ++UI) {
379 Instruction *User = cast<Instruction>(*UI);
Owen Andersonedadd3f2006-09-15 05:22:51 +0000380 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
381 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
382 ArgIndices.insert(Indices);
383 LoadInst *OrigLoad;
384 if (LoadInst *L = dyn_cast<LoadInst>(User))
385 OrigLoad = L;
386 else
387 OrigLoad = cast<LoadInst>(User->use_back());
388 OriginalLoads[Indices] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000389 }
390
391 // Add a parameter to the function for each element passed in.
Chris Lattner1c676f72004-06-21 00:07:58 +0000392 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000393 E = ArgIndices.end(); SI != E; ++SI)
Chris Lattnera7315132007-02-12 22:56:41 +0000394 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
David Greenec656cbb2007-09-04 15:46:09 +0000395 SI->begin(),
396 SI->end()));
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000397
398 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
399 ++NumArgumentsPromoted;
400 else
401 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000402 }
403
404 const Type *RetTy = FTy->getReturnType();
405
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000406 // Recompute the parameter attributes list based on the new arguments for
407 // the function.
408 if (ParamAttrsVec.empty())
409 PAL = 0;
410 else
411 PAL = ParamAttrsList::get(ParamAttrsVec);
412
Chris Lattner483ae012004-03-07 21:29:54 +0000413 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
414 // have zero fixed arguments.
415 bool ExtraArgHack = false;
416 if (Params.empty() && FTy->isVarArg()) {
417 ExtraArgHack = true;
Reid Spencerc635f472006-12-31 05:48:39 +0000418 Params.push_back(Type::Int32Ty);
Chris Lattner483ae012004-03-07 21:29:54 +0000419 }
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000420
421 // Construct the new function type using the new arguments.
Chris Lattner483ae012004-03-07 21:29:54 +0000422 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000423
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000424 // Create the new function body and insert it into the module...
Chris Lattner483ae012004-03-07 21:29:54 +0000425 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000426 NF->setCallingConv(F->getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000427 NF->setParamAttrs(PAL);
Gordon Henriksen520e64c2007-12-25 22:16:06 +0000428 if (F->hasCollector())
429 NF->setCollector(F->getCollector());
Chris Lattner483ae012004-03-07 21:29:54 +0000430 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner254f8f82004-05-23 21:21:17 +0000431
432 // Get the alias analysis information that we need to update to reflect our
433 // changes.
434 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
435
Chris Lattner483ae012004-03-07 21:29:54 +0000436 // Loop over all of the callers of the function, transforming the call sites
437 // to pass in the loaded pointers.
438 //
439 std::vector<Value*> Args;
440 while (!F->use_empty()) {
441 CallSite CS = CallSite::get(F->use_back());
442 Instruction *Call = CS.getInstruction();
443
Chris Lattner254f8f82004-05-23 21:21:17 +0000444 // Loop over the operands, inserting GEP and loads in the caller as
445 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000446 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerd0525a22005-05-09 01:05:50 +0000447 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
448 I != E; ++I, ++AI)
Chris Lattner483ae012004-03-07 21:29:54 +0000449 if (!ArgsToPromote.count(I))
450 Args.push_back(*AI); // Unmodified argument
451 else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000452 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattner1c676f72004-06-21 00:07:58 +0000453 ScalarizeTable &ArgIndices = ScalarizedElements[I];
454 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000455 E = ArgIndices.end(); SI != E; ++SI) {
456 Value *V = *AI;
Chris Lattner254f8f82004-05-23 21:21:17 +0000457 LoadInst *OrigLoad = OriginalLoads[*SI];
458 if (!SI->empty()) {
David Greenec656cbb2007-09-04 15:46:09 +0000459 V = new GetElementPtrInst(V, SI->begin(), SI->end(),
Chris Lattnera7315132007-02-12 22:56:41 +0000460 V->getName()+".idx", Call);
Chris Lattner254f8f82004-05-23 21:21:17 +0000461 AA.copyValue(OrigLoad->getOperand(0), V);
462 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000463 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner254f8f82004-05-23 21:21:17 +0000464 AA.copyValue(OrigLoad, Args.back());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000465 }
Chris Lattner483ae012004-03-07 21:29:54 +0000466 }
467
468 if (ExtraArgHack)
Reid Spencerc635f472006-12-31 05:48:39 +0000469 Args.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattner483ae012004-03-07 21:29:54 +0000470
471 // Push any varargs arguments on the list
472 for (; AI != CS.arg_end(); ++AI)
473 Args.push_back(*AI);
474
475 Instruction *New;
476 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
477 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
David Greene703623d2007-08-27 19:04:21 +0000478 Args.begin(), Args.end(), "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000479 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000480 cast<InvokeInst>(New)->setParamAttrs(PAL);
Chris Lattner483ae012004-03-07 21:29:54 +0000481 } else {
David Greene17a5dfe2007-08-01 03:43:44 +0000482 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000483 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000484 cast<CallInst>(New)->setParamAttrs(PAL);
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);
Chris Lattner8d4c36b2007-02-11 01:08:35 +0000496 New->takeName(Call);
Chris Lattner483ae012004-03-07 21:29:54 +0000497 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000498
Chris Lattner483ae012004-03-07 21:29:54 +0000499 // Finally, remove the old call from the program, reducing the use-count of
500 // F.
501 Call->getParent()->getInstList().erase(Call);
502 }
503
504 // Since we have now created the new function, splice the body of the old
505 // function right into the new function, leaving the old rotting hulk of the
506 // function empty.
507 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
508
509 // Loop over the argument list, transfering uses of the old arguments over to
510 // the new arguments, also transfering over the names as well.
511 //
Chris Lattnera06a8fd2007-02-13 02:10:56 +0000512 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
513 I2 = NF->arg_begin(); I != E; ++I)
Chris Lattner483ae012004-03-07 21:29:54 +0000514 if (!ArgsToPromote.count(I)) {
515 // If this is an unmodified argument, move the name and users over to the
516 // new version.
517 I->replaceAllUsesWith(I2);
Chris Lattner8d4c36b2007-02-11 01:08:35 +0000518 I2->takeName(I);
Chris Lattner254f8f82004-05-23 21:21:17 +0000519 AA.replaceWithNewValue(I, I2);
Chris Lattner483ae012004-03-07 21:29:54 +0000520 ++I2;
Chris Lattner254f8f82004-05-23 21:21:17 +0000521 } else if (I->use_empty()) {
522 AA.deleteValue(I);
523 } else {
Chris Lattner483ae012004-03-07 21:29:54 +0000524 // Otherwise, if we promoted this argument, then all users are load
525 // instructions, and all loads should be using the new argument that we
526 // added.
Chris Lattner1c676f72004-06-21 00:07:58 +0000527 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000528
Chris Lattner483ae012004-03-07 21:29:54 +0000529 while (!I->use_empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000530 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
531 assert(ArgIndices.begin()->empty() &&
532 "Load element should sort to front!");
533 I2->setName(I->getName()+".val");
534 LI->replaceAllUsesWith(I2);
Chris Lattner254f8f82004-05-23 21:21:17 +0000535 AA.replaceWithNewValue(LI, I2);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000536 LI->getParent()->getInstList().erase(LI);
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000537 DOUT << "*** Promoted load of argument '" << I->getName()
538 << "' in function '" << F->getName() << "'\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000539 } else {
540 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
541 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
542
Chris Lattner531f9e92005-03-15 04:54:21 +0000543 Function::arg_iterator TheArg = I2;
Chris Lattner1c676f72004-06-21 00:07:58 +0000544 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000545 *It != Operands; ++It, ++TheArg) {
546 assert(It != ArgIndices.end() && "GEP not handled??");
547 }
548
549 std::string NewName = I->getName();
550 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
551 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
Chris Lattnerb0f158c2007-08-23 05:15:32 +0000552 NewName += "." + CI->getValue().toStringUnsigned(10);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000553 else
554 NewName += ".x";
555 TheArg->setName(NewName+".val");
556
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000557 DOUT << "*** Promoted agg argument '" << TheArg->getName()
558 << "' of function '" << F->getName() << "'\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000559
560 // All of the uses must be load instructions. Replace them all with
561 // the argument specified by ArgNo.
562 while (!GEP->use_empty()) {
563 LoadInst *L = cast<LoadInst>(GEP->use_back());
564 L->replaceAllUsesWith(TheArg);
Chris Lattner254f8f82004-05-23 21:21:17 +0000565 AA.replaceWithNewValue(L, TheArg);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000566 L->getParent()->getInstList().erase(L);
567 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000568 AA.deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000569 GEP->getParent()->getInstList().erase(GEP);
570 }
Chris Lattner483ae012004-03-07 21:29:54 +0000571 }
Chris Lattnercc544e52004-03-07 22:52:53 +0000572
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000573 // Increment I2 past all of the arguments added for this promoted pointer.
574 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
575 ++I2;
Chris Lattner483ae012004-03-07 21:29:54 +0000576 }
577
Chris Lattner254f8f82004-05-23 21:21:17 +0000578 // Notify the alias analysis implementation that we inserted a new argument.
579 if (ExtraArgHack)
Reid Spencerc635f472006-12-31 05:48:39 +0000580 AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
Chris Lattner254f8f82004-05-23 21:21:17 +0000581
582
583 // Tell the alias analysis that the old function is about to disappear.
584 AA.replaceWithNewValue(F, NF);
585
Chris Lattner483ae012004-03-07 21:29:54 +0000586 // Now that the old function is dead, delete it.
587 F->getParent()->getFunctionList().erase(F);
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000588 return NF;
Chris Lattner483ae012004-03-07 21:29:54 +0000589}