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/LLVMContext.h"
27 #include "llvm/Module.h"
28 #include "llvm/CallGraphSCCPass.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Analysis/CallGraph.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/Compiler.h"
40 STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
41 STATISTIC(NumSRET , "Number of sret promoted");
43 /// SRETPromotion - This pass removes sret parameter and updates
44 /// function to use multiple return value.
46 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 CallGraphSCCPass::getAnalysisUsage(AU);
51 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
52 static char ID; // Pass identification, replacement for typeid
53 SRETPromotion() : CallGraphSCCPass(&ID) {}
56 bool PromoteReturn(CallGraphNode *CGN);
57 bool isSafeToUpdateAllCallers(Function *F);
58 Function *cloneFunctionBody(Function *F, const StructType *STy);
59 void updateCallSites(Function *F, Function *NF);
60 bool nestedStructType(const StructType *STy);
64 char SRETPromotion::ID = 0;
65 static RegisterPass<SRETPromotion>
66 X("sretpromotion", "Promote sret arguments to multiple ret values");
68 Pass *llvm::createStructRetPromotionPass() {
69 return new SRETPromotion();
72 bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
75 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
76 Changed |= PromoteReturn(SCC[i]);
81 /// PromoteReturn - This method promotes function that uses StructRet paramater
82 /// into a function that uses mulitple return value.
83 bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
84 Function *F = CGN->getFunction();
86 if (!F || F->isDeclaration() || !F->hasLocalLinkage())
89 // Make sure that function returns struct.
90 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
93 DOUT << "SretPromotion: Looking at sret function " << F->getNameStart() << "\n";
95 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
96 Function::arg_iterator AI = F->arg_begin();
97 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
98 assert (FArgType && "Invalid sret parameter type");
99 const llvm::StructType *STy =
100 dyn_cast<StructType>(FArgType->getElementType());
101 assert (STy && "Invalid sret parameter element type");
103 // Check if it is ok to perform this promotion.
104 if (isSafeToUpdateAllCallers(F) == false) {
105 DOUT << "SretPromotion: Not all callers can be updated\n";
106 NumRejectedSRETUses++;
110 DOUT << "SretPromotion: sret argument will be promoted\n";
112 // [1] Replace use of sret parameter
113 AllocaInst *TheAlloca = new AllocaInst (*Context, STy, NULL, "mrv",
114 F->getEntryBlock().begin());
115 Value *NFirstArg = F->arg_begin();
116 NFirstArg->replaceAllUsesWith(TheAlloca);
118 // [2] Find and replace ret instructions
119 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
120 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
123 if (isa<ReturnInst>(I)) {
124 Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
125 ReturnInst *NR = ReturnInst::Create(NV, I);
126 I->replaceAllUsesWith(NR);
127 I->eraseFromParent();
131 // [3] Create the new function body and insert it into the module.
132 Function *NF = cloneFunctionBody(F, STy);
134 // [4] Update all call sites to use new function
135 updateCallSites(F, NF);
137 F->eraseFromParent();
138 getAnalysis<CallGraph>().changeFunction(F, NF);
142 // Check if it is ok to perform this promotion.
143 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
146 // No users. OK to modify signature.
149 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
150 FnUseI != FnUseE; ++FnUseI) {
151 // The function is passed in as an argument to (possibly) another function,
152 // we can't change it!
153 CallSite CS = CallSite::get(*FnUseI);
154 Instruction *Call = CS.getInstruction();
155 // The function is used by something else than a call or invoke instruction,
156 // we can't change it!
157 if (!Call || !CS.isCallee(FnUseI))
159 CallSite::arg_iterator AI = CS.arg_begin();
160 Value *FirstArg = *AI;
162 if (!isa<AllocaInst>(FirstArg))
165 // Check FirstArg's users.
166 for (Value::use_iterator ArgI = FirstArg->use_begin(),
167 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
169 // If FirstArg user is a CallInst that does not correspond to current
170 // call site then this function F is not suitable for sret promotion.
171 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
175 // If FirstArg user is a GEP whose all users are not LoadInst then
176 // this function F is not suitable for sret promotion.
177 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
178 // TODO : Use dom info and insert PHINodes to collect get results
179 // from multiple call sites for this GEP.
180 if (GEP->getParent() != Call->getParent())
182 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
183 GEPI != GEPE; ++GEPI)
184 if (!isa<LoadInst>(GEPI))
187 // Any other FirstArg users make this function unsuitable for sret
197 /// cloneFunctionBody - Create a new function based on F and
198 /// insert it into module. Remove first argument. Use STy as
199 /// the return type for new function.
200 Function *SRETPromotion::cloneFunctionBody(Function *F,
201 const StructType *STy) {
203 const FunctionType *FTy = F->getFunctionType();
204 std::vector<const Type*> Params;
206 // Attributes - Keep track of the parameter attributes for the arguments.
207 SmallVector<AttributeWithIndex, 8> AttributesVec;
208 const AttrListPtr &PAL = F->getAttributes();
210 // Add any return attributes.
211 if (Attributes attrs = PAL.getRetAttributes())
212 AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
214 // Skip first argument.
215 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
217 // 0th parameter attribute is reserved for return type.
218 // 1th parameter attribute is for first 1st sret argument.
219 unsigned ParamIndex = 2;
221 Params.push_back(I->getType());
222 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
223 AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
228 // Add any fn attributes.
229 if (Attributes attrs = PAL.getFnAttributes())
230 AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
233 FunctionType *NFTy = Context->getFunctionType(STy, Params, FTy->isVarArg());
234 Function *NF = Function::Create(NFTy, F->getLinkage());
236 NF->copyAttributesFrom(F);
237 NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));
238 F->getParent()->getFunctionList().insert(F, NF);
239 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
244 Function::arg_iterator NI = NF->arg_begin();
247 I->replaceAllUsesWith(NI);
256 /// updateCallSites - Update all sites that call F to use NF.
257 void SRETPromotion::updateCallSites(Function *F, Function *NF) {
258 CallGraph &CG = getAnalysis<CallGraph>();
259 SmallVector<Value*, 16> Args;
261 // Attributes - Keep track of the parameter attributes for the arguments.
262 SmallVector<AttributeWithIndex, 8> ArgAttrsVec;
264 while (!F->use_empty()) {
265 CallSite CS = CallSite::get(*F->use_begin());
266 Instruction *Call = CS.getInstruction();
268 const AttrListPtr &PAL = F->getAttributes();
269 // Add any return attributes.
270 if (Attributes attrs = PAL.getRetAttributes())
271 ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));
273 // Copy arguments, however skip first one.
274 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
275 Value *FirstCArg = *AI;
277 // 0th parameter attribute is reserved for return type.
278 // 1th parameter attribute is for first 1st sret argument.
279 unsigned ParamIndex = 2;
282 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
283 ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
288 // Add any function attributes.
289 if (Attributes attrs = PAL.getFnAttributes())
290 ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));
292 AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
294 // Build new call instruction.
296 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
297 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
298 Args.begin(), Args.end(), "", Call);
299 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
300 cast<InvokeInst>(New)->setAttributes(NewPAL);
302 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
303 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
304 cast<CallInst>(New)->setAttributes(NewPAL);
305 if (cast<CallInst>(Call)->isTailCall())
306 cast<CallInst>(New)->setTailCall();
312 // Update the callgraph to know that the callsite has been transformed.
313 CG[Call->getParent()->getParent()]->replaceCallSite(Call, New);
315 // Update all users of sret parameter to extract value using extractvalue.
316 for (Value::use_iterator UI = FirstCArg->use_begin(),
317 UE = FirstCArg->use_end(); UI != UE; ) {
319 CallInst *C2 = dyn_cast<CallInst>(U2);
320 if (C2 && (C2 == Call))
322 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
323 ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2));
324 assert (Idx && "Unexpected getelementptr index!");
325 Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
327 while(!UGEP->use_empty()) {
328 // isSafeToUpdateAllCallers has checked that all GEP uses are
330 LoadInst *L = cast<LoadInst>(*UGEP->use_begin());
331 L->replaceAllUsesWith(GR);
332 L->eraseFromParent();
334 UGEP->eraseFromParent();
336 else assert( 0 && "Unexpected sret parameter use");
338 Call->eraseFromParent();
342 /// nestedStructType - Return true if STy includes any
343 /// other aggregate types
344 bool SRETPromotion::nestedStructType(const StructType *STy) {
345 unsigned Num = STy->getNumElements();
346 for (unsigned i = 0; i < Num; i++) {
347 const Type *Ty = STy->getElementType(i);
348 if (!Ty->isSingleValueType() && Ty != Type::VoidTy)