LLVM API Documentation

InlineFunction.cpp

Go to the documentation of this file.
00001 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements inlining of a function into a call site, resolving
00011 // parameters and the return value as appropriate.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/Cloning.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Module.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Intrinsics.h"
00021 #include "llvm/Analysis/CallGraph.h"
00022 #include "llvm/Support/CallSite.h"
00023 using namespace llvm;
00024 
00025 bool llvm::InlineFunction(CallInst *CI, CallGraph *CG) {
00026   return InlineFunction(CallSite(CI), CG);
00027 }
00028 bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG) {
00029   return InlineFunction(CallSite(II), CG);
00030 }
00031 
00032 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
00033 /// in the body of the inlined function into invokes and turn unwind
00034 /// instructions into branches to the invoke unwind dest.
00035 ///
00036 /// II is the invoke instruction begin inlined.  FirstNewBlock is the first
00037 /// block of the inlined code (the last block is the end of the function),
00038 /// and InlineCodeInfo is information about the code that got inlined.
00039 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
00040                                 ClonedCodeInfo &InlinedCodeInfo) {
00041   BasicBlock *InvokeDest = II->getUnwindDest();
00042   std::vector<Value*> InvokeDestPHIValues;
00043 
00044   // If there are PHI nodes in the unwind destination block, we need to
00045   // keep track of which values came into them from this invoke, then remove
00046   // the entry for this block.
00047   BasicBlock *InvokeBlock = II->getParent();
00048   for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
00049     PHINode *PN = cast<PHINode>(I);
00050     // Save the value to use for this edge.
00051     InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
00052   }
00053 
00054   Function *Caller = FirstNewBlock->getParent();
00055   
00056   // The inlined code is currently at the end of the function, scan from the
00057   // start of the inlined code to its end, checking for stuff we need to
00058   // rewrite.
00059   if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
00060     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00061          BB != E; ++BB) {
00062       if (InlinedCodeInfo.ContainsCalls) {
00063         for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
00064           Instruction *I = BBI++;
00065           
00066           // We only need to check for function calls: inlined invoke
00067           // instructions require no special handling.
00068           if (!isa<CallInst>(I)) continue;
00069           CallInst *CI = cast<CallInst>(I);
00070 
00071           // If this is an intrinsic function call, don't convert it to an
00072           // invoke.
00073           if (CI->getCalledFunction() &&
00074               CI->getCalledFunction()->getIntrinsicID())
00075             continue;
00076           
00077           // Convert this function call into an invoke instruction.
00078           // First, split the basic block.
00079           BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
00080           
00081           // Next, create the new invoke instruction, inserting it at the end
00082           // of the old basic block.
00083           InvokeInst *II =
00084             new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
00085                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
00086                            CI->getName(), BB->getTerminator());
00087           II->setCallingConv(CI->getCallingConv());
00088           
00089           // Make sure that anything using the call now uses the invoke!
00090           CI->replaceAllUsesWith(II);
00091           
00092           // Delete the unconditional branch inserted by splitBasicBlock
00093           BB->getInstList().pop_back();
00094           Split->getInstList().pop_front();  // Delete the original call
00095           
00096           // Update any PHI nodes in the exceptional block to indicate that
00097           // there is now a new entry in them.
00098           unsigned i = 0;
00099           for (BasicBlock::iterator I = InvokeDest->begin();
00100                isa<PHINode>(I); ++I, ++i) {
00101             PHINode *PN = cast<PHINode>(I);
00102             PN->addIncoming(InvokeDestPHIValues[i], BB);
00103           }
00104             
00105           // This basic block is now complete, start scanning the next one.
00106           break;
00107         }
00108       }
00109       
00110       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00111         // An UnwindInst requires special handling when it gets inlined into an
00112         // invoke site.  Once this happens, we know that the unwind would cause
00113         // a control transfer to the invoke exception destination, so we can
00114         // transform it into a direct branch to the exception destination.
00115         new BranchInst(InvokeDest, UI);
00116         
00117         // Delete the unwind instruction!
00118         UI->getParent()->getInstList().pop_back();
00119         
00120         // Update any PHI nodes in the exceptional block to indicate that
00121         // there is now a new entry in them.
00122         unsigned i = 0;
00123         for (BasicBlock::iterator I = InvokeDest->begin();
00124              isa<PHINode>(I); ++I, ++i) {
00125           PHINode *PN = cast<PHINode>(I);
00126           PN->addIncoming(InvokeDestPHIValues[i], BB);
00127         }
00128       }
00129     }
00130   }
00131 
00132   // Now that everything is happy, we have one final detail.  The PHI nodes in
00133   // the exception destination block still have entries due to the original
00134   // invoke instruction.  Eliminate these entries (which might even delete the
00135   // PHI node) now.
00136   InvokeDest->removePredecessor(II->getParent());
00137 }
00138 
00139 /// UpdateCallGraphAfterInlining - Once we have finished inlining a call from
00140 /// caller to callee, update the specified callgraph to reflect the changes we
00141 /// made.
00142 static void UpdateCallGraphAfterInlining(const Function *Caller, 
00143                                          const Function *Callee,
00144                                          CallGraph &CG) {
00145   // Update the call graph by deleting the edge from Callee to Caller
00146   CallGraphNode *CalleeNode = CG[Callee];
00147   CallGraphNode *CallerNode = CG[Caller];
00148   CallerNode->removeCallEdgeTo(CalleeNode);
00149   
00150   // Since we inlined all uninlined call sites in the callee into the caller,
00151   // add edges from the caller to all of the callees of the callee.
00152   for (CallGraphNode::iterator I = CalleeNode->begin(),
00153        E = CalleeNode->end(); I != E; ++I)
00154     CallerNode->addCalledFunction(*I);
00155 }
00156 
00157 
00158 // InlineFunction - This function inlines the called function into the basic
00159 // block of the caller.  This returns false if it is not possible to inline this
00160 // call.  The program is still in a well defined state if this occurs though.
00161 //
00162 // Note that this only does one level of inlining.  For example, if the
00163 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
00164 // exists in the instruction stream.  Similiarly this will inline a recursive
00165 // function by one level.
00166 //
00167 bool llvm::InlineFunction(CallSite CS, CallGraph *CG) {
00168   Instruction *TheCall = CS.getInstruction();
00169   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
00170          "Instruction not in function!");
00171 
00172   const Function *CalledFunc = CS.getCalledFunction();
00173   if (CalledFunc == 0 ||          // Can't inline external function or indirect
00174       CalledFunc->isExternal() || // call, or call to a vararg function!
00175       CalledFunc->getFunctionType()->isVarArg()) return false;
00176 
00177 
00178   // If the call to the callee is a non-tail call, we must clear the 'tail'
00179   // flags on any calls that we inline.
00180   bool MustClearTailCallFlags =
00181     isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
00182 
00183   BasicBlock *OrigBB = TheCall->getParent();
00184   Function *Caller = OrigBB->getParent();
00185 
00186   // Get an iterator to the last basic block in the function, which will have
00187   // the new function inlined after it.
00188   //
00189   Function::iterator LastBlock = &Caller->back();
00190 
00191   // Make sure to capture all of the return instructions from the cloned
00192   // function.
00193   std::vector<ReturnInst*> Returns;
00194   ClonedCodeInfo InlinedFunctionInfo;
00195   { // Scope to destroy ValueMap after cloning.
00196     // Calculate the vector of arguments to pass into the function cloner...
00197     std::map<const Value*, Value*> ValueMap;
00198     assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
00199            std::distance(CS.arg_begin(), CS.arg_end()) &&
00200            "No varargs calls can be inlined!");
00201 
00202     CallSite::arg_iterator AI = CS.arg_begin();
00203     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00204            E = CalledFunc->arg_end(); I != E; ++I, ++AI)
00205       ValueMap[I] = *AI;
00206 
00207     // Clone the entire body of the callee into the caller.
00208     CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
00209                       &InlinedFunctionInfo);
00210   }
00211 
00212   // Remember the first block that is newly cloned over.
00213   Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
00214 
00215   // If there are any alloca instructions in the block that used to be the entry
00216   // block for the callee, move them to the entry block of the caller.  First
00217   // calculate which instruction they should be inserted before.  We insert the
00218   // instructions at the end of the current alloca list.
00219   //
00220   {
00221     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
00222     for (BasicBlock::iterator I = FirstNewBlock->begin(),
00223            E = FirstNewBlock->end(); I != E; )
00224       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
00225         if (isa<Constant>(AI->getArraySize())) {
00226           // Scan for the block of allocas that we can move over, and move them
00227           // all at once.
00228           while (isa<AllocaInst>(I) &&
00229                  isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
00230             ++I;
00231 
00232           // Transfer all of the allocas over in a block.  Using splice means
00233           // that they instructions aren't removed from the symbol table, then
00234           // reinserted.
00235           Caller->front().getInstList().splice(InsertPoint,
00236                                                FirstNewBlock->getInstList(),
00237                                                AI, I);
00238         }
00239   }
00240 
00241   // If the inlined code contained dynamic alloca instructions, wrap the inlined
00242   // code with llvm.stacksave/llvm.stackrestore intrinsics.
00243   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
00244     Module *M = Caller->getParent();
00245     const Type *SBytePtr = PointerType::get(Type::SByteTy);
00246     // Get the two intrinsics we care about.
00247     Function *StackSave, *StackRestore;
00248     StackSave    = M->getOrInsertFunction("llvm.stacksave", SBytePtr, NULL);
00249     StackRestore = M->getOrInsertFunction("llvm.stackrestore", Type::VoidTy,
00250                                           SBytePtr, NULL);
00251     
00252     // Insert the llvm.stacksave.
00253     Value *SavedPtr = new CallInst(StackSave, "savedstack", 
00254                                    FirstNewBlock->begin());
00255     
00256     // Insert a call to llvm.stackrestore before any return instructions in the
00257     // inlined function.
00258     for (unsigned i = 0, e = Returns.size(); i != e; ++i)
00259       new CallInst(StackRestore, SavedPtr, "", Returns[i]);
00260 
00261     // Count the number of StackRestore calls we insert.
00262     unsigned NumStackRestores = Returns.size();
00263     
00264     // If we are inlining an invoke instruction, insert restores before each
00265     // unwind.  These unwinds will be rewritten into branches later.
00266     if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
00267       for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00268            BB != E; ++BB)
00269         if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00270           new CallInst(StackRestore, SavedPtr, "", UI);
00271           ++NumStackRestores;
00272         }
00273     }
00274       
00275     // If we are supposed to update the callgraph, do so now.
00276     if (CG) {
00277       CallGraphNode *StackSaveCGN    = CG->getOrInsertFunction(StackSave);
00278       CallGraphNode *StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
00279       CallGraphNode *CallerNode = (*CG)[Caller];
00280 
00281       // 'Caller' now calls llvm.stacksave one more time.
00282       CallerNode->addCalledFunction(StackSaveCGN);
00283       
00284       // 'Caller' now calls llvm.stackrestore the appropriate number of times.
00285       for (unsigned i = 0; i != NumStackRestores; ++i)
00286         CallerNode->addCalledFunction(StackRestoreCGN);
00287     }
00288   }
00289 
00290   // If we are inlining tail call instruction through a call site that isn't 
00291   // marked 'tail', we must remove the tail marker for any calls in the inlined
00292   // code.
00293   if (MustClearTailCallFlags && InlinedFunctionInfo.ContainsCalls) {
00294     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00295          BB != E; ++BB)
00296       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00297         if (CallInst *CI = dyn_cast<CallInst>(I))
00298           CI->setTailCall(false);
00299   }
00300 
00301   // If we are inlining for an invoke instruction, we must make sure to rewrite
00302   // any inlined 'unwind' instructions into branches to the invoke exception
00303   // destination, and call instructions into invoke instructions.
00304   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00305     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
00306 
00307   // If we cloned in _exactly one_ basic block, and if that block ends in a
00308   // return instruction, we splice the body of the inlined callee directly into
00309   // the calling basic block.
00310   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
00311     // Move all of the instructions right before the call.
00312     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
00313                                  FirstNewBlock->begin(), FirstNewBlock->end());
00314     // Remove the cloned basic block.
00315     Caller->getBasicBlockList().pop_back();
00316 
00317     // If the call site was an invoke instruction, add a branch to the normal
00318     // destination.
00319     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00320       new BranchInst(II->getNormalDest(), TheCall);
00321 
00322     // If the return instruction returned a value, replace uses of the call with
00323     // uses of the returned value.
00324     if (!TheCall->use_empty())
00325       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
00326 
00327     // Since we are now done with the Call/Invoke, we can delete it.
00328     TheCall->getParent()->getInstList().erase(TheCall);
00329 
00330     // Since we are now done with the return instruction, delete it also.
00331     Returns[0]->getParent()->getInstList().erase(Returns[0]);
00332 
00333     // Update the callgraph if requested.
00334     if (CG) UpdateCallGraphAfterInlining(Caller, CalledFunc, *CG);
00335     
00336     // We are now done with the inlining.
00337     return true;
00338   }
00339 
00340   // Otherwise, we have the normal case, of more than one block to inline or
00341   // multiple return sites.
00342 
00343   // We want to clone the entire callee function into the hole between the
00344   // "starter" and "ender" blocks.  How we accomplish this depends on whether
00345   // this is an invoke instruction or a call instruction.
00346   BasicBlock *AfterCallBB;
00347   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
00348 
00349     // Add an unconditional branch to make this look like the CallInst case...
00350     BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
00351 
00352     // Split the basic block.  This guarantees that no PHI nodes will have to be
00353     // updated due to new incoming edges, and make the invoke case more
00354     // symmetric to the call case.
00355     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
00356                                           CalledFunc->getName()+".exit");
00357 
00358   } else {  // It's a call
00359     // If this is a call instruction, we need to split the basic block that
00360     // the call lives in.
00361     //
00362     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
00363                                           CalledFunc->getName()+".exit");
00364   }
00365 
00366   // Change the branch that used to go to AfterCallBB to branch to the first
00367   // basic block of the inlined function.
00368   //
00369   TerminatorInst *Br = OrigBB->getTerminator();
00370   assert(Br && Br->getOpcode() == Instruction::Br &&
00371          "splitBasicBlock broken!");
00372   Br->setOperand(0, FirstNewBlock);
00373 
00374 
00375   // Now that the function is correct, make it a little bit nicer.  In
00376   // particular, move the basic blocks inserted from the end of the function
00377   // into the space made by splitting the source basic block.
00378   //
00379   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
00380                                      FirstNewBlock, Caller->end());
00381 
00382   // Handle all of the return instructions that we just cloned in, and eliminate
00383   // any users of the original call/invoke instruction.
00384   if (Returns.size() > 1) {
00385     // The PHI node should go at the front of the new basic block to merge all
00386     // possible incoming values.
00387     //
00388     PHINode *PHI = 0;
00389     if (!TheCall->use_empty()) {
00390       PHI = new PHINode(CalledFunc->getReturnType(),
00391                         TheCall->getName(), AfterCallBB->begin());
00392 
00393       // Anything that used the result of the function call should now use the
00394       // PHI node as their operand.
00395       //
00396       TheCall->replaceAllUsesWith(PHI);
00397     }
00398 
00399     // Loop over all of the return instructions, turning them into unconditional
00400     // branches to the merge point now, and adding entries to the PHI node as
00401     // appropriate.
00402     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00403       ReturnInst *RI = Returns[i];
00404 
00405       if (PHI) {
00406         assert(RI->getReturnValue() && "Ret should have value!");
00407         assert(RI->getReturnValue()->getType() == PHI->getType() &&
00408                "Ret value not consistent in function!");
00409         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
00410       }
00411 
00412       // Add a branch to the merge point where the PHI node lives if it exists.
00413       new BranchInst(AfterCallBB, RI);
00414 
00415       // Delete the return instruction now
00416       RI->getParent()->getInstList().erase(RI);
00417     }
00418 
00419   } else if (!Returns.empty()) {
00420     // Otherwise, if there is exactly one return value, just replace anything
00421     // using the return value of the call with the computed value.
00422     if (!TheCall->use_empty())
00423       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
00424 
00425     // Splice the code from the return block into the block that it will return
00426     // to, which contains the code that was after the call.
00427     BasicBlock *ReturnBB = Returns[0]->getParent();
00428     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
00429                                       ReturnBB->getInstList());
00430 
00431     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
00432     ReturnBB->replaceAllUsesWith(AfterCallBB);
00433 
00434     // Delete the return instruction now and empty ReturnBB now.
00435     Returns[0]->eraseFromParent();
00436     ReturnBB->eraseFromParent();
00437   } else if (!TheCall->use_empty()) {
00438     // No returns, but something is using the return value of the call.  Just
00439     // nuke the result.
00440     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
00441   }
00442 
00443   // Since we are now done with the Call/Invoke, we can delete it.
00444   TheCall->eraseFromParent();
00445 
00446   // We should always be able to fold the entry block of the function into the
00447   // single predecessor of the block...
00448   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
00449   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
00450 
00451   // Splice the code entry block into calling block, right before the
00452   // unconditional branch.
00453   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
00454   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
00455 
00456   // Remove the unconditional branch.
00457   OrigBB->getInstList().erase(Br);
00458 
00459   // Now we can remove the CalleeEntry block, which is now empty.
00460   Caller->getBasicBlockList().erase(CalleeEntry);
00461   
00462   // Update the callgraph if requested.
00463   if (CG) UpdateCallGraphAfterInlining(Caller, CalledFunc, *CG);
00464 
00465   return true;
00466 }