1 //===-- StructRetPromotion.cpp - Promote sret arguments ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass finds functions that return a struct (using a pointer to the struct
11 // as the first argument of the function, marked with the 'sret' attribute) and
12 // replaces them with a new function that simply returns each of the elements of
13 // that struct (using multiple return values).
15 // This pass works under a number of conditions:
16 // 1. The returned struct must not contain other structs
17 // 2. The returned struct must only be used to load values from
18 // 3. The placeholder struct passed in is the result of an alloca
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "sretpromotion"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/CallGraphSCCPass.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Support/Compiler.h"
39 STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
40 STATISTIC(NumSRET , "Number of sret promoted");
42 /// SRETPromotion - This pass removes sret parameter and updates
43 /// function to use multiple return value.
45 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 CallGraphSCCPass::getAnalysisUsage(AU);
50 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
51 static char ID; // Pass identification, replacement for typeid
52 SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
55 bool PromoteReturn(CallGraphNode *CGN);
56 bool isSafeToUpdateAllCallers(Function *F);
57 Function *cloneFunctionBody(Function *F, const StructType *STy);
58 void updateCallSites(Function *F, Function *NF);
59 bool nestedStructType(const StructType *STy);
63 char SRETPromotion::ID = 0;
64 static RegisterPass<SRETPromotion>
65 X("sretpromotion", "Promote sret arguments to multiple ret values");
67 Pass *llvm::createStructRetPromotionPass() {
68 return new SRETPromotion();
71 bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
74 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
75 Changed |= PromoteReturn(SCC[i]);
80 /// PromoteReturn - This method promotes function that uses StructRet paramater
81 /// into a function that uses mulitple return value.
82 bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
83 Function *F = CGN->getFunction();
85 if (!F || F->isDeclaration() || !F->hasInternalLinkage())
88 // Make sure that function returns struct.
89 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
92 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
93 Function::arg_iterator AI = F->arg_begin();
94 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
95 assert (FArgType && "Invalid sret parameter type");
96 const llvm::StructType *STy =
97 dyn_cast<StructType>(FArgType->getElementType());
98 assert (STy && "Invalid sret parameter element type");
100 // Check if it is ok to perform this promotion.
101 if (isSafeToUpdateAllCallers(F) == false) {
102 NumRejectedSRETUses++;
107 // [1] Replace use of sret parameter
108 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
109 F->getEntryBlock().begin());
110 Value *NFirstArg = F->arg_begin();
111 NFirstArg->replaceAllUsesWith(TheAlloca);
113 // [2] Find and replace ret instructions
114 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
115 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
118 if (isa<ReturnInst>(I)) {
119 Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
120 ReturnInst *NR = ReturnInst::Create(NV);
121 I->replaceAllUsesWith(NR);
122 I->eraseFromParent();
126 // [3] Create the new function body and insert it into the module.
127 Function *NF = cloneFunctionBody(F, STy);
129 // [4] Update all call sites to use new function
130 updateCallSites(F, NF);
132 F->eraseFromParent();
133 getAnalysis<CallGraph>().changeFunction(F, NF);
137 // Check if it is ok to perform this promotion.
138 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
141 // No users. OK to modify signature.
144 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
145 FnUseI != FnUseE; ++FnUseI) {
146 // The function is passed in as an argument to (possibly) another function,
147 // we can't change it!
148 if (FnUseI.getOperandNo() != 0)
151 CallSite CS = CallSite::get(*FnUseI);
152 Instruction *Call = CS.getInstruction();
153 // The function is used by something else than a call or invoke instruction,
154 // we can't change it!
157 CallSite::arg_iterator AI = CS.arg_begin();
158 Value *FirstArg = *AI;
160 if (!isa<AllocaInst>(FirstArg))
163 // Check FirstArg's users.
164 for (Value::use_iterator ArgI = FirstArg->use_begin(),
165 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
167 // If FirstArg user is a CallInst that does not correspond to current
168 // call site then this function F is not suitable for sret promotion.
169 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
173 // If FirstArg user is a GEP whose all users are not LoadInst then
174 // this function F is not suitable for sret promotion.
175 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
176 // TODO : Use dom info and insert PHINodes to collect get results
177 // from multiple call sites for this GEP.
178 if (GEP->getParent() != Call->getParent())
180 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
181 GEPI != GEPE; ++GEPI)
182 if (!isa<LoadInst>(GEPI))
185 // Any other FirstArg users make this function unsuitable for sret
195 /// cloneFunctionBody - Create a new function based on F and
196 /// insert it into module. Remove first argument. Use STy as
197 /// the return type for new function.
198 Function *SRETPromotion::cloneFunctionBody(Function *F,
199 const StructType *STy) {
201 const FunctionType *FTy = F->getFunctionType();
202 std::vector<const Type*> Params;
204 // ParamAttrs - Keep track of the parameter attributes for the arguments.
205 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
206 const PAListPtr &PAL = F->getParamAttrs();
208 // Add any return attributes.
209 if (ParameterAttributes attrs = PAL.getParamAttrs(0))
210 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
212 // Skip first argument.
213 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
215 // 0th parameter attribute is reserved for return type.
216 // 1th parameter attribute is for first 1st sret argument.
217 unsigned ParamIndex = 2;
219 Params.push_back(I->getType());
220 if (ParameterAttributes Attrs = PAL.getParamAttrs(ParamIndex))
221 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(ParamIndex - 1, Attrs));
226 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
227 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
228 NF->copyAttributesFrom(F);
229 NF->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end()));
230 F->getParent()->getFunctionList().insert(F, NF);
231 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
236 Function::arg_iterator NI = NF->arg_begin();
239 I->replaceAllUsesWith(NI);
248 /// updateCallSites - Update all sites that call F to use NF.
249 void SRETPromotion::updateCallSites(Function *F, Function *NF) {
251 SmallVector<Value*, 16> Args;
253 // ParamAttrs - Keep track of the parameter attributes for the arguments.
254 SmallVector<ParamAttrsWithIndex, 8> ArgAttrsVec;
256 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end();
258 CallSite CS = CallSite::get(*FUI);
260 Instruction *Call = CS.getInstruction();
262 const PAListPtr &PAL = F->getParamAttrs();
263 // Add any return attributes.
264 if (ParameterAttributes attrs = PAL.getParamAttrs(0))
265 ArgAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
267 // Copy arguments, however skip first one.
268 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
269 Value *FirstCArg = *AI;
271 // 0th parameter attribute is reserved for return type.
272 // 1th parameter attribute is for first 1st sret argument.
273 unsigned ParamIndex = 2;
276 if (ParameterAttributes Attrs = PAL.getParamAttrs(ParamIndex))
277 ArgAttrsVec.push_back(ParamAttrsWithIndex::get(ParamIndex - 1, Attrs));
283 PAListPtr NewPAL = PAListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
285 // Build new call instruction.
287 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
288 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
289 Args.begin(), Args.end(), "", Call);
290 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
291 cast<InvokeInst>(New)->setParamAttrs(NewPAL);
293 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
294 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
295 cast<CallInst>(New)->setParamAttrs(NewPAL);
296 if (cast<CallInst>(Call)->isTailCall())
297 cast<CallInst>(New)->setTailCall();
303 // Update all users of sret parameter to extract value using extractvalue.
304 for (Value::use_iterator UI = FirstCArg->use_begin(),
305 UE = FirstCArg->use_end(); UI != UE; ) {
307 CallInst *C2 = dyn_cast<CallInst>(U2);
308 if (C2 && (C2 == Call))
310 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
311 ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2));
312 assert (Idx && "Unexpected getelementptr index!");
313 Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
315 for (Value::use_iterator GI = UGEP->use_begin(),
316 GE = UGEP->use_end(); GI != GE; ++GI) {
317 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
318 L->replaceAllUsesWith(GR);
319 L->eraseFromParent();
322 UGEP->eraseFromParent();
324 else assert( 0 && "Unexpected sret parameter use");
326 Call->eraseFromParent();
330 /// nestedStructType - Return true if STy includes any
331 /// other aggregate types
332 bool SRETPromotion::nestedStructType(const StructType *STy) {
333 unsigned Num = STy->getNumElements();
334 for (unsigned i = 0; i < Num; i++) {
335 const Type *Ty = STy->getElementType(i);
336 if (!Ty->isSingleValueType() && Ty != Type::VoidTy)