1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass promotes "by reference" arguments to be "by value" arguments. In
11 // practice, this means looking for internal functions that have pointer
12 // arguments. If we can prove, through the use of alias analysis, that that an
13 // 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
15 // of code and lead to the elimination of allocas (especially in C++ template
16 // code like the STL).
18 // 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
22 // operands for a large array or structure!
24 // 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
26 // case. This case would be best handled when and if we start supporting
27 // multiple return values from functions.
29 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "argpromotion"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Constants.h"
34 #include "llvm/DerivedTypes.h"
35 #include "llvm/Module.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/ADT/DepthFirstIterator.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
50 Statistic<> NumArgumentsPromoted("argpromotion",
51 "Number of pointer arguments promoted");
52 Statistic<> NumAggregatesPromoted("argpromotion",
53 "Number of aggregate arguments promoted");
54 Statistic<> NumArgumentsDead("argpromotion",
55 "Number of dead pointer args eliminated");
57 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59 class ArgPromotion : public Pass {
60 // WorkList - The set of internal functions that we have yet to process. As
61 // we eliminate arguments from a function, we push all callers into this set
62 // so that the by-reference argument can be bubbled out as far as possible.
63 // This set contains only internal functions.
64 std::set<Function*> WorkList;
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<AliasAnalysis>();
68 AU.addRequired<TargetData>();
71 virtual bool run(Module &M);
73 bool PromoteArguments(Function *F);
74 bool isSafeToPromoteArgument(Argument *Arg) const;
75 void DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
78 RegisterOpt<ArgPromotion> X("argpromotion",
79 "Promote 'by reference' arguments to scalars");
82 Pass *llvm::createArgumentPromotionPass() {
83 return new ArgPromotion();
86 bool ArgPromotion::run(Module &M) {
88 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
89 if (I->hasInternalLinkage())
92 while (!WorkList.empty()) {
93 Function *F = *WorkList.begin();
94 WorkList.erase(WorkList.begin());
96 if (PromoteArguments(F)) // Attempt to promote an argument.
97 Changed = true; // Remember that we changed something.
103 /// PromoteArguments - This method checks the specified function to see if there
104 /// are any promotable arguments and if it is safe to promote the function (for
105 /// example, all callers are direct). If safe to promote some arguments, it
106 /// calls the DoPromotion method.
108 bool ArgPromotion::PromoteArguments(Function *F) {
109 assert(F->hasInternalLinkage() && "We can only process internal functions!");
111 // First check: see if there are any pointer arguments! If not, quick exit.
112 std::vector<Argument*> PointerArgs;
113 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
114 if (isa<PointerType>(I->getType()))
115 PointerArgs.push_back(I);
116 if (PointerArgs.empty()) return false;
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();
122 CallSite CS = CallSite::get(*UI);
123 if (!CS.getInstruction()) // "Taking the address" of the function
126 // Ensure that this call site is CALLING the function, not passing it as
128 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
130 if (*AI == F) return false; // Passing the function address in!
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();
141 // No promotable pointer arguments.
142 if (PointerArgs.empty()) return false;
144 // Okay, promote all of the arguments are rewrite the callees!
145 DoPromotion(F, PointerArgs);
150 /// isSafeToPromoteArgument - As you might guess from the name of this method,
151 /// it checks to see if it is both safe and useful to promote the argument.
152 /// This method limits promotion of aggregates to only promote up to three
153 /// elements of the aggregate in order to avoid exploding the number of
154 /// arguments passed in.
155 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
156 // We can only promote this argument if all of the uses are loads, or are GEP
157 // instructions (with constant indices) that are subsequently loaded.
158 std::vector<LoadInst*> Loads;
159 std::vector<std::vector<ConstantInt*> > GEPIndices;
160 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
162 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
163 if (LI->isVolatile()) return false; // Don't hack volatile loads
165 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
166 if (GEP->use_empty()) {
167 // Dead GEP's cause trouble later. Just remove them if we run into
169 getAnalysis<AliasAnalysis>().deleteValue(GEP);
170 GEP->getParent()->getInstList().erase(GEP);
171 return isSafeToPromoteArgument(Arg);
173 // Ensure that all of the indices are constants.
174 std::vector<ConstantInt*> Operands;
175 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
176 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
177 Operands.push_back(C);
179 return false; // Not a constant operand GEP!
181 // Ensure that the only users of the GEP are load instructions.
182 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
184 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
185 if (LI->isVolatile()) return false; // Don't hack volatile loads
191 // See if there is already a GEP with these indices. If not, check to
192 // make sure that we aren't promoting too many elements. If so, nothing
194 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
196 if (GEPIndices.size() == 3) {
197 DEBUG(std::cerr << "argpromotion disable promoting argument '"
198 << Arg->getName() << "' because it would require adding more "
199 << "than 3 arguments to the function.\n");
200 // We limit aggregate promotion to only promoting up to three elements
204 GEPIndices.push_back(Operands);
207 return false; // Not a load or a GEP.
210 if (Loads.empty()) return true; // No users, this is a dead argument.
212 // Okay, now we know that the argument is only used by load instructions. Use
213 // alias analysis to check to see if the pointer is guaranteed to not be
214 // modified from entry of the function to each of the load instructions.
215 Function &F = *Arg->getParent();
217 // Because there could be several/many load instructions, remember which
218 // blocks we know to be transparent to the load.
219 std::set<BasicBlock*> TranspBlocks;
221 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
222 TargetData &TD = getAnalysis<TargetData>();
224 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
225 // Check to see if the load is invalidated from the start of the block to
227 LoadInst *Load = Loads[i];
228 BasicBlock *BB = Load->getParent();
230 const PointerType *LoadTy =
231 cast<PointerType>(Load->getOperand(0)->getType());
232 unsigned LoadSize = TD.getTypeSize(LoadTy->getElementType());
234 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
235 return false; // Pointer is invalidated!
237 // Now check every path from the entry block to the load for transparency.
238 // To do this, we perform a depth first search on the inverse CFG from the
240 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
241 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
242 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
243 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
247 // If the path from the entry of the function to each load is free of
248 // instructions that potentially invalidate the load, we can make the
254 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
255 /// elements are instances of ConstantInt.
257 struct GEPIdxComparator {
258 bool operator()(const std::vector<Value*> &LHS,
259 const std::vector<Value*> &RHS) const {
261 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
262 if (LHS[idx] != RHS[idx]) {
263 return cast<ConstantInt>(LHS[idx])->getRawValue() <
264 cast<ConstantInt>(RHS[idx])->getRawValue();
268 // Return less than if we ran out of stuff in LHS and we didn't run out of
270 return idx == LHS.size() && idx != RHS.size();
276 /// DoPromotion - This method actually performs the promotion of the specified
277 /// arguments. At this point, we know that it's safe to do so.
278 void ArgPromotion::DoPromotion(Function *F, std::vector<Argument*> &Args2Prom) {
279 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
281 // Start by computing a new prototype for the function, which is the same as
282 // the old function, but has modified arguments.
283 const FunctionType *FTy = F->getFunctionType();
284 std::vector<const Type*> Params;
286 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
288 // ScalarizedElements - If we are promoting a pointer that has elements
289 // accessed out of it, keep track of which elements are accessed so that we
290 // can add one argument for each.
292 // Arguments that are directly loaded will have a zero element value here, to
293 // handle cases where there are both a direct load and GEP accesses.
295 std::map<Argument*, ScalarizeTable> ScalarizedElements;
297 // OriginalLoads - Keep track of a representative load instruction from the
298 // original function so that we can tell the alias analysis implementation
299 // what the new GEP/Load instructions we are inserting look like.
300 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
302 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
303 if (!ArgsToPromote.count(I)) {
304 Params.push_back(I->getType());
305 } else if (I->use_empty()) {
308 // Okay, this is being promoted. Check to see if there are any GEP uses
310 ScalarizeTable &ArgIndices = ScalarizedElements[I];
311 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
313 Instruction *User = cast<Instruction>(*UI);
314 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
315 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
316 ArgIndices.insert(Indices);
318 if (LoadInst *L = dyn_cast<LoadInst>(User))
321 OrigLoad = cast<LoadInst>(User->use_back());
322 OriginalLoads[Indices] = OrigLoad;
325 // Add a parameter to the function for each element passed in.
326 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
327 E = ArgIndices.end(); SI != E; ++SI)
328 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
330 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
331 ++NumArgumentsPromoted;
333 ++NumAggregatesPromoted;
336 const Type *RetTy = FTy->getReturnType();
338 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
339 // have zero fixed arguments.
340 bool ExtraArgHack = false;
341 if (Params.empty() && FTy->isVarArg()) {
343 Params.push_back(Type::IntTy);
345 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
347 // Create the new function body and insert it into the module...
348 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
349 F->getParent()->getFunctionList().insert(F, NF);
351 // Get the alias analysis information that we need to update to reflect our
353 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
355 // Loop over all of the callers of the function, transforming the call sites
356 // to pass in the loaded pointers.
358 std::vector<Value*> Args;
359 while (!F->use_empty()) {
360 CallSite CS = CallSite::get(F->use_back());
361 Instruction *Call = CS.getInstruction();
363 // Make sure the caller of this function is revisited now that we promoted
364 // arguments in a callee of it.
365 if (Call->getParent()->getParent()->hasInternalLinkage())
366 WorkList.insert(Call->getParent()->getParent());
368 // Loop over the operands, inserting GEP and loads in the caller as
370 CallSite::arg_iterator AI = CS.arg_begin();
371 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
372 if (!ArgsToPromote.count(I))
373 Args.push_back(*AI); // Unmodified argument
374 else if (!I->use_empty()) {
375 // Non-dead argument: insert GEPs and loads as appropriate.
376 ScalarizeTable &ArgIndices = ScalarizedElements[I];
377 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
378 E = ArgIndices.end(); SI != E; ++SI) {
380 LoadInst *OrigLoad = OriginalLoads[*SI];
382 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
383 AA.copyValue(OrigLoad->getOperand(0), V);
385 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
386 AA.copyValue(OrigLoad, Args.back());
391 Args.push_back(Constant::getNullValue(Type::IntTy));
393 // Push any varargs arguments on the list
394 for (; AI != CS.arg_end(); ++AI)
398 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
399 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
402 New = new CallInst(NF, Args, "", Call);
406 // Update the alias analysis implementation to know that we are replacing
407 // the old call with a new one.
408 AA.replaceWithNewValue(Call, New);
410 if (!Call->use_empty()) {
411 Call->replaceAllUsesWith(New);
412 std::string Name = Call->getName();
417 // Finally, remove the old call from the program, reducing the use-count of
419 Call->getParent()->getInstList().erase(Call);
422 // Since we have now created the new function, splice the body of the old
423 // function right into the new function, leaving the old rotting hulk of the
425 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
427 // Loop over the argument list, transfering uses of the old arguments over to
428 // the new arguments, also transfering over the names as well.
430 for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
432 if (!ArgsToPromote.count(I)) {
433 // If this is an unmodified argument, move the name and users over to the
435 I->replaceAllUsesWith(I2);
436 I2->setName(I->getName());
437 AA.replaceWithNewValue(I, I2);
439 } else if (I->use_empty()) {
442 // Otherwise, if we promoted this argument, then all users are load
443 // instructions, and all loads should be using the new argument that we
445 ScalarizeTable &ArgIndices = ScalarizedElements[I];
447 while (!I->use_empty()) {
448 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
449 assert(ArgIndices.begin()->empty() &&
450 "Load element should sort to front!");
451 I2->setName(I->getName()+".val");
452 LI->replaceAllUsesWith(I2);
453 AA.replaceWithNewValue(LI, I2);
454 LI->getParent()->getInstList().erase(LI);
455 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
456 << "' in function '" << F->getName() << "'\n");
458 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
459 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
462 Function::aiterator TheArg = I2;
463 for (ScalarizeTable::iterator It = ArgIndices.begin();
464 *It != Operands; ++It, ++TheArg) {
465 assert(It != ArgIndices.end() && "GEP not handled??");
468 std::string NewName = I->getName();
469 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
470 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
471 NewName += "."+itostr((int64_t)CI->getRawValue());
474 TheArg->setName(NewName+".val");
476 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
477 << "' of function '" << F->getName() << "'\n");
479 // All of the uses must be load instructions. Replace them all with
480 // the argument specified by ArgNo.
481 while (!GEP->use_empty()) {
482 LoadInst *L = cast<LoadInst>(GEP->use_back());
483 L->replaceAllUsesWith(TheArg);
484 AA.replaceWithNewValue(L, TheArg);
485 L->getParent()->getInstList().erase(L);
488 GEP->getParent()->getInstList().erase(GEP);
492 // If we inserted a new pointer type, it's possible that IT could be
493 // promoted too. Also, increment I2 past all of the arguments added for
494 // this promoted pointer.
495 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i, ++I2)
496 if (isa<PointerType>(I2->getType()))
500 // Notify the alias analysis implementation that we inserted a new argument.
502 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->abegin());
505 // Tell the alias analysis that the old function is about to disappear.
506 AA.replaceWithNewValue(F, NF);
508 // Now that the old function is dead, delete it.
509 F->getParent()->getFunctionList().erase(F);