1 //===-- StructRetPromotion.cpp - Promote sret arguments -000000------------===//
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 // TODO : Describe this pass.
11 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "sretpromotion"
14 #include "llvm/Transforms/IPO.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ParamAttrsList.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Compiler.h"
31 STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
32 STATISTIC(NumSRET , "Number of sret promoted");
34 /// SRETPromotion - This pass removes sret parameter and updates
35 /// function to use multiple return value.
37 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
38 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39 CallGraphSCCPass::getAnalysisUsage(AU);
42 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
43 static char ID; // Pass identification, replacement for typeid
44 SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
47 bool PromoteReturn(CallGraphNode *CGN);
48 bool isSafeToUpdateAllCallers(Function *F);
49 Function *cloneFunctionBody(Function *F, const StructType *STy);
50 void updateCallSites(Function *F, Function *NF);
53 char SRETPromotion::ID = 0;
54 RegisterPass<SRETPromotion> X("sretpromotion",
55 "Promote sret arguments to multiple ret values");
58 Pass *llvm::createStructRetPromotionPass() {
59 return new SRETPromotion();
62 bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
65 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
66 Changed |= PromoteReturn(SCC[i]);
71 /// PromoteReturn - This method promotes function that uses StructRet paramater
72 /// into a function that uses mulitple return value.
73 bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
74 Function *F = CGN->getFunction();
76 // Make sure that it is local to this module.
77 if (!F || !F->hasInternalLinkage())
80 // Make sure that function returns struct.
81 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
84 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
85 Function::arg_iterator AI = F->arg_begin();
86 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
87 assert (FArgType && "Invalid sret paramater type");
88 const llvm::StructType *STy =
89 dyn_cast<StructType>(FArgType->getElementType());
90 assert (STy && "Invalid sret parameter element type");
92 // Check if it is ok to perform this promotion.
93 if (isSafeToUpdateAllCallers(F) == false) {
94 NumRejectedSRETUses++;
98 // [1] Replace use of sret parameter
99 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
100 F->getEntryBlock().begin());
101 Value *NFirstArg = F->arg_begin();
102 NFirstArg->replaceAllUsesWith(TheAlloca);
104 // [2] Find and replace ret instructions
105 SmallVector<Value *,4> RetVals;
106 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
107 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
110 if (isa<ReturnInst>(I)) {
112 for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
113 SmallVector<Value*, 2> GEPIdx;
114 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
115 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
116 Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(),
118 Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
119 RetVals.push_back(NV);
122 ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I);
123 I->replaceAllUsesWith(NR);
124 I->eraseFromParent();
128 // [3] Create the new function body and insert it into the module.
129 Function *NF = cloneFunctionBody(F, STy);
131 // [4] Update all call sites to use new function
132 updateCallSites(F, NF);
134 F->eraseFromParent();
135 getAnalysis<CallGraph>().changeFunction(F, NF);
139 // Check if it is ok to perform this promotion.
140 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
143 // No users. OK to modify signature.
146 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
147 FnUseI != FnUseE; ++FnUseI) {
149 CallSite CS = CallSite::get(*FnUseI);
150 Instruction *Call = CS.getInstruction();
151 CallSite::arg_iterator AI = CS.arg_begin();
152 Value *FirstArg = *AI;
154 if (!isa<AllocaInst>(FirstArg))
157 // Check FirstArg's users.
158 for (Value::use_iterator ArgI = FirstArg->use_begin(),
159 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
161 // If FirstArg user is a CallInst that does not correspond to current
162 // call site then this function F is not suitable for sret promotion.
163 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
167 // If FirstArg user is a GEP whose all users are not LoadInst then
168 // this function F is not suitable for sret promotion.
169 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
170 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
171 GEPI != GEPE; ++GEPI)
172 if (!isa<LoadInst>(GEPI))
175 // Any other FirstArg users make this function unsuitable for sret
185 /// cloneFunctionBody - Create a new function based on F and
186 /// insert it into module. Remove first argument. Use STy as
187 /// the return type for new function.
188 Function *SRETPromotion::cloneFunctionBody(Function *F,
189 const StructType *STy) {
191 const FunctionType *FTy = F->getFunctionType();
192 std::vector<const Type*> Params;
194 // ParamAttrs - Keep track of the parameter attributes for the arguments.
195 ParamAttrsVector ParamAttrsVec;
196 const ParamAttrsList *PAL = F->getParamAttrs();
198 // Add any return attributes.
199 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
200 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
202 // Skip first argument.
203 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
205 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
207 Params.push_back(I->getType());
208 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
210 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
215 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
216 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
217 NF->setCallingConv(F->getCallingConv());
218 NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
219 F->getParent()->getFunctionList().insert(F, NF);
220 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
225 Function::arg_iterator NI = NF->arg_begin();
228 I->replaceAllUsesWith(NI);
237 /// updateCallSites - Update all sites that call F to use NF.
238 void SRETPromotion::updateCallSites(Function *F, Function *NF) {
240 SmallVector<Value*, 16> Args;
242 // ParamAttrs - Keep track of the parameter attributes for the arguments.
243 ParamAttrsVector ParamAttrsVec;
245 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) {
246 CallSite CS = CallSite::get(*FUI);
248 Instruction *Call = CS.getInstruction();
250 const ParamAttrsList *PAL = F->getParamAttrs();
251 // Add any return attributes.
252 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
253 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
255 // Copy arguments, however skip first one.
256 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
257 Value *FirstCArg = *AI;
259 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
262 if (ParameterAttributes Attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
264 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
269 // Build new call instruction.
271 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
272 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
273 Args.begin(), Args.end(), "", Call);
274 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
275 cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
277 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
278 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
279 cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
280 if (cast<CallInst>(Call)->isTailCall())
281 cast<CallInst>(New)->setTailCall();
284 ParamAttrsVec.clear();
287 // Update all users of sret parameter to extract value using getresult.
288 for (Value::use_iterator UI = FirstCArg->use_begin(),
289 UE = FirstCArg->use_end(); UI != UE; ) {
291 CallInst *C2 = dyn_cast<CallInst>(U2);
292 if (C2 && (C2 == Call))
294 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
295 Value *GR = new GetResultInst(New, 5, "xxx", UGEP);
296 for (Value::use_iterator GI = UGEP->use_begin(),
297 GE = UGEP->use_end(); GI != GE; ++GI) {
298 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
299 L->replaceAllUsesWith(GR);
300 L->eraseFromParent();
303 UGEP->eraseFromParent();
305 else assert( 0 && "Unexpected sret parameter use");
307 Call->eraseFromParent();