cleanup as per Duncan's review
[oota-llvm.git] / lib / Transforms / IPO / StructRetPromotion.cpp
index 77a35b428759220352771115bf12b176cea6056c..2f44d80ae489395c1dc970f26ae6f3387f0ad36c 100644 (file)
@@ -1,4 +1,4 @@
-//===-- StructRetPromotion.cpp - Promote sret arguments -000000------------===//
+//===-- StructRetPromotion.cpp - Promote sret arguments ------------------===//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -7,7 +7,16 @@
 //
 //===----------------------------------------------------------------------===//
 //
-// TODO : Describe this pass.
+// This pass finds functions that return a struct (using a pointer to the struct
+// as the first argument of the function, marked with the 'sret' attribute) and
+// replaces them with a new function that simply returns each of the elements of
+// that struct (using multiple return values).
+//
+// This pass works under a number of conditions:
+//  1. The returned struct must not contain other structs
+//  2. The returned struct must only be used to load values from
+//  3. The placeholder struct passed in is the result of an alloca
+//
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "sretpromotion"
@@ -49,12 +58,12 @@ namespace {
     void updateCallSites(Function *F, Function *NF);
     bool nestedStructType(const StructType *STy);
   };
-
-  char SRETPromotion::ID = 0;
-  RegisterPass<SRETPromotion> X("sretpromotion",
-                               "Promote sret arguments to multiple ret values");
 }
 
+char SRETPromotion::ID = 0;
+static RegisterPass<SRETPromotion>
+X("sretpromotion", "Promote sret arguments to multiple ret values");
+
 Pass *llvm::createStructRetPromotionPass() {
   return new SRETPromotion();
 }
@@ -80,23 +89,24 @@ bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
   if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
     return false;
 
+  DOUT << "SretPromotion: Looking at sret function " << F->getNameStart() << "\n";
+
   assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
   Function::arg_iterator AI = F->arg_begin();
   const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
-  assert (FArgType && "Invalid sret paramater type");
+  assert (FArgType && "Invalid sret parameter type");
   const llvm::StructType *STy = 
     dyn_cast<StructType>(FArgType->getElementType());
   assert (STy && "Invalid sret parameter element type");
 
-  if (nestedStructType(STy))
-    return false;
-
   // Check if it is ok to perform this promotion.
   if (isSafeToUpdateAllCallers(F) == false) {
+    DOUT << "SretPromotion: Not all callers can be updated\n";
     NumRejectedSRETUses++;
     return false;
   }
 
+  DOUT << "SretPromotion: sret argument will be promoted\n";
   NumSRET++;
   // [1] Replace use of sret parameter 
   AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv", 
@@ -105,25 +115,13 @@ bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
   NFirstArg->replaceAllUsesWith(TheAlloca);
 
   // [2] Find and replace ret instructions
-  SmallVector<Value *,4> RetVals;
   for (Function::iterator FI = F->begin(), FE = F->end();  FI != FE; ++FI) 
     for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
       Instruction *I = BI;
       ++BI;
       if (isa<ReturnInst>(I)) {
-        RetVals.clear();
-        for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
-          SmallVector<Value*, 2> GEPIdx;
-          GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
-          GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
-          Value *NGEPI = GetElementPtrInst::Create(TheAlloca, GEPIdx.begin(),
-                                                   GEPIdx.end(),
-                                                   "mrv.gep", I);
-          Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
-          RetVals.push_back(NV);
-        }
-    
-        ReturnInst *NR = ReturnInst::Create(&RetVals[0], RetVals.size(), I);
+        Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
+        ReturnInst *NR = ReturnInst::Create(NV, I);
         I->replaceAllUsesWith(NR);
         I->eraseFromParent();
       }
@@ -140,7 +138,7 @@ bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
   return true;
 }
 
-  // Check if it is ok to perform this promotion.
+// Check if it is ok to perform this promotion.
 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
 
   if (F->use_empty())
@@ -149,9 +147,17 @@ bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
 
   for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
        FnUseI != FnUseE; ++FnUseI) {
+    // The function is passed in as an argument to (possibly) another function,
+    // we can't change it!
+    if (FnUseI.getOperandNo() != 0)
+      return false;
 
     CallSite CS = CallSite::get(*FnUseI);
     Instruction *Call = CS.getInstruction();
+    // The function is used by something else than a call or invoke instruction,
+    // we can't change it!
+    if (!Call)
+      return false;
     CallSite::arg_iterator AI = CS.arg_begin();
     Value *FirstArg = *AI;
 
@@ -222,8 +228,9 @@ Function *SRETPromotion::cloneFunctionBody(Function *F,
   }
 
   FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
-  Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
-  NF->setCallingConv(F->getCallingConv());
+  Function *NF = Function::Create(NFTy, F->getLinkage());
+  NF->takeName(F);
+  NF->copyAttributesFrom(F);
   NF->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end()));
   F->getParent()->getFunctionList().insert(F, NF);
   NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
@@ -251,10 +258,8 @@ void SRETPromotion::updateCallSites(Function *F, Function *NF) {
   // ParamAttrs - Keep track of the parameter attributes for the arguments.
   SmallVector<ParamAttrsWithIndex, 8> ArgAttrsVec;
 
-  for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end();
-       FUI != FUE;) {
-    CallSite CS = CallSite::get(*FUI);
-    ++FUI;
+  while (!F->use_empty()) {
+    CallSite CS = CallSite::get(*F->use_begin());
     Instruction *Call = CS.getInstruction();
 
     const PAListPtr &PAL = F->getParamAttrs();
@@ -298,7 +303,7 @@ void SRETPromotion::updateCallSites(Function *F, Function *NF) {
     ArgAttrsVec.clear();
     New->takeName(Call);
 
-    // Update all users of sret parameter to extract value using getresult.
+    // Update all users of sret parameter to extract value using extractvalue.
     for (Value::use_iterator UI = FirstCArg->use_begin(), 
            UE = FirstCArg->use_end(); UI != UE; ) {
       User *U2 = *UI++;
@@ -308,13 +313,14 @@ void SRETPromotion::updateCallSites(Function *F, Function *NF) {
       else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
         ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2));
         assert (Idx && "Unexpected getelementptr index!");
-        Value *GR = new GetResultInst(New, Idx->getZExtValue(), "gr", UGEP);
-        for (Value::use_iterator GI = UGEP->use_begin(),
-               GE = UGEP->use_end(); GI != GE; ++GI) {
-          if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
-            L->replaceAllUsesWith(GR);
-            L->eraseFromParent();
-          }
+        Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
+                                             "evi", UGEP);
+        while(!UGEP->use_empty()) {
+          // isSafeToUpdateAllCallers has checked that all GEP uses are
+          // LoadInsts
+          LoadInst *L = cast<LoadInst>(*UGEP->use_begin());
+          L->replaceAllUsesWith(GR);
+          L->eraseFromParent();
         }
         UGEP->eraseFromParent();
       }
@@ -330,7 +336,7 @@ bool SRETPromotion::nestedStructType(const StructType *STy) {
   unsigned Num = STy->getNumElements();
   for (unsigned i = 0; i < Num; i++) {
     const Type *Ty = STy->getElementType(i);
-    if (!Ty->isFirstClassType() && Ty != Type::VoidTy)
+    if (!Ty->isSingleValueType() && Ty != Type::VoidTy)
       return true;
   }
   return false;