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 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/ADT/SmallVector.h"
00017 #include "llvm/ADT/StringExtras.h"
00018 #include "llvm/Analysis/CallGraph.h"
00019 #include "llvm/Analysis/InstructionSimplify.h"
00020 #include "llvm/IR/Attributes.h"
00021 #include "llvm/IR/CallSite.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/DebugInfo.h"
00025 #include "llvm/IR/DerivedTypes.h"
00026 #include "llvm/IR/IRBuilder.h"
00027 #include "llvm/IR/Instructions.h"
00028 #include "llvm/IR/IntrinsicInst.h"
00029 #include "llvm/IR/Intrinsics.h"
00030 #include "llvm/IR/Module.h"
00031 #include "llvm/Transforms/Utils/Local.h"
00032 using namespace llvm;
00033 
00034 bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
00035                           bool InsertLifetime) {
00036   return InlineFunction(CallSite(CI), IFI, InsertLifetime);
00037 }
00038 bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
00039                           bool InsertLifetime) {
00040   return InlineFunction(CallSite(II), IFI, InsertLifetime);
00041 }
00042 
00043 namespace {
00044   /// A class for recording information about inlining through an invoke.
00045   class InvokeInliningInfo {
00046     BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
00047     BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
00048     LandingPadInst *CallerLPad;  ///< LandingPadInst associated with the invoke.
00049     PHINode *InnerEHValuesPHI;   ///< PHI for EH values from landingpad insts.
00050     SmallVector<Value*, 8> UnwindDestPHIValues;
00051 
00052   public:
00053     InvokeInliningInfo(InvokeInst *II)
00054       : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(0),
00055         CallerLPad(0), InnerEHValuesPHI(0) {
00056       // If there are PHI nodes in the unwind destination block, we need to keep
00057       // track of which values came into them from the invoke before removing
00058       // the edge from this block.
00059       llvm::BasicBlock *InvokeBB = II->getParent();
00060       BasicBlock::iterator I = OuterResumeDest->begin();
00061       for (; isa<PHINode>(I); ++I) {
00062         // Save the value to use for this edge.
00063         PHINode *PHI = cast<PHINode>(I);
00064         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
00065       }
00066 
00067       CallerLPad = cast<LandingPadInst>(I);
00068     }
00069 
00070     /// getOuterResumeDest - The outer unwind destination is the target of
00071     /// unwind edges introduced for calls within the inlined function.
00072     BasicBlock *getOuterResumeDest() const {
00073       return OuterResumeDest;
00074     }
00075 
00076     BasicBlock *getInnerResumeDest();
00077 
00078     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
00079 
00080     /// forwardResume - Forward the 'resume' instruction to the caller's landing
00081     /// pad block. When the landing pad block has only one predecessor, this is
00082     /// a simple branch. When there is more than one predecessor, we need to
00083     /// split the landing pad block after the landingpad instruction and jump
00084     /// to there.
00085     void forwardResume(ResumeInst *RI,
00086                        SmallPtrSet<LandingPadInst*, 16> &InlinedLPads);
00087 
00088     /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
00089     /// destination block for the given basic block, using the values for the
00090     /// original invoke's source block.
00091     void addIncomingPHIValuesFor(BasicBlock *BB) const {
00092       addIncomingPHIValuesForInto(BB, OuterResumeDest);
00093     }
00094 
00095     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
00096       BasicBlock::iterator I = dest->begin();
00097       for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
00098         PHINode *phi = cast<PHINode>(I);
00099         phi->addIncoming(UnwindDestPHIValues[i], src);
00100       }
00101     }
00102   };
00103 }
00104 
00105 /// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
00106 BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
00107   if (InnerResumeDest) return InnerResumeDest;
00108 
00109   // Split the landing pad.
00110   BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
00111   InnerResumeDest =
00112     OuterResumeDest->splitBasicBlock(SplitPoint,
00113                                      OuterResumeDest->getName() + ".body");
00114 
00115   // The number of incoming edges we expect to the inner landing pad.
00116   const unsigned PHICapacity = 2;
00117 
00118   // Create corresponding new PHIs for all the PHIs in the outer landing pad.
00119   BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
00120   BasicBlock::iterator I = OuterResumeDest->begin();
00121   for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
00122     PHINode *OuterPHI = cast<PHINode>(I);
00123     PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
00124                                         OuterPHI->getName() + ".lpad-body",
00125                                         InsertPoint);
00126     OuterPHI->replaceAllUsesWith(InnerPHI);
00127     InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
00128   }
00129 
00130   // Create a PHI for the exception values.
00131   InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
00132                                      "eh.lpad-body", InsertPoint);
00133   CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
00134   InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
00135 
00136   // All done.
00137   return InnerResumeDest;
00138 }
00139 
00140 /// forwardResume - Forward the 'resume' instruction to the caller's landing pad
00141 /// block. When the landing pad block has only one predecessor, this is a simple
00142 /// branch. When there is more than one predecessor, we need to split the
00143 /// landing pad block after the landingpad instruction and jump to there.
00144 void InvokeInliningInfo::forwardResume(ResumeInst *RI,
00145                                SmallPtrSet<LandingPadInst*, 16> &InlinedLPads) {
00146   BasicBlock *Dest = getInnerResumeDest();
00147   BasicBlock *Src = RI->getParent();
00148 
00149   BranchInst::Create(Dest, Src);
00150 
00151   // Update the PHIs in the destination. They were inserted in an order which
00152   // makes this work.
00153   addIncomingPHIValuesForInto(Src, Dest);
00154 
00155   InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
00156   RI->eraseFromParent();
00157 }
00158 
00159 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
00160 /// an invoke, we have to turn all of the calls that can throw into
00161 /// invokes.  This function analyze BB to see if there are any calls, and if so,
00162 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
00163 /// nodes in that block with the values specified in InvokeDestPHIValues.
00164 static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
00165                                                    InvokeInliningInfo &Invoke) {
00166   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
00167     Instruction *I = BBI++;
00168 
00169     // We only need to check for function calls: inlined invoke
00170     // instructions require no special handling.
00171     CallInst *CI = dyn_cast<CallInst>(I);
00172 
00173     // If this call cannot unwind, don't convert it to an invoke.
00174     // Inline asm calls cannot throw.
00175     if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
00176       continue;
00177 
00178     // Convert this function call into an invoke instruction.  First, split the
00179     // basic block.
00180     BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
00181 
00182     // Delete the unconditional branch inserted by splitBasicBlock
00183     BB->getInstList().pop_back();
00184 
00185     // Create the new invoke instruction.
00186     ImmutableCallSite CS(CI);
00187     SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
00188     InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
00189                                         Invoke.getOuterResumeDest(),
00190                                         InvokeArgs, CI->getName(), BB);
00191     II->setCallingConv(CI->getCallingConv());
00192     II->setAttributes(CI->getAttributes());
00193     
00194     // Make sure that anything using the call now uses the invoke!  This also
00195     // updates the CallGraph if present, because it uses a WeakVH.
00196     CI->replaceAllUsesWith(II);
00197 
00198     // Delete the original call
00199     Split->getInstList().pop_front();
00200 
00201     // Update any PHI nodes in the exceptional block to indicate that there is
00202     // now a new entry in them.
00203     Invoke.addIncomingPHIValuesFor(BB);
00204     return;
00205   }
00206 }
00207 
00208 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
00209 /// in the body of the inlined function into invokes.
00210 ///
00211 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
00212 /// block of the inlined code (the last block is the end of the function),
00213 /// and InlineCodeInfo is information about the code that got inlined.
00214 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
00215                                 ClonedCodeInfo &InlinedCodeInfo) {
00216   BasicBlock *InvokeDest = II->getUnwindDest();
00217 
00218   Function *Caller = FirstNewBlock->getParent();
00219 
00220   // The inlined code is currently at the end of the function, scan from the
00221   // start of the inlined code to its end, checking for stuff we need to
00222   // rewrite.
00223   InvokeInliningInfo Invoke(II);
00224 
00225   // Get all of the inlined landing pad instructions.
00226   SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
00227   for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
00228     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
00229       InlinedLPads.insert(II->getLandingPadInst());
00230 
00231   // Append the clauses from the outer landing pad instruction into the inlined
00232   // landing pad instructions.
00233   LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
00234   for (SmallPtrSet<LandingPadInst*, 16>::iterator I = InlinedLPads.begin(),
00235          E = InlinedLPads.end(); I != E; ++I) {
00236     LandingPadInst *InlinedLPad = *I;
00237     unsigned OuterNum = OuterLPad->getNumClauses();
00238     InlinedLPad->reserveClauses(OuterNum);
00239     for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
00240       InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
00241     if (OuterLPad->isCleanup())
00242       InlinedLPad->setCleanup(true);
00243   }
00244 
00245   for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
00246     if (InlinedCodeInfo.ContainsCalls)
00247       HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
00248 
00249     // Forward any resumes that are remaining here.
00250     if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
00251       Invoke.forwardResume(RI, InlinedLPads);
00252   }
00253 
00254   // Now that everything is happy, we have one final detail.  The PHI nodes in
00255   // the exception destination block still have entries due to the original
00256   // invoke instruction. Eliminate these entries (which might even delete the
00257   // PHI node) now.
00258   InvokeDest->removePredecessor(II->getParent());
00259 }
00260 
00261 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
00262 /// into the caller, update the specified callgraph to reflect the changes we
00263 /// made.  Note that it's possible that not all code was copied over, so only
00264 /// some edges of the callgraph may remain.
00265 static void UpdateCallGraphAfterInlining(CallSite CS,
00266                                          Function::iterator FirstNewBlock,
00267                                          ValueToValueMapTy &VMap,
00268                                          InlineFunctionInfo &IFI) {
00269   CallGraph &CG = *IFI.CG;
00270   const Function *Caller = CS.getInstruction()->getParent()->getParent();
00271   const Function *Callee = CS.getCalledFunction();
00272   CallGraphNode *CalleeNode = CG[Callee];
00273   CallGraphNode *CallerNode = CG[Caller];
00274 
00275   // Since we inlined some uninlined call sites in the callee into the caller,
00276   // add edges from the caller to all of the callees of the callee.
00277   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
00278 
00279   // Consider the case where CalleeNode == CallerNode.
00280   CallGraphNode::CalledFunctionsVector CallCache;
00281   if (CalleeNode == CallerNode) {
00282     CallCache.assign(I, E);
00283     I = CallCache.begin();
00284     E = CallCache.end();
00285   }
00286 
00287   for (; I != E; ++I) {
00288     const Value *OrigCall = I->first;
00289 
00290     ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
00291     // Only copy the edge if the call was inlined!
00292     if (VMI == VMap.end() || VMI->second == 0)
00293       continue;
00294     
00295     // If the call was inlined, but then constant folded, there is no edge to
00296     // add.  Check for this case.
00297     Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
00298     if (NewCall == 0) continue;
00299 
00300     // Remember that this call site got inlined for the client of
00301     // InlineFunction.
00302     IFI.InlinedCalls.push_back(NewCall);
00303 
00304     // It's possible that inlining the callsite will cause it to go from an
00305     // indirect to a direct call by resolving a function pointer.  If this
00306     // happens, set the callee of the new call site to a more precise
00307     // destination.  This can also happen if the call graph node of the caller
00308     // was just unnecessarily imprecise.
00309     if (I->second->getFunction() == 0)
00310       if (Function *F = CallSite(NewCall).getCalledFunction()) {
00311         // Indirect call site resolved to direct call.
00312         CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
00313 
00314         continue;
00315       }
00316 
00317     CallerNode->addCalledFunction(CallSite(NewCall), I->second);
00318   }
00319   
00320   // Update the call graph by deleting the edge from Callee to Caller.  We must
00321   // do this after the loop above in case Caller and Callee are the same.
00322   CallerNode->removeCallEdgeFor(CS);
00323 }
00324 
00325 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
00326                                     BasicBlock *InsertBlock,
00327                                     InlineFunctionInfo &IFI) {
00328   LLVMContext &Context = Src->getContext();
00329   Type *VoidPtrTy = Type::getInt8PtrTy(Context);
00330   Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
00331   Type *Tys[3] = { VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context) };
00332   Function *MemCpyFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
00333   IRBuilder<> builder(InsertBlock->begin());
00334   Value *DstCast = builder.CreateBitCast(Dst, VoidPtrTy, "tmp");
00335   Value *SrcCast = builder.CreateBitCast(Src, VoidPtrTy, "tmp");
00336 
00337   Value *Size;
00338   if (IFI.DL == 0)
00339     Size = ConstantExpr::getSizeOf(AggTy);
00340   else
00341     Size = ConstantInt::get(Type::getInt64Ty(Context),
00342                             IFI.DL->getTypeStoreSize(AggTy));
00343 
00344   // Always generate a memcpy of alignment 1 here because we don't know
00345   // the alignment of the src pointer.  Other optimizations can infer
00346   // better alignment.
00347   Value *CallArgs[] = {
00348     DstCast, SrcCast, Size,
00349     ConstantInt::get(Type::getInt32Ty(Context), 1),
00350     ConstantInt::getFalse(Context) // isVolatile
00351   };
00352   builder.CreateCall(MemCpyFn, CallArgs);
00353 }
00354 
00355 /// HandleByValArgument - When inlining a call site that has a byval argument,
00356 /// we have to make the implicit memcpy explicit by adding it.
00357 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
00358                                   const Function *CalledFunc,
00359                                   InlineFunctionInfo &IFI,
00360                                   unsigned ByValAlignment) {
00361   Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
00362 
00363   // If the called function is readonly, then it could not mutate the caller's
00364   // copy of the byval'd memory.  In this case, it is safe to elide the copy and
00365   // temporary.
00366   if (CalledFunc->onlyReadsMemory()) {
00367     // If the byval argument has a specified alignment that is greater than the
00368     // passed in pointer, then we either have to round up the input pointer or
00369     // give up on this transformation.
00370     if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
00371       return Arg;
00372 
00373     // If the pointer is already known to be sufficiently aligned, or if we can
00374     // round it up to a larger alignment, then we don't need a temporary.
00375     if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
00376                                    IFI.DL) >= ByValAlignment)
00377       return Arg;
00378     
00379     // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
00380     // for code quality, but rarely happens and is required for correctness.
00381   }
00382 
00383   // Create the alloca.  If we have DataLayout, use nice alignment.
00384   unsigned Align = 1;
00385   if (IFI.DL)
00386     Align = IFI.DL->getPrefTypeAlignment(AggTy);
00387   
00388   // If the byval had an alignment specified, we *must* use at least that
00389   // alignment, as it is required by the byval argument (and uses of the
00390   // pointer inside the callee).
00391   Align = std::max(Align, ByValAlignment);
00392   
00393   Function *Caller = TheCall->getParent()->getParent(); 
00394   
00395   Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(), 
00396                                     &*Caller->begin()->begin());
00397   IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
00398   
00399   // Uses of the argument in the function should use our new alloca
00400   // instead.
00401   return NewAlloca;
00402 }
00403 
00404 // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
00405 // intrinsic.
00406 static bool isUsedByLifetimeMarker(Value *V) {
00407   for (User *U : V->users()) {
00408     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
00409       switch (II->getIntrinsicID()) {
00410       default: break;
00411       case Intrinsic::lifetime_start:
00412       case Intrinsic::lifetime_end:
00413         return true;
00414       }
00415     }
00416   }
00417   return false;
00418 }
00419 
00420 // hasLifetimeMarkers - Check whether the given alloca already has
00421 // lifetime.start or lifetime.end intrinsics.
00422 static bool hasLifetimeMarkers(AllocaInst *AI) {
00423   Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
00424   if (AI->getType() == Int8PtrTy)
00425     return isUsedByLifetimeMarker(AI);
00426 
00427   // Do a scan to find all the casts to i8*.
00428   for (User *U : AI->users()) {
00429     if (U->getType() != Int8PtrTy) continue;
00430     if (U->stripPointerCasts() != AI) continue;
00431     if (isUsedByLifetimeMarker(U))
00432       return true;
00433   }
00434   return false;
00435 }
00436 
00437 /// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
00438 /// recursively update InlinedAtEntry of a DebugLoc.
00439 static DebugLoc updateInlinedAtInfo(const DebugLoc &DL, 
00440                                     const DebugLoc &InlinedAtDL,
00441                                     LLVMContext &Ctx) {
00442   if (MDNode *IA = DL.getInlinedAt(Ctx)) {
00443     DebugLoc NewInlinedAtDL 
00444       = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
00445     return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
00446                          NewInlinedAtDL.getAsMDNode(Ctx));
00447   }
00448 
00449   return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
00450                        InlinedAtDL.getAsMDNode(Ctx));
00451 }
00452 
00453 /// fixupLineNumbers - Update inlined instructions' line numbers to 
00454 /// to encode location where these instructions are inlined.
00455 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
00456                              Instruction *TheCall) {
00457   DebugLoc TheCallDL = TheCall->getDebugLoc();
00458   if (TheCallDL.isUnknown())
00459     return;
00460 
00461   for (; FI != Fn->end(); ++FI) {
00462     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
00463          BI != BE; ++BI) {
00464       DebugLoc DL = BI->getDebugLoc();
00465       if (!DL.isUnknown()) {
00466         BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
00467         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
00468           LLVMContext &Ctx = BI->getContext();
00469           MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
00470           DVI->setOperand(2, createInlinedVariable(DVI->getVariable(), 
00471                                                    InlinedAt, Ctx));
00472         }
00473       }
00474     }
00475   }
00476 }
00477 
00478 /// InlineFunction - This function inlines the called function into the basic
00479 /// block of the caller.  This returns false if it is not possible to inline
00480 /// this call.  The program is still in a well defined state if this occurs
00481 /// though.
00482 ///
00483 /// Note that this only does one level of inlining.  For example, if the
00484 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
00485 /// exists in the instruction stream.  Similarly this will inline a recursive
00486 /// function by one level.
00487 bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
00488                           bool InsertLifetime) {
00489   Instruction *TheCall = CS.getInstruction();
00490   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
00491          "Instruction not in function!");
00492 
00493   // If IFI has any state in it, zap it before we fill it in.
00494   IFI.reset();
00495   
00496   const Function *CalledFunc = CS.getCalledFunction();
00497   if (CalledFunc == 0 ||          // Can't inline external function or indirect
00498       CalledFunc->isDeclaration() || // call, or call to a vararg function!
00499       CalledFunc->getFunctionType()->isVarArg()) return false;
00500 
00501   // If the call to the callee is not a tail call, we must clear the 'tail'
00502   // flags on any calls that we inline.
00503   bool MustClearTailCallFlags =
00504     !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
00505 
00506   // If the call to the callee cannot throw, set the 'nounwind' flag on any
00507   // calls that we inline.
00508   bool MarkNoUnwind = CS.doesNotThrow();
00509 
00510   BasicBlock *OrigBB = TheCall->getParent();
00511   Function *Caller = OrigBB->getParent();
00512 
00513   // GC poses two hazards to inlining, which only occur when the callee has GC:
00514   //  1. If the caller has no GC, then the callee's GC must be propagated to the
00515   //     caller.
00516   //  2. If the caller has a differing GC, it is invalid to inline.
00517   if (CalledFunc->hasGC()) {
00518     if (!Caller->hasGC())
00519       Caller->setGC(CalledFunc->getGC());
00520     else if (CalledFunc->getGC() != Caller->getGC())
00521       return false;
00522   }
00523 
00524   // Get the personality function from the callee if it contains a landing pad.
00525   Value *CalleePersonality = 0;
00526   for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
00527        I != E; ++I)
00528     if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
00529       const BasicBlock *BB = II->getUnwindDest();
00530       const LandingPadInst *LP = BB->getLandingPadInst();
00531       CalleePersonality = LP->getPersonalityFn();
00532       break;
00533     }
00534 
00535   // Find the personality function used by the landing pads of the caller. If it
00536   // exists, then check to see that it matches the personality function used in
00537   // the callee.
00538   if (CalleePersonality) {
00539     for (Function::const_iterator I = Caller->begin(), E = Caller->end();
00540          I != E; ++I)
00541       if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
00542         const BasicBlock *BB = II->getUnwindDest();
00543         const LandingPadInst *LP = BB->getLandingPadInst();
00544 
00545         // If the personality functions match, then we can perform the
00546         // inlining. Otherwise, we can't inline.
00547         // TODO: This isn't 100% true. Some personality functions are proper
00548         //       supersets of others and can be used in place of the other.
00549         if (LP->getPersonalityFn() != CalleePersonality)
00550           return false;
00551 
00552         break;
00553       }
00554   }
00555 
00556   // Get an iterator to the last basic block in the function, which will have
00557   // the new function inlined after it.
00558   Function::iterator LastBlock = &Caller->back();
00559 
00560   // Make sure to capture all of the return instructions from the cloned
00561   // function.
00562   SmallVector<ReturnInst*, 8> Returns;
00563   ClonedCodeInfo InlinedFunctionInfo;
00564   Function::iterator FirstNewBlock;
00565 
00566   { // Scope to destroy VMap after cloning.
00567     ValueToValueMapTy VMap;
00568     // Keep a list of pair (dst, src) to emit byval initializations.
00569     SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
00570 
00571     assert(CalledFunc->arg_size() == CS.arg_size() &&
00572            "No varargs calls can be inlined!");
00573 
00574     // Calculate the vector of arguments to pass into the function cloner, which
00575     // matches up the formal to the actual argument values.
00576     CallSite::arg_iterator AI = CS.arg_begin();
00577     unsigned ArgNo = 0;
00578     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00579          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
00580       Value *ActualArg = *AI;
00581 
00582       // When byval arguments actually inlined, we need to make the copy implied
00583       // by them explicit.  However, we don't do this if the callee is readonly
00584       // or readnone, because the copy would be unneeded: the callee doesn't
00585       // modify the struct.
00586       if (CS.isByValArgument(ArgNo)) {
00587         ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
00588                                         CalledFunc->getParamAlignment(ArgNo+1));
00589  
00590         // Calls that we inline may use the new alloca, so we need to clear
00591         // their 'tail' flags if HandleByValArgument introduced a new alloca and
00592         // the callee has calls.
00593         if (ActualArg != *AI) {
00594           MustClearTailCallFlags = true;
00595           ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
00596         }
00597 
00598       }
00599 
00600       VMap[I] = ActualArg;
00601     }
00602 
00603     // We want the inliner to prune the code as it copies.  We would LOVE to
00604     // have no dead or constant instructions leftover after inlining occurs
00605     // (which can happen, e.g., because an argument was constant), but we'll be
00606     // happy with whatever the cloner can do.
00607     CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, 
00608                               /*ModuleLevelChanges=*/false, Returns, ".i",
00609                               &InlinedFunctionInfo, IFI.DL, TheCall);
00610 
00611     // Remember the first block that is newly cloned over.
00612     FirstNewBlock = LastBlock; ++FirstNewBlock;
00613 
00614     // Inject byval arguments initialization.
00615     for (std::pair<Value*, Value*> &Init : ByValInit)
00616       HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
00617                               FirstNewBlock, IFI);
00618 
00619     // Update the callgraph if requested.
00620     if (IFI.CG)
00621       UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
00622 
00623     // Update inlined instructions' line number information.
00624     fixupLineNumbers(Caller, FirstNewBlock, TheCall);
00625   }
00626 
00627   // If there are any alloca instructions in the block that used to be the entry
00628   // block for the callee, move them to the entry block of the caller.  First
00629   // calculate which instruction they should be inserted before.  We insert the
00630   // instructions at the end of the current alloca list.
00631   {
00632     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
00633     for (BasicBlock::iterator I = FirstNewBlock->begin(),
00634          E = FirstNewBlock->end(); I != E; ) {
00635       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
00636       if (AI == 0) continue;
00637       
00638       // If the alloca is now dead, remove it.  This often occurs due to code
00639       // specialization.
00640       if (AI->use_empty()) {
00641         AI->eraseFromParent();
00642         continue;
00643       }
00644 
00645       if (!isa<Constant>(AI->getArraySize()))
00646         continue;
00647       
00648       // Keep track of the static allocas that we inline into the caller.
00649       IFI.StaticAllocas.push_back(AI);
00650       
00651       // Scan for the block of allocas that we can move over, and move them
00652       // all at once.
00653       while (isa<AllocaInst>(I) &&
00654              isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
00655         IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
00656         ++I;
00657       }
00658 
00659       // Transfer all of the allocas over in a block.  Using splice means
00660       // that the instructions aren't removed from the symbol table, then
00661       // reinserted.
00662       Caller->getEntryBlock().getInstList().splice(InsertPoint,
00663                                                    FirstNewBlock->getInstList(),
00664                                                    AI, I);
00665     }
00666   }
00667 
00668   // Leave lifetime markers for the static alloca's, scoping them to the
00669   // function we just inlined.
00670   if (InsertLifetime && !IFI.StaticAllocas.empty()) {
00671     IRBuilder<> builder(FirstNewBlock->begin());
00672     for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
00673       AllocaInst *AI = IFI.StaticAllocas[ai];
00674 
00675       // If the alloca is already scoped to something smaller than the whole
00676       // function then there's no need to add redundant, less accurate markers.
00677       if (hasLifetimeMarkers(AI))
00678         continue;
00679 
00680       // Try to determine the size of the allocation.
00681       ConstantInt *AllocaSize = 0;
00682       if (ConstantInt *AIArraySize =
00683           dyn_cast<ConstantInt>(AI->getArraySize())) {
00684         if (IFI.DL) {
00685           Type *AllocaType = AI->getAllocatedType();
00686           uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
00687           uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
00688           assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
00689           // Check that array size doesn't saturate uint64_t and doesn't
00690           // overflow when it's multiplied by type size.
00691           if (AllocaArraySize != ~0ULL &&
00692               UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
00693             AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
00694                                           AllocaArraySize * AllocaTypeSize);
00695           }
00696         }
00697       }
00698 
00699       builder.CreateLifetimeStart(AI, AllocaSize);
00700       for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
00701         IRBuilder<> builder(Returns[ri]);
00702         builder.CreateLifetimeEnd(AI, AllocaSize);
00703       }
00704     }
00705   }
00706 
00707   // If the inlined code contained dynamic alloca instructions, wrap the inlined
00708   // code with llvm.stacksave/llvm.stackrestore intrinsics.
00709   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
00710     Module *M = Caller->getParent();
00711     // Get the two intrinsics we care about.
00712     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
00713     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
00714 
00715     // Insert the llvm.stacksave.
00716     CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
00717       .CreateCall(StackSave, "savedstack");
00718 
00719     // Insert a call to llvm.stackrestore before any return instructions in the
00720     // inlined function.
00721     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00722       IRBuilder<>(Returns[i]).CreateCall(StackRestore, SavedPtr);
00723     }
00724   }
00725 
00726   // If we are inlining tail call instruction through a call site that isn't
00727   // marked 'tail', we must remove the tail marker for any calls in the inlined
00728   // code.  Also, calls inlined through a 'nounwind' call site should be marked
00729   // 'nounwind'.
00730   if (InlinedFunctionInfo.ContainsCalls &&
00731       (MustClearTailCallFlags || MarkNoUnwind)) {
00732     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00733          BB != E; ++BB)
00734       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00735         if (CallInst *CI = dyn_cast<CallInst>(I)) {
00736           if (MustClearTailCallFlags)
00737             CI->setTailCall(false);
00738           if (MarkNoUnwind)
00739             CI->setDoesNotThrow();
00740         }
00741   }
00742 
00743   // If we are inlining for an invoke instruction, we must make sure to rewrite
00744   // any call instructions into invoke instructions.
00745   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00746     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
00747 
00748   // If we cloned in _exactly one_ basic block, and if that block ends in a
00749   // return instruction, we splice the body of the inlined callee directly into
00750   // the calling basic block.
00751   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
00752     // Move all of the instructions right before the call.
00753     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
00754                                  FirstNewBlock->begin(), FirstNewBlock->end());
00755     // Remove the cloned basic block.
00756     Caller->getBasicBlockList().pop_back();
00757 
00758     // If the call site was an invoke instruction, add a branch to the normal
00759     // destination.
00760     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
00761       BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
00762       NewBr->setDebugLoc(Returns[0]->getDebugLoc());
00763     }
00764 
00765     // If the return instruction returned a value, replace uses of the call with
00766     // uses of the returned value.
00767     if (!TheCall->use_empty()) {
00768       ReturnInst *R = Returns[0];
00769       if (TheCall == R->getReturnValue())
00770         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
00771       else
00772         TheCall->replaceAllUsesWith(R->getReturnValue());
00773     }
00774     // Since we are now done with the Call/Invoke, we can delete it.
00775     TheCall->eraseFromParent();
00776 
00777     // Since we are now done with the return instruction, delete it also.
00778     Returns[0]->eraseFromParent();
00779 
00780     // We are now done with the inlining.
00781     return true;
00782   }
00783 
00784   // Otherwise, we have the normal case, of more than one block to inline or
00785   // multiple return sites.
00786 
00787   // We want to clone the entire callee function into the hole between the
00788   // "starter" and "ender" blocks.  How we accomplish this depends on whether
00789   // this is an invoke instruction or a call instruction.
00790   BasicBlock *AfterCallBB;
00791   BranchInst *CreatedBranchToNormalDest = NULL;
00792   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
00793 
00794     // Add an unconditional branch to make this look like the CallInst case...
00795     CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
00796 
00797     // Split the basic block.  This guarantees that no PHI nodes will have to be
00798     // updated due to new incoming edges, and make the invoke case more
00799     // symmetric to the call case.
00800     AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
00801                                           CalledFunc->getName()+".exit");
00802 
00803   } else {  // It's a call
00804     // If this is a call instruction, we need to split the basic block that
00805     // the call lives in.
00806     //
00807     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
00808                                           CalledFunc->getName()+".exit");
00809   }
00810 
00811   // Change the branch that used to go to AfterCallBB to branch to the first
00812   // basic block of the inlined function.
00813   //
00814   TerminatorInst *Br = OrigBB->getTerminator();
00815   assert(Br && Br->getOpcode() == Instruction::Br &&
00816          "splitBasicBlock broken!");
00817   Br->setOperand(0, FirstNewBlock);
00818 
00819 
00820   // Now that the function is correct, make it a little bit nicer.  In
00821   // particular, move the basic blocks inserted from the end of the function
00822   // into the space made by splitting the source basic block.
00823   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
00824                                      FirstNewBlock, Caller->end());
00825 
00826   // Handle all of the return instructions that we just cloned in, and eliminate
00827   // any users of the original call/invoke instruction.
00828   Type *RTy = CalledFunc->getReturnType();
00829 
00830   PHINode *PHI = 0;
00831   if (Returns.size() > 1) {
00832     // The PHI node should go at the front of the new basic block to merge all
00833     // possible incoming values.
00834     if (!TheCall->use_empty()) {
00835       PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
00836                             AfterCallBB->begin());
00837       // Anything that used the result of the function call should now use the
00838       // PHI node as their operand.
00839       TheCall->replaceAllUsesWith(PHI);
00840     }
00841 
00842     // Loop over all of the return instructions adding entries to the PHI node
00843     // as appropriate.
00844     if (PHI) {
00845       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00846         ReturnInst *RI = Returns[i];
00847         assert(RI->getReturnValue()->getType() == PHI->getType() &&
00848                "Ret value not consistent in function!");
00849         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
00850       }
00851     }
00852 
00853 
00854     // Add a branch to the merge points and remove return instructions.
00855     DebugLoc Loc;
00856     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00857       ReturnInst *RI = Returns[i];
00858       BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
00859       Loc = RI->getDebugLoc();
00860       BI->setDebugLoc(Loc);
00861       RI->eraseFromParent();
00862     }
00863     // We need to set the debug location to *somewhere* inside the
00864     // inlined function. The line number may be nonsensical, but the
00865     // instruction will at least be associated with the right
00866     // function.
00867     if (CreatedBranchToNormalDest)
00868       CreatedBranchToNormalDest->setDebugLoc(Loc);
00869   } else if (!Returns.empty()) {
00870     // Otherwise, if there is exactly one return value, just replace anything
00871     // using the return value of the call with the computed value.
00872     if (!TheCall->use_empty()) {
00873       if (TheCall == Returns[0]->getReturnValue())
00874         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
00875       else
00876         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
00877     }
00878 
00879     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
00880     BasicBlock *ReturnBB = Returns[0]->getParent();
00881     ReturnBB->replaceAllUsesWith(AfterCallBB);
00882 
00883     // Splice the code from the return block into the block that it will return
00884     // to, which contains the code that was after the call.
00885     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
00886                                       ReturnBB->getInstList());
00887 
00888     if (CreatedBranchToNormalDest)
00889       CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
00890 
00891     // Delete the return instruction now and empty ReturnBB now.
00892     Returns[0]->eraseFromParent();
00893     ReturnBB->eraseFromParent();
00894   } else if (!TheCall->use_empty()) {
00895     // No returns, but something is using the return value of the call.  Just
00896     // nuke the result.
00897     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
00898   }
00899 
00900   // Since we are now done with the Call/Invoke, we can delete it.
00901   TheCall->eraseFromParent();
00902 
00903   // We should always be able to fold the entry block of the function into the
00904   // single predecessor of the block...
00905   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
00906   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
00907 
00908   // Splice the code entry block into calling block, right before the
00909   // unconditional branch.
00910   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
00911   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
00912 
00913   // Remove the unconditional branch.
00914   OrigBB->getInstList().erase(Br);
00915 
00916   // Now we can remove the CalleeEntry block, which is now empty.
00917   Caller->getBasicBlockList().erase(CalleeEntry);
00918 
00919   // If we inserted a phi node, check to see if it has a single value (e.g. all
00920   // the entries are the same or undef).  If so, remove the PHI so it doesn't
00921   // block other optimizations.
00922   if (PHI) {
00923     if (Value *V = SimplifyInstruction(PHI, IFI.DL)) {
00924       PHI->replaceAllUsesWith(V);
00925       PHI->eraseFromParent();
00926     }
00927   }
00928 
00929   return true;
00930 }