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