blob: c6e27b4d627a7ccb36831a4d629af7bd64aa6dde [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//
Chris Lattner4ee451d2007-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 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
Gordon Henriksen55cbec32007-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 Lattnered570a72004-03-07 21:29:54 +000014// 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
Chris Lattnerbcd203c2008-04-19 19:50:01 +000020// by default it refuses to scalarize aggregates which would require passing in more than
Gordon Henriksen55cbec32007-10-26 03:03:51 +000021// three operands to the function, because passing thousands of operands for a
Chris Lattnerbcd203c2008-04-19 19:50:01 +000022// large array or structure is unprofitable! This limit is can be configured or
23// disabled, however.
Chris Lattner9440db82004-03-08 01:04:36 +000024//
Chris Lattnered570a72004-03-07 21:29:54 +000025// Note that this transformation could also be done for arguments that are only
Gordon Henriksen55cbec32007-10-26 03:03:51 +000026// stored to (returning the value instead), but does not currently. This case
27// would be best handled when and if LLVM begins supporting multiple return
28// values from functions.
Chris Lattnered570a72004-03-07 21:29:54 +000029//
30//===----------------------------------------------------------------------===//
31
Chris Lattner9e7cc2f2004-05-23 21:21:17 +000032#define DEBUG_TYPE "argpromotion"
Chris Lattnered570a72004-03-07 21:29:54 +000033#include "llvm/Transforms/IPO.h"
34#include "llvm/Constants.h"
35#include "llvm/DerivedTypes.h"
36#include "llvm/Module.h"
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000037#include "llvm/CallGraphSCCPass.h"
Chris Lattnered570a72004-03-07 21:29:54 +000038#include "llvm/Instructions.h"
39#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000040#include "llvm/Analysis/CallGraph.h"
Chris Lattnered570a72004-03-07 21:29:54 +000041#include "llvm/Target/TargetData.h"
42#include "llvm/Support/CallSite.h"
43#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-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 Spencer9133fe22007-02-05 23:32:05 +000048#include "llvm/Support/Compiler.h"
Chris Lattnered570a72004-03-07 21:29:54 +000049#include <set>
50using namespace llvm;
51
Chris Lattner86453c52006-12-19 22:09:18 +000052STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
53STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
Chris Lattner10603e02008-01-11 22:31:41 +000054STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
Chris Lattner86453c52006-12-19 22:09:18 +000055STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
Chris Lattnered570a72004-03-07 21:29:54 +000056
Chris Lattner86453c52006-12-19 22:09:18 +000057namespace {
Chris Lattnered570a72004-03-07 21:29:54 +000058 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59 ///
Reid Spencer9133fe22007-02-05 23:32:05 +000060 struct VISIBILITY_HIDDEN 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);
Nick Lewyckyecd94c82007-05-06 13:37:16 +000068 static char ID; // Pass identification, replacement for typeid
Chris Lattnerbcd203c2008-04-19 19:50:01 +000069 ArgPromotion(unsigned maxElements = 3) : CallGraphSCCPass((intptr_t)&ID), maxElements(maxElements) {}
Devang Patel794fd752007-05-01 21:15:47 +000070
Chris Lattnered570a72004-03-07 21:29:54 +000071 private:
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000072 bool PromoteArguments(CallGraphNode *CGN);
Chris Lattner40c14be2008-01-11 19:20:39 +000073 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
Chris Lattnera10145f2008-01-11 18:43:58 +000074 Function *DoPromotion(Function *F,
Chris Lattner10603e02008-01-11 22:31:41 +000075 SmallPtrSet<Argument*, 8> &ArgsToPromote,
76 SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
Chris Lattnerbcd203c2008-04-19 19:50:01 +000077 /// The maximum number of elements to expand, or 0 for unlimited.
78 unsigned maxElements;
Chris Lattnered570a72004-03-07 21:29:54 +000079 };
80
Devang Patel19974732007-05-03 01:11:54 +000081 char ArgPromotion::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000082 RegisterPass<ArgPromotion> X("argpromotion",
83 "Promote 'by reference' arguments to scalars");
Chris Lattnered570a72004-03-07 21:29:54 +000084}
85
Chris Lattnerbcd203c2008-04-19 19:50:01 +000086Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
87 return new ArgPromotion(maxElements);
Chris Lattnered570a72004-03-07 21:29:54 +000088}
89
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000090bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
91 bool Changed = false, LocalChange;
Chris Lattnered570a72004-03-07 21:29:54 +000092
Chris Lattnerf5afcab2004-09-19 01:05:16 +000093 do { // Iterate until we stop promoting from this SCC.
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000094 LocalChange = false;
95 // Attempt to promote arguments from all functions in this SCC.
96 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
97 LocalChange |= PromoteArguments(SCC[i]);
98 Changed |= LocalChange; // Remember that we changed something.
99 } while (LocalChange);
Misha Brukmanfd939082005-04-21 23:48:37 +0000100
Chris Lattnered570a72004-03-07 21:29:54 +0000101 return Changed;
102}
103
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000104/// PromoteArguments - This method checks the specified function to see if there
105/// are any promotable arguments and if it is safe to promote the function (for
106/// example, all callers are direct). If safe to promote some arguments, it
107/// calls the DoPromotion method.
108///
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000109bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
110 Function *F = CGN->getFunction();
111
112 // Make sure that it is local to this module.
113 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattnered570a72004-03-07 21:29:54 +0000114
115 // First check: see if there are any pointer arguments! If not, quick exit.
Chris Lattner40c14be2008-01-11 19:20:39 +0000116 SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
117 unsigned ArgNo = 0;
118 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
119 I != E; ++I, ++ArgNo)
Chris Lattnered570a72004-03-07 21:29:54 +0000120 if (isa<PointerType>(I->getType()))
Chris Lattner40c14be2008-01-11 19:20:39 +0000121 PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
Chris Lattnered570a72004-03-07 21:29:54 +0000122 if (PointerArgs.empty()) return false;
123
124 // Second check: make sure that all callers are direct callers. We can't
125 // transform functions that have indirect callers.
126 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner7db5a6d2004-03-07 22:43:27 +0000127 UI != E; ++UI) {
128 CallSite CS = CallSite::get(*UI);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000129 if (!CS.getInstruction()) // "Taking the address" of the function
130 return false;
131
132 // Ensure that this call site is CALLING the function, not passing it as
133 // an argument.
Chris Lattnerf1577012008-01-11 18:55:10 +0000134 if (UI.getOperandNo() != 0)
135 return false;
Chris Lattner7db5a6d2004-03-07 22:43:27 +0000136 }
Chris Lattnered570a72004-03-07 21:29:54 +0000137
Chris Lattner40c14be2008-01-11 19:20:39 +0000138 // Check to see which arguments are promotable. If an argument is promotable,
139 // add it to ArgsToPromote.
140 SmallPtrSet<Argument*, 8> ArgsToPromote;
Chris Lattner10603e02008-01-11 22:31:41 +0000141 SmallPtrSet<Argument*, 8> ByValArgsToTransform;
Chris Lattner40c14be2008-01-11 19:20:39 +0000142 for (unsigned i = 0; i != PointerArgs.size(); ++i) {
Chris Lattner10603e02008-01-11 22:31:41 +0000143 bool isByVal = F->paramHasAttr(PointerArgs[i].second+1, ParamAttr::ByVal);
144
145 // If this is a byval argument, and if the aggregate type is small, just
146 // pass the elements, which is always safe.
147 Argument *PtrArg = PointerArgs[i].first;
148 if (isByVal) {
149 const Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
150 if (const StructType *STy = dyn_cast<StructType>(AgTy))
Chris Lattnerbcd203c2008-04-19 19:50:01 +0000151 if (maxElements > 0 && STy->getNumElements() > maxElements) {
152 DOUT << "argpromotion disable promoting argument '"
153 << PtrArg->getName() << "' because it would require adding more "
154 << "than " << maxElements << " arguments to the function.\n";
155 } else {
Chris Lattner10603e02008-01-11 22:31:41 +0000156 // If all the elements are first class types, we can promote it.
157 bool AllSimple = true;
158 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
159 if (!STy->getElementType(i)->isFirstClassType()) {
160 AllSimple = false;
161 break;
162 }
163
164 // Safe to transform, don't even bother trying to "promote" it.
165 // Passing the elements as a scalar will allow scalarrepl to hack on
166 // the new alloca we introduce.
167 if (AllSimple) {
168 ByValArgsToTransform.insert(PtrArg);
169 continue;
170 }
171 }
172 }
173
174 // Otherwise, see if we can promote the pointer to its value.
175 if (isSafeToPromoteArgument(PtrArg, isByVal))
176 ArgsToPromote.insert(PtrArg);
Chris Lattner40c14be2008-01-11 19:20:39 +0000177 }
178
Chris Lattnered570a72004-03-07 21:29:54 +0000179 // No promotable pointer arguments.
Chris Lattner10603e02008-01-11 22:31:41 +0000180 if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) return false;
Chris Lattnered570a72004-03-07 21:29:54 +0000181
Chris Lattner10603e02008-01-11 22:31:41 +0000182 Function *NewF = DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000183
Duncan Sandsdc024672007-11-27 13:23:08 +0000184 // Update the call graph to know that the function has been transformed.
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000185 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattnered570a72004-03-07 21:29:54 +0000186 return true;
187}
188
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000189/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
190/// to load.
191static bool IsAlwaysValidPointer(Value *V) {
192 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
193 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
194 return IsAlwaysValidPointer(GEP->getOperand(0));
195 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
196 if (CE->getOpcode() == Instruction::GetElementPtr)
197 return IsAlwaysValidPointer(CE->getOperand(0));
198
199 return false;
200}
201
202/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
203/// all callees pass in a valid pointer for the specified function argument.
204static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
205 Function *Callee = Arg->getParent();
206
Chris Lattner93e985f2007-02-13 02:10:56 +0000207 unsigned ArgNo = std::distance(Callee->arg_begin(),
208 Function::arg_iterator(Arg));
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000209
210 // Look at all call sites of the function. At this pointer we know we only
211 // have direct callees.
212 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
213 UI != E; ++UI) {
214 CallSite CS = CallSite::get(*UI);
215 assert(CS.getInstruction() && "Should only have direct calls!");
216
217 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
218 return false;
219 }
220 return true;
221}
222
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000223
224/// isSafeToPromoteArgument - As you might guess from the name of this method,
225/// it checks to see if it is both safe and useful to promote the argument.
226/// This method limits promotion of aggregates to only promote up to three
227/// elements of the aggregate in order to avoid exploding the number of
228/// arguments passed in.
Chris Lattner40c14be2008-01-11 19:20:39 +0000229bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
Chris Lattner9440db82004-03-08 01:04:36 +0000230 // We can only promote this argument if all of the uses are loads, or are GEP
231 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner170b1812008-01-11 19:34:32 +0000232
233 // We can also only promote the load if we can guarantee that it will happen.
234 // Promoting a load causes the load to be unconditionally executed in the
235 // caller, so we can't turn a conditional load into an unconditional load in
236 // general.
237 bool SafeToUnconditionallyLoad = false;
238 if (isByVal) // ByVal arguments are always safe to load from.
239 SafeToUnconditionallyLoad = true;
240
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000241 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattnera10145f2008-01-11 18:43:58 +0000242 SmallVector<LoadInst*, 16> Loads;
243 std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
Chris Lattnered570a72004-03-07 21:29:54 +0000244 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
245 UI != E; ++UI)
246 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
247 if (LI->isVolatile()) return false; // Don't hack volatile loads
248 Loads.push_back(LI);
Chris Lattner170b1812008-01-11 19:34:32 +0000249
250 // If this load occurs in the entry block, then the pointer is
251 // unconditionally loaded.
252 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-03-08 01:04:36 +0000253 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
254 if (GEP->use_empty()) {
255 // Dead GEP's cause trouble later. Just remove them if we run into
256 // them.
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000257 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattner40c14be2008-01-11 19:20:39 +0000258 GEP->eraseFromParent();
259 return isSafeToPromoteArgument(Arg, isByVal);
Chris Lattner9440db82004-03-08 01:04:36 +0000260 }
261 // Ensure that all of the indices are constants.
Chris Lattnera10145f2008-01-11 18:43:58 +0000262 SmallVector<ConstantInt*, 8> Operands;
Chris Lattner9440db82004-03-08 01:04:36 +0000263 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattnerbeabf452004-06-21 00:07:58 +0000264 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattner9440db82004-03-08 01:04:36 +0000265 Operands.push_back(C);
266 else
267 return false; // Not a constant operand GEP!
268
269 // Ensure that the only users of the GEP are load instructions.
270 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
271 UI != E; ++UI)
272 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
273 if (LI->isVolatile()) return false; // Don't hack volatile loads
274 Loads.push_back(LI);
Chris Lattner170b1812008-01-11 19:34:32 +0000275
276 // If this load occurs in the entry block, then the pointer is
277 // unconditionally loaded.
278 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-03-08 01:04:36 +0000279 } else {
280 return false;
281 }
282
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000283 // See if there is already a GEP with these indices. If not, check to
284 // make sure that we aren't promoting too many elements. If so, nothing
285 // to do.
Chris Lattner9440db82004-03-08 01:04:36 +0000286 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
287 GEPIndices.end()) {
Chris Lattnerbcd203c2008-04-19 19:50:01 +0000288 if (maxElements > 0 && GEPIndices.size() == maxElements) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000289 DOUT << "argpromotion disable promoting argument '"
290 << Arg->getName() << "' because it would require adding more "
Chris Lattnerbcd203c2008-04-19 19:50:01 +0000291 << "than " << maxElements << " arguments to the function.\n";
292 // We limit aggregate promotion to only promoting up to a fixed number
293 // of elements of the aggregate.
Chris Lattner9440db82004-03-08 01:04:36 +0000294 return false;
295 }
296 GEPIndices.push_back(Operands);
297 }
298 } else {
299 return false; // Not a load or a GEP.
300 }
Chris Lattnered570a72004-03-07 21:29:54 +0000301
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000302 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattnered570a72004-03-07 21:29:54 +0000303
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000304 // If we decide that we want to promote this argument, the value is going to
305 // be unconditionally loaded in all callees. This is only safe to do if the
306 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
307 // of the pointer in the entry block of the function) or if we can prove that
308 // all pointers passed in are always to legal locations (for example, no null
309 // pointers are passed in, no pointers to free'd memory, etc).
Chris Lattner170b1812008-01-11 19:34:32 +0000310 if (!SafeToUnconditionallyLoad &&
311 !AllCalleesPassInValidPointerForArgument(Arg))
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000312 return false; // Cannot prove that this is safe!!
313
314 // Okay, now we know that the argument is only used by load instructions and
315 // it is safe to unconditionally load the pointer. Use alias analysis to
316 // check to see if the pointer is guaranteed to not be modified from entry of
317 // the function to each of the load instructions.
Chris Lattnered570a72004-03-07 21:29:54 +0000318
319 // Because there could be several/many load instructions, remember which
320 // blocks we know to be transparent to the load.
Chris Lattnere027efa2008-01-11 19:36:30 +0000321 SmallPtrSet<BasicBlock*, 16> TranspBlocks;
Owen Anderson46f022a2006-09-15 05:22:51 +0000322
323 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner9440db82004-03-08 01:04:36 +0000324 TargetData &TD = getAnalysis<TargetData>();
Chris Lattnered570a72004-03-07 21:29:54 +0000325
326 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
327 // Check to see if the load is invalidated from the start of the block to
328 // the load itself.
329 LoadInst *Load = Loads[i];
330 BasicBlock *BB = Load->getParent();
Chris Lattner9440db82004-03-08 01:04:36 +0000331
332 const PointerType *LoadTy =
333 cast<PointerType>(Load->getOperand(0)->getType());
Duncan Sands514ab342007-11-01 20:53:16 +0000334 unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
Chris Lattner9440db82004-03-08 01:04:36 +0000335
Chris Lattnered570a72004-03-07 21:29:54 +0000336 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
337 return false; // Pointer is invalidated!
338
339 // Now check every path from the entry block to the load for transparency.
340 // To do this, we perform a depth first search on the inverse CFG from the
341 // loading block.
342 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Chris Lattnere027efa2008-01-11 19:36:30 +0000343 for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
344 I = idf_ext_begin(*PI, TranspBlocks),
Chris Lattnered570a72004-03-07 21:29:54 +0000345 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
346 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
347 return false;
348 }
349
350 // If the path from the entry of the function to each load is free of
351 // instructions that potentially invalidate the load, we can make the
352 // transformation!
353 return true;
354}
355
Chris Lattnerbeabf452004-06-21 00:07:58 +0000356namespace {
357 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
358 /// elements are instances of ConstantInt.
359 ///
360 struct GEPIdxComparator {
361 bool operator()(const std::vector<Value*> &LHS,
362 const std::vector<Value*> &RHS) const {
363 unsigned idx = 0;
364 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
365 if (LHS[idx] != RHS[idx]) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000366 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
367 cast<ConstantInt>(RHS[idx])->getZExtValue();
Chris Lattnerbeabf452004-06-21 00:07:58 +0000368 }
369 }
370
371 // Return less than if we ran out of stuff in LHS and we didn't run out of
372 // stuff in RHS.
373 return idx == LHS.size() && idx != RHS.size();
374 }
375 };
376}
377
378
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000379/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000380/// arguments, and returns the new function. At this point, we know that it's
381/// safe to do so.
382Function *ArgPromotion::DoPromotion(Function *F,
Chris Lattner10603e02008-01-11 22:31:41 +0000383 SmallPtrSet<Argument*, 8> &ArgsToPromote,
384 SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000385
Chris Lattnered570a72004-03-07 21:29:54 +0000386 // Start by computing a new prototype for the function, which is the same as
387 // the old function, but has modified arguments.
388 const FunctionType *FTy = F->getFunctionType();
389 std::vector<const Type*> Params;
390
Chris Lattnerbeabf452004-06-21 00:07:58 +0000391 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
392
Chris Lattner9440db82004-03-08 01:04:36 +0000393 // ScalarizedElements - If we are promoting a pointer that has elements
394 // accessed out of it, keep track of which elements are accessed so that we
395 // can add one argument for each.
396 //
397 // Arguments that are directly loaded will have a zero element value here, to
398 // handle cases where there are both a direct load and GEP accesses.
399 //
Chris Lattnerbeabf452004-06-21 00:07:58 +0000400 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattner9440db82004-03-08 01:04:36 +0000401
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000402 // OriginalLoads - Keep track of a representative load instruction from the
403 // original function so that we can tell the alias analysis implementation
404 // what the new GEP/Load instructions we are inserting look like.
405 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
406
Duncan Sandsdc024672007-11-27 13:23:08 +0000407 // ParamAttrs - Keep track of the parameter attributes for the arguments
408 // that we are *not* promoting. For the ones that we do promote, the parameter
409 // attributes are lost
Chris Lattner58d74912008-03-12 17:45:29 +0000410 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
411 const PAListPtr &PAL = F->getParamAttrs();
Duncan Sandsdc024672007-11-27 13:23:08 +0000412
Duncan Sands532d0222008-02-01 20:37:16 +0000413 // Add any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000414 if (ParameterAttributes attrs = PAL.getParamAttrs(0))
Duncan Sands532d0222008-02-01 20:37:16 +0000415 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
416
Chris Lattnerab04e132008-01-17 01:17:03 +0000417 unsigned ArgIndex = 1;
Duncan Sandsdc024672007-11-27 13:23:08 +0000418 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
Chris Lattnerab04e132008-01-17 01:17:03 +0000419 ++I, ++ArgIndex) {
Chris Lattner10603e02008-01-11 22:31:41 +0000420 if (ByValArgsToTransform.count(I)) {
421 // Just add all the struct element types.
422 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
423 const StructType *STy = cast<StructType>(AgTy);
424 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
425 Params.push_back(STy->getElementType(i));
426 ++NumByValArgsPromoted;
427 } else if (!ArgsToPromote.count(I)) {
Chris Lattnered570a72004-03-07 21:29:54 +0000428 Params.push_back(I->getType());
Chris Lattner58d74912008-03-12 17:45:29 +0000429 if (ParameterAttributes attrs = PAL.getParamAttrs(ArgIndex))
Chris Lattner10603e02008-01-11 22:31:41 +0000430 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000431 } else if (I->use_empty()) {
432 ++NumArgumentsDead;
433 } else {
Chris Lattner9440db82004-03-08 01:04:36 +0000434 // Okay, this is being promoted. Check to see if there are any GEP uses
435 // of the argument.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000436 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattner9440db82004-03-08 01:04:36 +0000437 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
438 ++UI) {
439 Instruction *User = cast<Instruction>(*UI);
Owen Anderson46f022a2006-09-15 05:22:51 +0000440 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
441 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
442 ArgIndices.insert(Indices);
443 LoadInst *OrigLoad;
444 if (LoadInst *L = dyn_cast<LoadInst>(User))
445 OrigLoad = L;
446 else
447 OrigLoad = cast<LoadInst>(User->use_back());
448 OriginalLoads[Indices] = OrigLoad;
Chris Lattner9440db82004-03-08 01:04:36 +0000449 }
450
451 // Add a parameter to the function for each element passed in.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000452 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000453 E = ArgIndices.end(); SI != E; ++SI)
Chris Lattner1ccd1852007-02-12 22:56:41 +0000454 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
David Greeneb8f74792007-09-04 15:46:09 +0000455 SI->begin(),
456 SI->end()));
Chris Lattner9440db82004-03-08 01:04:36 +0000457
458 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
459 ++NumArgumentsPromoted;
460 else
461 ++NumAggregatesPromoted;
Chris Lattnered570a72004-03-07 21:29:54 +0000462 }
Chris Lattner10603e02008-01-11 22:31:41 +0000463 }
Chris Lattnered570a72004-03-07 21:29:54 +0000464
465 const Type *RetTy = FTy->getReturnType();
466
467 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
468 // have zero fixed arguments.
469 bool ExtraArgHack = false;
470 if (Params.empty() && FTy->isVarArg()) {
471 ExtraArgHack = true;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000472 Params.push_back(Type::Int32Ty);
Chris Lattnered570a72004-03-07 21:29:54 +0000473 }
Duncan Sandsdc024672007-11-27 13:23:08 +0000474
475 // Construct the new function type using the new arguments.
Chris Lattnered570a72004-03-07 21:29:54 +0000476 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanfd939082005-04-21 23:48:37 +0000477
Duncan Sandsdc024672007-11-27 13:23:08 +0000478 // Create the new function body and insert it into the module...
Gabor Greif051a9502008-04-06 20:25:17 +0000479 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000480 NF->setCallingConv(F->getCallingConv());
Chris Lattnerab04e132008-01-17 01:17:03 +0000481
482 // Recompute the parameter attributes list based on the new arguments for
483 // the function.
Chris Lattner58d74912008-03-12 17:45:29 +0000484 NF->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end()));
485 ParamAttrsVec.clear();
Chris Lattnerab04e132008-01-17 01:17:03 +0000486
Gordon Henriksen194c90e2007-12-25 22:16:06 +0000487 if (F->hasCollector())
488 NF->setCollector(F->getCollector());
Chris Lattnered570a72004-03-07 21:29:54 +0000489 F->getParent()->getFunctionList().insert(F, NF);
Zhou Sheng2b3407f2008-03-20 08:05:05 +0000490 NF->takeName(F);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000491
492 // Get the alias analysis information that we need to update to reflect our
493 // changes.
494 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
495
Chris Lattnered570a72004-03-07 21:29:54 +0000496 // Loop over all of the callers of the function, transforming the call sites
497 // to pass in the loaded pointers.
498 //
Chris Lattnerab04e132008-01-17 01:17:03 +0000499 SmallVector<Value*, 16> Args;
Chris Lattnered570a72004-03-07 21:29:54 +0000500 while (!F->use_empty()) {
501 CallSite CS = CallSite::get(F->use_back());
502 Instruction *Call = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +0000503 const PAListPtr &CallPAL = CS.getParamAttrs();
Chris Lattnerab04e132008-01-17 01:17:03 +0000504
Duncan Sands532d0222008-02-01 20:37:16 +0000505 // Add any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000506 if (ParameterAttributes attrs = CallPAL.getParamAttrs(0))
Duncan Sands532d0222008-02-01 20:37:16 +0000507 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
508
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000509 // Loop over the operands, inserting GEP and loads in the caller as
510 // appropriate.
Chris Lattnered570a72004-03-07 21:29:54 +0000511 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerab04e132008-01-17 01:17:03 +0000512 ArgIndex = 1;
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000513 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
Chris Lattnerab04e132008-01-17 01:17:03 +0000514 I != E; ++I, ++AI, ++ArgIndex)
Chris Lattner10603e02008-01-11 22:31:41 +0000515 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
Chris Lattnered570a72004-03-07 21:29:54 +0000516 Args.push_back(*AI); // Unmodified argument
Chris Lattnerab04e132008-01-17 01:17:03 +0000517
Chris Lattner58d74912008-03-12 17:45:29 +0000518 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
Chris Lattnerab04e132008-01-17 01:17:03 +0000519 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
520
Chris Lattner10603e02008-01-11 22:31:41 +0000521 } else if (ByValArgsToTransform.count(I)) {
522 // Emit a GEP and load for each element of the struct.
523 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
524 const StructType *STy = cast<StructType>(AgTy);
525 Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
526 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
527 Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
Gabor Greif051a9502008-04-06 20:25:17 +0000528 Value *Idx = GetElementPtrInst::Create(*AI, Idxs, Idxs+2,
529 (*AI)->getName()+"."+utostr(i),
530 Call);
Chris Lattner10603e02008-01-11 22:31:41 +0000531 // TODO: Tell AA about the new values?
532 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
533 }
534 } else if (!I->use_empty()) {
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000535 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000536 ScalarizeTable &ArgIndices = ScalarizedElements[I];
537 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000538 E = ArgIndices.end(); SI != E; ++SI) {
539 Value *V = *AI;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000540 LoadInst *OrigLoad = OriginalLoads[*SI];
541 if (!SI->empty()) {
Gabor Greif051a9502008-04-06 20:25:17 +0000542 V = GetElementPtrInst::Create(V, SI->begin(), SI->end(),
543 V->getName()+".idx", Call);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000544 AA.copyValue(OrigLoad->getOperand(0), V);
545 }
Chris Lattner9440db82004-03-08 01:04:36 +0000546 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000547 AA.copyValue(OrigLoad, Args.back());
Chris Lattner9440db82004-03-08 01:04:36 +0000548 }
Chris Lattnered570a72004-03-07 21:29:54 +0000549 }
550
551 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000552 Args.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattnered570a72004-03-07 21:29:54 +0000553
554 // Push any varargs arguments on the list
Chris Lattnerab04e132008-01-17 01:17:03 +0000555 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
Chris Lattnered570a72004-03-07 21:29:54 +0000556 Args.push_back(*AI);
Chris Lattner58d74912008-03-12 17:45:29 +0000557 if (ParameterAttributes Attrs = CallPAL.getParamAttrs(ArgIndex))
Chris Lattnerab04e132008-01-17 01:17:03 +0000558 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
559 }
Chris Lattnered570a72004-03-07 21:29:54 +0000560
561 Instruction *New;
562 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000563 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
564 Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000565 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000566 cast<InvokeInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
567 ParamAttrsVec.end()));
Chris Lattnered570a72004-03-07 21:29:54 +0000568 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000569 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000570 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000571 cast<CallInst>(New)->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(),
572 ParamAttrsVec.end()));
Chris Lattner1430ef12005-05-06 06:46:58 +0000573 if (cast<CallInst>(Call)->isTailCall())
574 cast<CallInst>(New)->setTailCall();
Chris Lattnered570a72004-03-07 21:29:54 +0000575 }
576 Args.clear();
Chris Lattnerab04e132008-01-17 01:17:03 +0000577 ParamAttrsVec.clear();
Chris Lattnered570a72004-03-07 21:29:54 +0000578
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000579 // Update the alias analysis implementation to know that we are replacing
580 // the old call with a new one.
581 AA.replaceWithNewValue(Call, New);
582
Chris Lattnered570a72004-03-07 21:29:54 +0000583 if (!Call->use_empty()) {
584 Call->replaceAllUsesWith(New);
Chris Lattner046800a2007-02-11 01:08:35 +0000585 New->takeName(Call);
Chris Lattnered570a72004-03-07 21:29:54 +0000586 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000587
Chris Lattnered570a72004-03-07 21:29:54 +0000588 // Finally, remove the old call from the program, reducing the use-count of
589 // F.
Chris Lattner40c14be2008-01-11 19:20:39 +0000590 Call->eraseFromParent();
Chris Lattnered570a72004-03-07 21:29:54 +0000591 }
592
593 // Since we have now created the new function, splice the body of the old
594 // function right into the new function, leaving the old rotting hulk of the
595 // function empty.
596 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
597
598 // Loop over the argument list, transfering uses of the old arguments over to
599 // the new arguments, also transfering over the names as well.
600 //
Chris Lattner93e985f2007-02-13 02:10:56 +0000601 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Chris Lattner10603e02008-01-11 22:31:41 +0000602 I2 = NF->arg_begin(); I != E; ++I) {
603 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
Chris Lattnered570a72004-03-07 21:29:54 +0000604 // If this is an unmodified argument, move the name and users over to the
605 // new version.
606 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000607 I2->takeName(I);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000608 AA.replaceWithNewValue(I, I2);
Chris Lattnered570a72004-03-07 21:29:54 +0000609 ++I2;
Chris Lattner10603e02008-01-11 22:31:41 +0000610 continue;
Chris Lattnered570a72004-03-07 21:29:54 +0000611 }
Chris Lattner10603e02008-01-11 22:31:41 +0000612
613 if (ByValArgsToTransform.count(I)) {
614 // In the callee, we create an alloca, and store each of the new incoming
615 // arguments into the alloca.
616 Instruction *InsertPt = NF->begin()->begin();
617
618 // Just add all the struct element types.
619 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
620 Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
621 const StructType *STy = cast<StructType>(AgTy);
622 Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
623
624 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
625 Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
Gabor Greif051a9502008-04-06 20:25:17 +0000626 Value *Idx = GetElementPtrInst::Create(TheAlloca, Idxs, Idxs+2,
627 TheAlloca->getName()+"."+utostr(i),
628 InsertPt);
Chris Lattner10603e02008-01-11 22:31:41 +0000629 I2->setName(I->getName()+"."+utostr(i));
630 new StoreInst(I2++, Idx, InsertPt);
631 }
632
633 // Anything that used the arg should now use the alloca.
634 I->replaceAllUsesWith(TheAlloca);
635 TheAlloca->takeName(I);
636 AA.replaceWithNewValue(I, TheAlloca);
637 continue;
638 }
639
640 if (I->use_empty()) {
641 AA.deleteValue(I);
642 continue;
643 }
644
645 // Otherwise, if we promoted this argument, then all users are load
646 // instructions, and all loads should be using the new argument that we
647 // added.
648 ScalarizeTable &ArgIndices = ScalarizedElements[I];
649
650 while (!I->use_empty()) {
651 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
652 assert(ArgIndices.begin()->empty() &&
653 "Load element should sort to front!");
654 I2->setName(I->getName()+".val");
655 LI->replaceAllUsesWith(I2);
656 AA.replaceWithNewValue(LI, I2);
657 LI->eraseFromParent();
658 DOUT << "*** Promoted load of argument '" << I->getName()
659 << "' in function '" << F->getName() << "'\n";
660 } else {
661 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
662 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
663
664 Function::arg_iterator TheArg = I2;
665 for (ScalarizeTable::iterator It = ArgIndices.begin();
666 *It != Operands; ++It, ++TheArg) {
667 assert(It != ArgIndices.end() && "GEP not handled??");
668 }
669
670 std::string NewName = I->getName();
671 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
672 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
673 NewName += "." + CI->getValue().toStringUnsigned(10);
674 else
675 NewName += ".x";
676 TheArg->setName(NewName+".val");
677
678 DOUT << "*** Promoted agg argument '" << TheArg->getName()
679 << "' of function '" << F->getName() << "'\n";
680
681 // All of the uses must be load instructions. Replace them all with
682 // the argument specified by ArgNo.
683 while (!GEP->use_empty()) {
684 LoadInst *L = cast<LoadInst>(GEP->use_back());
685 L->replaceAllUsesWith(TheArg);
686 AA.replaceWithNewValue(L, TheArg);
687 L->eraseFromParent();
688 }
689 AA.deleteValue(GEP);
690 GEP->eraseFromParent();
691 }
692 }
693
694 // Increment I2 past all of the arguments added for this promoted pointer.
695 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
696 ++I2;
697 }
Chris Lattnered570a72004-03-07 21:29:54 +0000698
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000699 // Notify the alias analysis implementation that we inserted a new argument.
700 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000701 AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000702
703
704 // Tell the alias analysis that the old function is about to disappear.
705 AA.replaceWithNewValue(F, NF);
706
Chris Lattnered570a72004-03-07 21:29:54 +0000707 // Now that the old function is dead, delete it.
Chris Lattner40c14be2008-01-11 19:20:39 +0000708 F->eraseFromParent();
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000709 return NF;
Chris Lattnered570a72004-03-07 21:29:54 +0000710}