LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

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 is distributed under the University of Illinois Open Source
00006 // 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/ParameterAttributes.h"
00022 #include "llvm/Analysis/CallGraph.h"
00023 #include "llvm/Target/TargetData.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/Support/CallSite.h"
00027 using namespace llvm;
00028 
00029 bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD) {
00030   return InlineFunction(CallSite(CI), CG, TD);
00031 }
00032 bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD) {
00033   return InlineFunction(CallSite(II), CG, TD);
00034 }
00035 
00036 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
00037 /// in the body of the inlined function into invokes and turn unwind
00038 /// instructions into branches to the invoke unwind dest.
00039 ///
00040 /// II is the invoke instruction begin inlined.  FirstNewBlock is the first
00041 /// block of the inlined code (the last block is the end of the function),
00042 /// and InlineCodeInfo is information about the code that got inlined.
00043 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
00044                                 ClonedCodeInfo &InlinedCodeInfo) {
00045   BasicBlock *InvokeDest = II->getUnwindDest();
00046   std::vector<Value*> InvokeDestPHIValues;
00047 
00048   // If there are PHI nodes in the unwind destination block, we need to
00049   // keep track of which values came into them from this invoke, then remove
00050   // the entry for this block.
00051   BasicBlock *InvokeBlock = II->getParent();
00052   for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
00053     PHINode *PN = cast<PHINode>(I);
00054     // Save the value to use for this edge.
00055     InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
00056   }
00057 
00058   Function *Caller = FirstNewBlock->getParent();
00059   
00060   // The inlined code is currently at the end of the function, scan from the
00061   // start of the inlined code to its end, checking for stuff we need to
00062   // rewrite.
00063   if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
00064     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00065          BB != E; ++BB) {
00066       if (InlinedCodeInfo.ContainsCalls) {
00067         for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
00068           Instruction *I = BBI++;
00069           
00070           // We only need to check for function calls: inlined invoke
00071           // instructions require no special handling.
00072           if (!isa<CallInst>(I)) continue;
00073           CallInst *CI = cast<CallInst>(I);
00074 
00075           // If this call cannot unwind, don't convert it to an invoke.
00076           if (CI->doesNotThrow())
00077             continue;
00078 
00079           // Convert this function call into an invoke instruction.
00080           // First, split the basic block.
00081           BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
00082           
00083           // Next, create the new invoke instruction, inserting it at the end
00084           // of the old basic block.
00085           SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
00086           InvokeInst *II =
00087             InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
00088                                InvokeArgs.begin(), InvokeArgs.end(),
00089                                CI->getName(), BB->getTerminator());
00090           II->setCallingConv(CI->getCallingConv());
00091           II->setParamAttrs(CI->getParamAttrs());
00092           
00093           // Make sure that anything using the call now uses the invoke!
00094           CI->replaceAllUsesWith(II);
00095           
00096           // Delete the unconditional branch inserted by splitBasicBlock
00097           BB->getInstList().pop_back();
00098           Split->getInstList().pop_front();  // Delete the original call
00099           
00100           // Update any PHI nodes in the exceptional block to indicate that
00101           // there is now a new entry in them.
00102           unsigned i = 0;
00103           for (BasicBlock::iterator I = InvokeDest->begin();
00104                isa<PHINode>(I); ++I, ++i) {
00105             PHINode *PN = cast<PHINode>(I);
00106             PN->addIncoming(InvokeDestPHIValues[i], BB);
00107           }
00108             
00109           // This basic block is now complete, start scanning the next one.
00110           break;
00111         }
00112       }
00113       
00114       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00115         // An UnwindInst requires special handling when it gets inlined into an
00116         // invoke site.  Once this happens, we know that the unwind would cause
00117         // a control transfer to the invoke exception destination, so we can
00118         // transform it into a direct branch to the exception destination.
00119         BranchInst::Create(InvokeDest, UI);
00120         
00121         // Delete the unwind instruction!
00122         UI->eraseFromParent();
00123         
00124         // Update any PHI nodes in the exceptional block to indicate that
00125         // there is now a new entry in them.
00126         unsigned i = 0;
00127         for (BasicBlock::iterator I = InvokeDest->begin();
00128              isa<PHINode>(I); ++I, ++i) {
00129           PHINode *PN = cast<PHINode>(I);
00130           PN->addIncoming(InvokeDestPHIValues[i], BB);
00131         }
00132       }
00133     }
00134   }
00135 
00136   // Now that everything is happy, we have one final detail.  The PHI nodes in
00137   // the exception destination block still have entries due to the original
00138   // invoke instruction.  Eliminate these entries (which might even delete the
00139   // PHI node) now.
00140   InvokeDest->removePredecessor(II->getParent());
00141 }
00142 
00143 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
00144 /// into the caller, update the specified callgraph to reflect the changes we
00145 /// made.  Note that it's possible that not all code was copied over, so only
00146 /// some edges of the callgraph will be remain.
00147 static void UpdateCallGraphAfterInlining(const Function *Caller,
00148                                          const Function *Callee,
00149                                          Function::iterator FirstNewBlock,
00150                                        DenseMap<const Value*, Value*> &ValueMap,
00151                                          CallGraph &CG) {
00152   // Update the call graph by deleting the edge from Callee to Caller
00153   CallGraphNode *CalleeNode = CG[Callee];
00154   CallGraphNode *CallerNode = CG[Caller];
00155   CallerNode->removeCallEdgeTo(CalleeNode);
00156   
00157   // Since we inlined some uninlined call sites in the callee into the caller,
00158   // add edges from the caller to all of the callees of the callee.
00159   for (CallGraphNode::iterator I = CalleeNode->begin(),
00160        E = CalleeNode->end(); I != E; ++I) {
00161     const Instruction *OrigCall = I->first.getInstruction();
00162     
00163     DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
00164     // Only copy the edge if the call was inlined!
00165     if (VMI != ValueMap.end() && VMI->second) {
00166       // If the call was inlined, but then constant folded, there is no edge to
00167       // add.  Check for this case.
00168       if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
00169         CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
00170     }
00171   }
00172 }
00173 
00174 
00175 // InlineFunction - This function inlines the called function into the basic
00176 // block of the caller.  This returns false if it is not possible to inline this
00177 // call.  The program is still in a well defined state if this occurs though.
00178 //
00179 // Note that this only does one level of inlining.  For example, if the
00180 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
00181 // exists in the instruction stream.  Similiarly this will inline a recursive
00182 // function by one level.
00183 //
00184 bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD) {
00185   Instruction *TheCall = CS.getInstruction();
00186   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
00187          "Instruction not in function!");
00188 
00189   const Function *CalledFunc = CS.getCalledFunction();
00190   if (CalledFunc == 0 ||          // Can't inline external function or indirect
00191       CalledFunc->isDeclaration() || // call, or call to a vararg function!
00192       CalledFunc->getFunctionType()->isVarArg()) return false;
00193 
00194 
00195   // If the call to the callee is a non-tail call, we must clear the 'tail'
00196   // flags on any calls that we inline.
00197   bool MustClearTailCallFlags =
00198     isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
00199 
00200   // If the call to the callee cannot throw, set the 'nounwind' flag on any
00201   // calls that we inline.
00202   bool MarkNoUnwind = CS.doesNotThrow();
00203 
00204   BasicBlock *OrigBB = TheCall->getParent();
00205   Function *Caller = OrigBB->getParent();
00206 
00207   // GC poses two hazards to inlining, which only occur when the callee has GC:
00208   //  1. If the caller has no GC, then the callee's GC must be propagated to the
00209   //     caller.
00210   //  2. If the caller has a differing GC, it is invalid to inline.
00211   if (CalledFunc->hasGC()) {
00212     if (!Caller->hasGC())
00213       Caller->setGC(CalledFunc->getGC());
00214     else if (CalledFunc->getGC() != Caller->getGC())
00215       return false;
00216   }
00217   
00218   // Get an iterator to the last basic block in the function, which will have
00219   // the new function inlined after it.
00220   //
00221   Function::iterator LastBlock = &Caller->back();
00222 
00223   // Make sure to capture all of the return instructions from the cloned
00224   // function.
00225   std::vector<ReturnInst*> Returns;
00226   ClonedCodeInfo InlinedFunctionInfo;
00227   Function::iterator FirstNewBlock;
00228 
00229   { // Scope to destroy ValueMap after cloning.
00230     DenseMap<const Value*, Value*> ValueMap;
00231 
00232     assert(CalledFunc->arg_size() == CS.arg_size() &&
00233            "No varargs calls can be inlined!");
00234     
00235     // Calculate the vector of arguments to pass into the function cloner, which
00236     // matches up the formal to the actual argument values.
00237     CallSite::arg_iterator AI = CS.arg_begin();
00238     unsigned ArgNo = 0;
00239     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00240          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
00241       Value *ActualArg = *AI;
00242       
00243       // When byval arguments actually inlined, we need to make the copy implied
00244       // by them explicit.  However, we don't do this if the callee is readonly
00245       // or readnone, because the copy would be unneeded: the callee doesn't
00246       // modify the struct.
00247       if (CalledFunc->paramHasAttr(ArgNo+1, ParamAttr::ByVal) &&
00248           !CalledFunc->onlyReadsMemory()) {
00249         const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
00250         const Type *VoidPtrTy = PointerType::getUnqual(Type::Int8Ty);
00251         
00252         // Create the alloca.  If we have TargetData, use nice alignment.
00253         unsigned Align = 1;
00254         if (TD) Align = TD->getPrefTypeAlignment(AggTy);
00255         Value *NewAlloca = new AllocaInst(AggTy, 0, Align, I->getName(), 
00256                                           Caller->begin()->begin());
00257         // Emit a memcpy.
00258         Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
00259                                                        Intrinsic::memcpy_i64);
00260         Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
00261         Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
00262         
00263         Value *Size;
00264         if (TD == 0)
00265           Size = ConstantExpr::getSizeOf(AggTy);
00266         else
00267           Size = ConstantInt::get(Type::Int64Ty, TD->getTypeStoreSize(AggTy));
00268         
00269         // Always generate a memcpy of alignment 1 here because we don't know
00270         // the alignment of the src pointer.  Other optimizations can infer
00271         // better alignment.
00272         Value *CallArgs[] = {
00273           DestCast, SrcCast, Size, ConstantInt::get(Type::Int32Ty, 1)
00274         };
00275         CallInst *TheMemCpy =
00276           CallInst::Create(MemCpyFn, CallArgs, CallArgs+4, "", TheCall);
00277         
00278         // If we have a call graph, update it.
00279         if (CG) {
00280           CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
00281           CallGraphNode *CallerNode = (*CG)[Caller];
00282           CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
00283         }
00284         
00285         // Uses of the argument in the function should use our new alloca
00286         // instead.
00287         ActualArg = NewAlloca;
00288       }
00289       
00290       ValueMap[I] = ActualArg;
00291     }
00292 
00293     // We want the inliner to prune the code as it copies.  We would LOVE to
00294     // have no dead or constant instructions leftover after inlining occurs
00295     // (which can happen, e.g., because an argument was constant), but we'll be
00296     // happy with whatever the cloner can do.
00297     CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
00298                               &InlinedFunctionInfo, TD);
00299     
00300     // Remember the first block that is newly cloned over.
00301     FirstNewBlock = LastBlock; ++FirstNewBlock;
00302     
00303     // Update the callgraph if requested.
00304     if (CG)
00305       UpdateCallGraphAfterInlining(Caller, CalledFunc, FirstNewBlock, ValueMap,
00306                                    *CG);
00307   }
00308  
00309   // If there are any alloca instructions in the block that used to be the entry
00310   // block for the callee, move them to the entry block of the caller.  First
00311   // calculate which instruction they should be inserted before.  We insert the
00312   // instructions at the end of the current alloca list.
00313   //
00314   {
00315     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
00316     for (BasicBlock::iterator I = FirstNewBlock->begin(),
00317            E = FirstNewBlock->end(); I != E; )
00318       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++)) {
00319         // If the alloca is now dead, remove it.  This often occurs due to code
00320         // specialization.
00321         if (AI->use_empty()) {
00322           AI->eraseFromParent();
00323           continue;
00324         }
00325         
00326         if (isa<Constant>(AI->getArraySize())) {
00327           // Scan for the block of allocas that we can move over, and move them
00328           // all at once.
00329           while (isa<AllocaInst>(I) &&
00330                  isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
00331             ++I;
00332 
00333           // Transfer all of the allocas over in a block.  Using splice means
00334           // that the instructions aren't removed from the symbol table, then
00335           // reinserted.
00336           Caller->getEntryBlock().getInstList().splice(
00337               InsertPoint,
00338               FirstNewBlock->getInstList(),
00339               AI, I);
00340         }
00341       }
00342   }
00343 
00344   // If the inlined code contained dynamic alloca instructions, wrap the inlined
00345   // code with llvm.stacksave/llvm.stackrestore intrinsics.
00346   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
00347     Module *M = Caller->getParent();
00348     // Get the two intrinsics we care about.
00349     Constant *StackSave, *StackRestore;
00350     StackSave    = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
00351     StackRestore = Intrinsic::getDeclaration(M, Intrinsic::stackrestore);
00352 
00353     // If we are preserving the callgraph, add edges to the stacksave/restore
00354     // functions for the calls we insert.
00355     CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
00356     if (CG) {
00357       // We know that StackSave/StackRestore are Function*'s, because they are
00358       // intrinsics which must have the right types.
00359       StackSaveCGN    = CG->getOrInsertFunction(cast<Function>(StackSave));
00360       StackRestoreCGN = CG->getOrInsertFunction(cast<Function>(StackRestore));
00361       CallerNode = (*CG)[Caller];
00362     }
00363       
00364     // Insert the llvm.stacksave.
00365     CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack", 
00366                                           FirstNewBlock->begin());
00367     if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
00368       
00369     // Insert a call to llvm.stackrestore before any return instructions in the
00370     // inlined function.
00371     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00372       CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
00373       if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
00374     }
00375 
00376     // Count the number of StackRestore calls we insert.
00377     unsigned NumStackRestores = Returns.size();
00378     
00379     // If we are inlining an invoke instruction, insert restores before each
00380     // unwind.  These unwinds will be rewritten into branches later.
00381     if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
00382       for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00383            BB != E; ++BB)
00384         if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00385           CallInst::Create(StackRestore, SavedPtr, "", UI);
00386           ++NumStackRestores;
00387         }
00388     }
00389   }
00390 
00391   // If we are inlining tail call instruction through a call site that isn't 
00392   // marked 'tail', we must remove the tail marker for any calls in the inlined
00393   // code.  Also, calls inlined through a 'nounwind' call site should be marked
00394   // 'nounwind'.
00395   if (InlinedFunctionInfo.ContainsCalls &&
00396       (MustClearTailCallFlags || MarkNoUnwind)) {
00397     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00398          BB != E; ++BB)
00399       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00400         if (CallInst *CI = dyn_cast<CallInst>(I)) {
00401           if (MustClearTailCallFlags)
00402             CI->setTailCall(false);
00403           if (MarkNoUnwind)
00404             CI->setDoesNotThrow();
00405         }
00406   }
00407 
00408   // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
00409   // instructions are unreachable.
00410   if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
00411     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00412          BB != E; ++BB) {
00413       TerminatorInst *Term = BB->getTerminator();
00414       if (isa<UnwindInst>(Term)) {
00415         new UnreachableInst(Term);
00416         BB->getInstList().erase(Term);
00417       }
00418     }
00419 
00420   // If we are inlining for an invoke instruction, we must make sure to rewrite
00421   // any inlined 'unwind' instructions into branches to the invoke exception
00422   // destination, and call instructions into invoke instructions.
00423   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00424     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
00425 
00426   // If we cloned in _exactly one_ basic block, and if that block ends in a
00427   // return instruction, we splice the body of the inlined callee directly into
00428   // the calling basic block.
00429   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
00430     // Move all of the instructions right before the call.
00431     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
00432                                  FirstNewBlock->begin(), FirstNewBlock->end());
00433     // Remove the cloned basic block.
00434     Caller->getBasicBlockList().pop_back();
00435 
00436     // If the call site was an invoke instruction, add a branch to the normal
00437     // destination.
00438     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00439       BranchInst::Create(II->getNormalDest(), TheCall);
00440 
00441     // If the return instruction returned a value, replace uses of the call with
00442     // uses of the returned value.
00443     if (!TheCall->use_empty()) {
00444       ReturnInst *R = Returns[0];
00445       TheCall->replaceAllUsesWith(R->getReturnValue());
00446     }
00447     // Since we are now done with the Call/Invoke, we can delete it.
00448     TheCall->eraseFromParent();
00449 
00450     // Since we are now done with the return instruction, delete it also.
00451     Returns[0]->eraseFromParent();
00452 
00453     // We are now done with the inlining.
00454     return true;
00455   }
00456 
00457   // Otherwise, we have the normal case, of more than one block to inline or
00458   // multiple return sites.
00459 
00460   // We want to clone the entire callee function into the hole between the
00461   // "starter" and "ender" blocks.  How we accomplish this depends on whether
00462   // this is an invoke instruction or a call instruction.
00463   BasicBlock *AfterCallBB;
00464   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
00465 
00466     // Add an unconditional branch to make this look like the CallInst case...
00467     BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
00468 
00469     // Split the basic block.  This guarantees that no PHI nodes will have to be
00470     // updated due to new incoming edges, and make the invoke case more
00471     // symmetric to the call case.
00472     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
00473                                           CalledFunc->getName()+".exit");
00474 
00475   } else {  // It's a call
00476     // If this is a call instruction, we need to split the basic block that
00477     // the call lives in.
00478     //
00479     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
00480                                           CalledFunc->getName()+".exit");
00481   }
00482 
00483   // Change the branch that used to go to AfterCallBB to branch to the first
00484   // basic block of the inlined function.
00485   //
00486   TerminatorInst *Br = OrigBB->getTerminator();
00487   assert(Br && Br->getOpcode() == Instruction::Br &&
00488          "splitBasicBlock broken!");
00489   Br->setOperand(0, FirstNewBlock);
00490 
00491 
00492   // Now that the function is correct, make it a little bit nicer.  In
00493   // particular, move the basic blocks inserted from the end of the function
00494   // into the space made by splitting the source basic block.
00495   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
00496                                      FirstNewBlock, Caller->end());
00497 
00498   // Handle all of the return instructions that we just cloned in, and eliminate
00499   // any users of the original call/invoke instruction.
00500   const Type *RTy = CalledFunc->getReturnType();
00501 
00502   if (Returns.size() > 1) {
00503     // The PHI node should go at the front of the new basic block to merge all
00504     // possible incoming values.
00505     PHINode *PHI = 0;
00506     if (!TheCall->use_empty()) {
00507       PHI = PHINode::Create(RTy, TheCall->getName(),
00508                             AfterCallBB->begin());
00509       // Anything that used the result of the function call should now use the
00510       // PHI node as their operand.
00511       TheCall->replaceAllUsesWith(PHI); 
00512     }
00513 
00514     // Loop over all of the return instructions adding entries to the PHI node as
00515     // appropriate.
00516     if (PHI) {
00517       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00518         ReturnInst *RI = Returns[i];
00519         assert(RI->getReturnValue()->getType() == PHI->getType() &&
00520                "Ret value not consistent in function!");
00521         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
00522       }
00523     }
00524 
00525     // Add a branch to the merge points and remove retrun instructions.
00526     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00527       ReturnInst *RI = Returns[i];
00528       BranchInst::Create(AfterCallBB, RI);
00529       RI->eraseFromParent();
00530     }
00531   } else if (!Returns.empty()) {
00532     // Otherwise, if there is exactly one return value, just replace anything
00533     // using the return value of the call with the computed value.
00534     if (!TheCall->use_empty())
00535       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
00536     
00537     // Splice the code from the return block into the block that it will return
00538     // to, which contains the code that was after the call.
00539     BasicBlock *ReturnBB = Returns[0]->getParent();
00540     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
00541                                       ReturnBB->getInstList());
00542     
00543     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
00544     ReturnBB->replaceAllUsesWith(AfterCallBB);
00545     
00546     // Delete the return instruction now and empty ReturnBB now.
00547     Returns[0]->eraseFromParent();
00548     ReturnBB->eraseFromParent();
00549   } else if (!TheCall->use_empty()) {
00550     // No returns, but something is using the return value of the call.  Just
00551     // nuke the result.
00552     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
00553   }
00554 
00555   // Since we are now done with the Call/Invoke, we can delete it.
00556   TheCall->eraseFromParent();
00557 
00558   // We should always be able to fold the entry block of the function into the
00559   // single predecessor of the block...
00560   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
00561   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
00562 
00563   // Splice the code entry block into calling block, right before the
00564   // unconditional branch.
00565   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
00566   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
00567 
00568   // Remove the unconditional branch.
00569   OrigBB->getInstList().erase(Br);
00570 
00571   // Now we can remove the CalleeEntry block, which is now empty.
00572   Caller->getBasicBlockList().erase(CalleeEntry);
00573   
00574   return true;
00575 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.