1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements inlining of a function into a call site, resolving
11 // parameters and the return value as appropriate.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/Transforms/Utils/Local.h"
39 bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
40 bool InsertLifetime) {
41 return InlineFunction(CallSite(CI), IFI, InsertLifetime);
43 bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
44 bool InsertLifetime) {
45 return InlineFunction(CallSite(II), IFI, InsertLifetime);
49 /// A class for recording information about inlining through an invoke.
50 class InvokeInliningInfo {
51 BasicBlock *OuterResumeDest; ///< Destination of the invoke's unwind.
52 BasicBlock *InnerResumeDest; ///< Destination for the callee's resume.
53 LandingPadInst *CallerLPad; ///< LandingPadInst associated with the invoke.
54 PHINode *InnerEHValuesPHI; ///< PHI for EH values from landingpad insts.
55 SmallVector<Value*, 8> UnwindDestPHIValues;
58 InvokeInliningInfo(InvokeInst *II)
59 : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
60 CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
61 // If there are PHI nodes in the unwind destination block, we need to keep
62 // track of which values came into them from the invoke before removing
63 // the edge from this block.
64 llvm::BasicBlock *InvokeBB = II->getParent();
65 BasicBlock::iterator I = OuterResumeDest->begin();
66 for (; isa<PHINode>(I); ++I) {
67 // Save the value to use for this edge.
68 PHINode *PHI = cast<PHINode>(I);
69 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
72 CallerLPad = cast<LandingPadInst>(I);
75 /// getOuterResumeDest - The outer unwind destination is the target of
76 /// unwind edges introduced for calls within the inlined function.
77 BasicBlock *getOuterResumeDest() const {
78 return OuterResumeDest;
81 BasicBlock *getInnerResumeDest();
83 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
85 /// forwardResume - Forward the 'resume' instruction to the caller's landing
86 /// pad block. When the landing pad block has only one predecessor, this is
87 /// a simple branch. When there is more than one predecessor, we need to
88 /// split the landing pad block after the landingpad instruction and jump
90 void forwardResume(ResumeInst *RI,
91 SmallPtrSet<LandingPadInst*, 16> &InlinedLPads);
93 /// addIncomingPHIValuesFor - Add incoming-PHI values to the unwind
94 /// destination block for the given basic block, using the values for the
95 /// original invoke's source block.
96 void addIncomingPHIValuesFor(BasicBlock *BB) const {
97 addIncomingPHIValuesForInto(BB, OuterResumeDest);
100 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
101 BasicBlock::iterator I = dest->begin();
102 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
103 PHINode *phi = cast<PHINode>(I);
104 phi->addIncoming(UnwindDestPHIValues[i], src);
110 /// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
111 BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
112 if (InnerResumeDest) return InnerResumeDest;
114 // Split the landing pad.
115 BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
117 OuterResumeDest->splitBasicBlock(SplitPoint,
118 OuterResumeDest->getName() + ".body");
120 // The number of incoming edges we expect to the inner landing pad.
121 const unsigned PHICapacity = 2;
123 // Create corresponding new PHIs for all the PHIs in the outer landing pad.
124 BasicBlock::iterator InsertPoint = InnerResumeDest->begin();
125 BasicBlock::iterator I = OuterResumeDest->begin();
126 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
127 PHINode *OuterPHI = cast<PHINode>(I);
128 PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity,
129 OuterPHI->getName() + ".lpad-body",
131 OuterPHI->replaceAllUsesWith(InnerPHI);
132 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
135 // Create a PHI for the exception values.
136 InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity,
137 "eh.lpad-body", InsertPoint);
138 CallerLPad->replaceAllUsesWith(InnerEHValuesPHI);
139 InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest);
142 return InnerResumeDest;
145 /// forwardResume - Forward the 'resume' instruction to the caller's landing pad
146 /// block. When the landing pad block has only one predecessor, this is a simple
147 /// branch. When there is more than one predecessor, we need to split the
148 /// landing pad block after the landingpad instruction and jump to there.
149 void InvokeInliningInfo::forwardResume(ResumeInst *RI,
150 SmallPtrSet<LandingPadInst*, 16> &InlinedLPads) {
151 BasicBlock *Dest = getInnerResumeDest();
152 BasicBlock *Src = RI->getParent();
154 BranchInst::Create(Dest, Src);
156 // Update the PHIs in the destination. They were inserted in an order which
158 addIncomingPHIValuesForInto(Src, Dest);
160 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
161 RI->eraseFromParent();
164 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
165 /// an invoke, we have to turn all of the calls that can throw into
166 /// invokes. This function analyze BB to see if there are any calls, and if so,
167 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
168 /// nodes in that block with the values specified in InvokeDestPHIValues.
169 static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
170 InvokeInliningInfo &Invoke) {
171 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
172 Instruction *I = BBI++;
174 // We only need to check for function calls: inlined invoke
175 // instructions require no special handling.
176 CallInst *CI = dyn_cast<CallInst>(I);
178 // If this call cannot unwind, don't convert it to an invoke.
179 // Inline asm calls cannot throw.
180 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
183 // Convert this function call into an invoke instruction. First, split the
185 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
187 // Delete the unconditional branch inserted by splitBasicBlock
188 BB->getInstList().pop_back();
190 // Create the new invoke instruction.
191 ImmutableCallSite CS(CI);
192 SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
193 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
194 Invoke.getOuterResumeDest(),
195 InvokeArgs, CI->getName(), BB);
196 II->setDebugLoc(CI->getDebugLoc());
197 II->setCallingConv(CI->getCallingConv());
198 II->setAttributes(CI->getAttributes());
200 // Make sure that anything using the call now uses the invoke! This also
201 // updates the CallGraph if present, because it uses a WeakVH.
202 CI->replaceAllUsesWith(II);
204 // Delete the original call
205 Split->getInstList().pop_front();
207 // Update any PHI nodes in the exceptional block to indicate that there is
208 // now a new entry in them.
209 Invoke.addIncomingPHIValuesFor(BB);
214 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
215 /// in the body of the inlined function into invokes.
217 /// II is the invoke instruction being inlined. FirstNewBlock is the first
218 /// block of the inlined code (the last block is the end of the function),
219 /// and InlineCodeInfo is information about the code that got inlined.
220 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
221 ClonedCodeInfo &InlinedCodeInfo) {
222 BasicBlock *InvokeDest = II->getUnwindDest();
224 Function *Caller = FirstNewBlock->getParent();
226 // The inlined code is currently at the end of the function, scan from the
227 // start of the inlined code to its end, checking for stuff we need to
229 InvokeInliningInfo Invoke(II);
231 // Get all of the inlined landing pad instructions.
232 SmallPtrSet<LandingPadInst*, 16> InlinedLPads;
233 for (Function::iterator I = FirstNewBlock, E = Caller->end(); I != E; ++I)
234 if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator()))
235 InlinedLPads.insert(II->getLandingPadInst());
237 // Append the clauses from the outer landing pad instruction into the inlined
238 // landing pad instructions.
239 LandingPadInst *OuterLPad = Invoke.getLandingPadInst();
240 for (SmallPtrSet<LandingPadInst*, 16>::iterator I = InlinedLPads.begin(),
241 E = InlinedLPads.end(); I != E; ++I) {
242 LandingPadInst *InlinedLPad = *I;
243 unsigned OuterNum = OuterLPad->getNumClauses();
244 InlinedLPad->reserveClauses(OuterNum);
245 for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx)
246 InlinedLPad->addClause(OuterLPad->getClause(OuterIdx));
247 if (OuterLPad->isCleanup())
248 InlinedLPad->setCleanup(true);
251 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
252 if (InlinedCodeInfo.ContainsCalls)
253 HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
255 // Forward any resumes that are remaining here.
256 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
257 Invoke.forwardResume(RI, InlinedLPads);
260 // Now that everything is happy, we have one final detail. The PHI nodes in
261 // the exception destination block still have entries due to the original
262 // invoke instruction. Eliminate these entries (which might even delete the
264 InvokeDest->removePredecessor(II->getParent());
267 /// CloneAliasScopeMetadata - When inlining a function that contains noalias
268 /// scope metadata, this metadata needs to be cloned so that the inlined blocks
269 /// have different "unqiue scopes" at every call site. Were this not done, then
270 /// aliasing scopes from a function inlined into a caller multiple times could
271 /// not be differentiated (and this would lead to miscompiles because the
272 /// non-aliasing property communicated by the metadata could have
273 /// call-site-specific control dependencies).
274 static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
275 const Function *CalledFunc = CS.getCalledFunction();
276 SetVector<const MDNode *> MD;
278 // Note: We could only clone the metadata if it is already used in the
279 // caller. I'm omitting that check here because it might confuse
280 // inter-procedural alias analysis passes. We can revisit this if it becomes
281 // an efficiency or overhead problem.
283 for (Function::const_iterator I = CalledFunc->begin(), IE = CalledFunc->end();
285 for (BasicBlock::const_iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
286 if (const MDNode *M = J->getMetadata(LLVMContext::MD_alias_scope))
288 if (const MDNode *M = J->getMetadata(LLVMContext::MD_noalias))
295 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
297 SmallVector<const Value *, 16> Queue(MD.begin(), MD.end());
298 while (!Queue.empty()) {
299 const MDNode *M = cast<MDNode>(Queue.pop_back_val());
300 for (unsigned i = 0, ie = M->getNumOperands(); i != ie; ++i)
301 if (const MDNode *M1 = dyn_cast<MDNode>(M->getOperand(i)))
306 // Now we have a complete set of all metadata in the chains used to specify
307 // the noalias scopes and the lists of those scopes.
308 SmallVector<MDNode *, 16> DummyNodes;
309 DenseMap<const MDNode *, TrackingVH<MDNode> > MDMap;
310 for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
312 MDNode *Dummy = MDNode::getTemporary(CalledFunc->getContext(),
314 DummyNodes.push_back(Dummy);
318 // Create new metadata nodes to replace the dummy nodes, replacing old
319 // metadata references with either a dummy node or an already-created new
321 for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
323 SmallVector<Value *, 4> NewOps;
324 for (unsigned i = 0, ie = (*I)->getNumOperands(); i != ie; ++i) {
325 const Value *V = (*I)->getOperand(i);
326 if (const MDNode *M = dyn_cast<MDNode>(V))
327 NewOps.push_back(MDMap[M]);
329 NewOps.push_back(const_cast<Value *>(V));
332 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps),
335 TempM->replaceAllUsesWith(NewM);
338 // Now replace the metadata in the new inlined instructions with the
339 // repacements from the map.
340 for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end();
341 VMI != VMIE; ++VMI) {
345 Instruction *NI = dyn_cast<Instruction>(VMI->second);
349 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope))
350 NI->setMetadata(LLVMContext::MD_alias_scope, MDMap[M]);
352 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias))
353 NI->setMetadata(LLVMContext::MD_noalias, MDMap[M]);
356 // Now that everything has been replaced, delete the dummy nodes.
357 for (unsigned i = 0, ie = DummyNodes.size(); i != ie; ++i)
358 MDNode::deleteTemporary(DummyNodes[i]);
361 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
362 /// into the caller, update the specified callgraph to reflect the changes we
363 /// made. Note that it's possible that not all code was copied over, so only
364 /// some edges of the callgraph may remain.
365 static void UpdateCallGraphAfterInlining(CallSite CS,
366 Function::iterator FirstNewBlock,
367 ValueToValueMapTy &VMap,
368 InlineFunctionInfo &IFI) {
369 CallGraph &CG = *IFI.CG;
370 const Function *Caller = CS.getInstruction()->getParent()->getParent();
371 const Function *Callee = CS.getCalledFunction();
372 CallGraphNode *CalleeNode = CG[Callee];
373 CallGraphNode *CallerNode = CG[Caller];
375 // Since we inlined some uninlined call sites in the callee into the caller,
376 // add edges from the caller to all of the callees of the callee.
377 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
379 // Consider the case where CalleeNode == CallerNode.
380 CallGraphNode::CalledFunctionsVector CallCache;
381 if (CalleeNode == CallerNode) {
382 CallCache.assign(I, E);
383 I = CallCache.begin();
387 for (; I != E; ++I) {
388 const Value *OrigCall = I->first;
390 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
391 // Only copy the edge if the call was inlined!
392 if (VMI == VMap.end() || VMI->second == nullptr)
395 // If the call was inlined, but then constant folded, there is no edge to
396 // add. Check for this case.
397 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
398 if (!NewCall) continue;
400 // Remember that this call site got inlined for the client of
402 IFI.InlinedCalls.push_back(NewCall);
404 // It's possible that inlining the callsite will cause it to go from an
405 // indirect to a direct call by resolving a function pointer. If this
406 // happens, set the callee of the new call site to a more precise
407 // destination. This can also happen if the call graph node of the caller
408 // was just unnecessarily imprecise.
409 if (!I->second->getFunction())
410 if (Function *F = CallSite(NewCall).getCalledFunction()) {
411 // Indirect call site resolved to direct call.
412 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
417 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
420 // Update the call graph by deleting the edge from Callee to Caller. We must
421 // do this after the loop above in case Caller and Callee are the same.
422 CallerNode->removeCallEdgeFor(CS);
425 static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
426 BasicBlock *InsertBlock,
427 InlineFunctionInfo &IFI) {
428 LLVMContext &Context = Src->getContext();
429 Type *VoidPtrTy = Type::getInt8PtrTy(Context);
430 Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
431 Type *Tys[3] = { VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context) };
432 Function *MemCpyFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
433 IRBuilder<> builder(InsertBlock->begin());
434 Value *DstCast = builder.CreateBitCast(Dst, VoidPtrTy, "tmp");
435 Value *SrcCast = builder.CreateBitCast(Src, VoidPtrTy, "tmp");
438 if (IFI.DL == nullptr)
439 Size = ConstantExpr::getSizeOf(AggTy);
441 Size = ConstantInt::get(Type::getInt64Ty(Context),
442 IFI.DL->getTypeStoreSize(AggTy));
444 // Always generate a memcpy of alignment 1 here because we don't know
445 // the alignment of the src pointer. Other optimizations can infer
447 Value *CallArgs[] = {
448 DstCast, SrcCast, Size,
449 ConstantInt::get(Type::getInt32Ty(Context), 1),
450 ConstantInt::getFalse(Context) // isVolatile
452 builder.CreateCall(MemCpyFn, CallArgs);
455 /// HandleByValArgument - When inlining a call site that has a byval argument,
456 /// we have to make the implicit memcpy explicit by adding it.
457 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
458 const Function *CalledFunc,
459 InlineFunctionInfo &IFI,
460 unsigned ByValAlignment) {
461 PointerType *ArgTy = cast<PointerType>(Arg->getType());
462 Type *AggTy = ArgTy->getElementType();
464 // If the called function is readonly, then it could not mutate the caller's
465 // copy of the byval'd memory. In this case, it is safe to elide the copy and
467 if (CalledFunc->onlyReadsMemory()) {
468 // If the byval argument has a specified alignment that is greater than the
469 // passed in pointer, then we either have to round up the input pointer or
470 // give up on this transformation.
471 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
474 // If the pointer is already known to be sufficiently aligned, or if we can
475 // round it up to a larger alignment, then we don't need a temporary.
476 if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
477 IFI.DL) >= ByValAlignment)
480 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
481 // for code quality, but rarely happens and is required for correctness.
484 // Create the alloca. If we have DataLayout, use nice alignment.
487 Align = IFI.DL->getPrefTypeAlignment(AggTy);
489 // If the byval had an alignment specified, we *must* use at least that
490 // alignment, as it is required by the byval argument (and uses of the
491 // pointer inside the callee).
492 Align = std::max(Align, ByValAlignment);
494 Function *Caller = TheCall->getParent()->getParent();
496 Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(),
497 &*Caller->begin()->begin());
498 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
500 // Uses of the argument in the function should use our new alloca
505 // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
507 static bool isUsedByLifetimeMarker(Value *V) {
508 for (User *U : V->users()) {
509 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
510 switch (II->getIntrinsicID()) {
512 case Intrinsic::lifetime_start:
513 case Intrinsic::lifetime_end:
521 // hasLifetimeMarkers - Check whether the given alloca already has
522 // lifetime.start or lifetime.end intrinsics.
523 static bool hasLifetimeMarkers(AllocaInst *AI) {
524 Type *Ty = AI->getType();
525 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
526 Ty->getPointerAddressSpace());
528 return isUsedByLifetimeMarker(AI);
530 // Do a scan to find all the casts to i8*.
531 for (User *U : AI->users()) {
532 if (U->getType() != Int8PtrTy) continue;
533 if (U->stripPointerCasts() != AI) continue;
534 if (isUsedByLifetimeMarker(U))
540 /// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
541 /// recursively update InlinedAtEntry of a DebugLoc.
542 static DebugLoc updateInlinedAtInfo(const DebugLoc &DL,
543 const DebugLoc &InlinedAtDL,
545 if (MDNode *IA = DL.getInlinedAt(Ctx)) {
546 DebugLoc NewInlinedAtDL
547 = updateInlinedAtInfo(DebugLoc::getFromDILocation(IA), InlinedAtDL, Ctx);
548 return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
549 NewInlinedAtDL.getAsMDNode(Ctx));
552 return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
553 InlinedAtDL.getAsMDNode(Ctx));
556 /// fixupLineNumbers - Update inlined instructions' line numbers to
557 /// to encode location where these instructions are inlined.
558 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
559 Instruction *TheCall) {
560 DebugLoc TheCallDL = TheCall->getDebugLoc();
561 if (TheCallDL.isUnknown())
564 for (; FI != Fn->end(); ++FI) {
565 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
567 DebugLoc DL = BI->getDebugLoc();
568 if (DL.isUnknown()) {
569 // If the inlined instruction has no line number, make it look as if it
570 // originates from the call location. This is important for
571 // ((__always_inline__, __nodebug__)) functions which must use caller
572 // location for all instructions in their function body.
573 BI->setDebugLoc(TheCallDL);
575 BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
576 if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(BI)) {
577 LLVMContext &Ctx = BI->getContext();
578 MDNode *InlinedAt = BI->getDebugLoc().getInlinedAt(Ctx);
579 DVI->setOperand(2, createInlinedVariable(DVI->getVariable(),
587 /// Returns a musttail call instruction if one immediately precedes the given
588 /// return instruction with an optional bitcast instruction between them.
589 static CallInst *getPrecedingMustTailCall(ReturnInst *RI) {
590 Instruction *Prev = RI->getPrevNode();
594 if (Value *RV = RI->getReturnValue()) {
598 // Look through the optional bitcast.
599 if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
600 RV = BI->getOperand(0);
601 Prev = BI->getPrevNode();
602 if (!Prev || RV != Prev)
607 if (auto *CI = dyn_cast<CallInst>(Prev)) {
608 if (CI->isMustTailCall())
614 /// InlineFunction - This function inlines the called function into the basic
615 /// block of the caller. This returns false if it is not possible to inline
616 /// this call. The program is still in a well defined state if this occurs
619 /// Note that this only does one level of inlining. For example, if the
620 /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
621 /// exists in the instruction stream. Similarly this will inline a recursive
622 /// function by one level.
623 bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
624 bool InsertLifetime) {
625 Instruction *TheCall = CS.getInstruction();
626 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
627 "Instruction not in function!");
629 // If IFI has any state in it, zap it before we fill it in.
632 const Function *CalledFunc = CS.getCalledFunction();
633 if (!CalledFunc || // Can't inline external function or indirect
634 CalledFunc->isDeclaration() || // call, or call to a vararg function!
635 CalledFunc->getFunctionType()->isVarArg()) return false;
637 // If the call to the callee cannot throw, set the 'nounwind' flag on any
638 // calls that we inline.
639 bool MarkNoUnwind = CS.doesNotThrow();
641 BasicBlock *OrigBB = TheCall->getParent();
642 Function *Caller = OrigBB->getParent();
644 // GC poses two hazards to inlining, which only occur when the callee has GC:
645 // 1. If the caller has no GC, then the callee's GC must be propagated to the
647 // 2. If the caller has a differing GC, it is invalid to inline.
648 if (CalledFunc->hasGC()) {
649 if (!Caller->hasGC())
650 Caller->setGC(CalledFunc->getGC());
651 else if (CalledFunc->getGC() != Caller->getGC())
655 // Get the personality function from the callee if it contains a landing pad.
656 Value *CalleePersonality = nullptr;
657 for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
659 if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
660 const BasicBlock *BB = II->getUnwindDest();
661 const LandingPadInst *LP = BB->getLandingPadInst();
662 CalleePersonality = LP->getPersonalityFn();
666 // Find the personality function used by the landing pads of the caller. If it
667 // exists, then check to see that it matches the personality function used in
669 if (CalleePersonality) {
670 for (Function::const_iterator I = Caller->begin(), E = Caller->end();
672 if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
673 const BasicBlock *BB = II->getUnwindDest();
674 const LandingPadInst *LP = BB->getLandingPadInst();
676 // If the personality functions match, then we can perform the
677 // inlining. Otherwise, we can't inline.
678 // TODO: This isn't 100% true. Some personality functions are proper
679 // supersets of others and can be used in place of the other.
680 if (LP->getPersonalityFn() != CalleePersonality)
687 // Get an iterator to the last basic block in the function, which will have
688 // the new function inlined after it.
689 Function::iterator LastBlock = &Caller->back();
691 // Make sure to capture all of the return instructions from the cloned
693 SmallVector<ReturnInst*, 8> Returns;
694 ClonedCodeInfo InlinedFunctionInfo;
695 Function::iterator FirstNewBlock;
697 { // Scope to destroy VMap after cloning.
698 ValueToValueMapTy VMap;
699 // Keep a list of pair (dst, src) to emit byval initializations.
700 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
702 assert(CalledFunc->arg_size() == CS.arg_size() &&
703 "No varargs calls can be inlined!");
705 // Calculate the vector of arguments to pass into the function cloner, which
706 // matches up the formal to the actual argument values.
707 CallSite::arg_iterator AI = CS.arg_begin();
709 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
710 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
711 Value *ActualArg = *AI;
713 // When byval arguments actually inlined, we need to make the copy implied
714 // by them explicit. However, we don't do this if the callee is readonly
715 // or readnone, because the copy would be unneeded: the callee doesn't
716 // modify the struct.
717 if (CS.isByValArgument(ArgNo)) {
718 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
719 CalledFunc->getParamAlignment(ArgNo+1));
720 if (ActualArg != *AI)
721 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
727 // We want the inliner to prune the code as it copies. We would LOVE to
728 // have no dead or constant instructions leftover after inlining occurs
729 // (which can happen, e.g., because an argument was constant), but we'll be
730 // happy with whatever the cloner can do.
731 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
732 /*ModuleLevelChanges=*/false, Returns, ".i",
733 &InlinedFunctionInfo, IFI.DL, TheCall);
735 // Remember the first block that is newly cloned over.
736 FirstNewBlock = LastBlock; ++FirstNewBlock;
738 // Inject byval arguments initialization.
739 for (std::pair<Value*, Value*> &Init : ByValInit)
740 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
743 // Update the callgraph if requested.
745 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
747 // Update inlined instructions' line number information.
748 fixupLineNumbers(Caller, FirstNewBlock, TheCall);
750 // Clone existing noalias metadata if necessary.
751 CloneAliasScopeMetadata(CS, VMap);
754 // If there are any alloca instructions in the block that used to be the entry
755 // block for the callee, move them to the entry block of the caller. First
756 // calculate which instruction they should be inserted before. We insert the
757 // instructions at the end of the current alloca list.
759 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
760 for (BasicBlock::iterator I = FirstNewBlock->begin(),
761 E = FirstNewBlock->end(); I != E; ) {
762 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
765 // If the alloca is now dead, remove it. This often occurs due to code
767 if (AI->use_empty()) {
768 AI->eraseFromParent();
772 if (!isa<Constant>(AI->getArraySize()))
775 // Keep track of the static allocas that we inline into the caller.
776 IFI.StaticAllocas.push_back(AI);
778 // Scan for the block of allocas that we can move over, and move them
780 while (isa<AllocaInst>(I) &&
781 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
782 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
786 // Transfer all of the allocas over in a block. Using splice means
787 // that the instructions aren't removed from the symbol table, then
789 Caller->getEntryBlock().getInstList().splice(InsertPoint,
790 FirstNewBlock->getInstList(),
795 bool InlinedMustTailCalls = false;
796 if (InlinedFunctionInfo.ContainsCalls) {
797 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
798 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
799 CallSiteTailKind = CI->getTailCallKind();
801 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
803 for (Instruction &I : *BB) {
804 CallInst *CI = dyn_cast<CallInst>(&I);
808 // We need to reduce the strength of any inlined tail calls. For
809 // musttail, we have to avoid introducing potential unbounded stack
810 // growth. For example, if functions 'f' and 'g' are mutually recursive
811 // with musttail, we can inline 'g' into 'f' so long as we preserve
812 // musttail on the cloned call to 'f'. If either the inlined call site
813 // or the cloned call site is *not* musttail, the program already has
814 // one frame of stack growth, so it's safe to remove musttail. Here is
815 // a table of example transformations:
817 // f -> musttail g -> musttail f ==> f -> musttail f
818 // f -> musttail g -> tail f ==> f -> tail f
819 // f -> g -> musttail f ==> f -> f
820 // f -> g -> tail f ==> f -> f
821 CallInst::TailCallKind ChildTCK = CI->getTailCallKind();
822 ChildTCK = std::min(CallSiteTailKind, ChildTCK);
823 CI->setTailCallKind(ChildTCK);
824 InlinedMustTailCalls |= CI->isMustTailCall();
826 // Calls inlined through a 'nounwind' call site should be marked
829 CI->setDoesNotThrow();
834 // Leave lifetime markers for the static alloca's, scoping them to the
835 // function we just inlined.
836 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
837 IRBuilder<> builder(FirstNewBlock->begin());
838 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
839 AllocaInst *AI = IFI.StaticAllocas[ai];
841 // If the alloca is already scoped to something smaller than the whole
842 // function then there's no need to add redundant, less accurate markers.
843 if (hasLifetimeMarkers(AI))
846 // Try to determine the size of the allocation.
847 ConstantInt *AllocaSize = nullptr;
848 if (ConstantInt *AIArraySize =
849 dyn_cast<ConstantInt>(AI->getArraySize())) {
851 Type *AllocaType = AI->getAllocatedType();
852 uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
853 uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
854 assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
855 // Check that array size doesn't saturate uint64_t and doesn't
856 // overflow when it's multiplied by type size.
857 if (AllocaArraySize != ~0ULL &&
858 UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
859 AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
860 AllocaArraySize * AllocaTypeSize);
865 builder.CreateLifetimeStart(AI, AllocaSize);
866 for (ReturnInst *RI : Returns) {
867 // Don't insert llvm.lifetime.end calls between a musttail call and a
868 // return. The return kills all local allocas.
869 if (InlinedMustTailCalls && getPrecedingMustTailCall(RI))
871 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
876 // If the inlined code contained dynamic alloca instructions, wrap the inlined
877 // code with llvm.stacksave/llvm.stackrestore intrinsics.
878 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
879 Module *M = Caller->getParent();
880 // Get the two intrinsics we care about.
881 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
882 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
884 // Insert the llvm.stacksave.
885 CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
886 .CreateCall(StackSave, "savedstack");
888 // Insert a call to llvm.stackrestore before any return instructions in the
890 for (ReturnInst *RI : Returns) {
891 // Don't insert llvm.stackrestore calls between a musttail call and a
892 // return. The return will restore the stack pointer.
893 if (InlinedMustTailCalls && getPrecedingMustTailCall(RI))
895 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
899 // If we are inlining for an invoke instruction, we must make sure to rewrite
900 // any call instructions into invoke instructions.
901 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
902 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
904 // Handle any inlined musttail call sites. In order for a new call site to be
905 // musttail, the source of the clone and the inlined call site must have been
906 // musttail. Therefore it's safe to return without merging control into the
908 if (InlinedMustTailCalls) {
909 // Check if we need to bitcast the result of any musttail calls.
910 Type *NewRetTy = Caller->getReturnType();
911 bool NeedBitCast = !TheCall->use_empty() && TheCall->getType() != NewRetTy;
913 // Handle the returns preceded by musttail calls separately.
914 SmallVector<ReturnInst *, 8> NormalReturns;
915 for (ReturnInst *RI : Returns) {
916 CallInst *ReturnedMustTail = getPrecedingMustTailCall(RI);
917 if (!ReturnedMustTail) {
918 NormalReturns.push_back(RI);
924 // Delete the old return and any preceding bitcast.
925 BasicBlock *CurBB = RI->getParent();
926 auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue());
927 RI->eraseFromParent();
929 OldCast->eraseFromParent();
931 // Insert a new bitcast and return with the right type.
932 IRBuilder<> Builder(CurBB);
933 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
936 // Leave behind the normal returns so we can merge control flow.
937 std::swap(Returns, NormalReturns);
940 // If we cloned in _exactly one_ basic block, and if that block ends in a
941 // return instruction, we splice the body of the inlined callee directly into
942 // the calling basic block.
943 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
944 // Move all of the instructions right before the call.
945 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
946 FirstNewBlock->begin(), FirstNewBlock->end());
947 // Remove the cloned basic block.
948 Caller->getBasicBlockList().pop_back();
950 // If the call site was an invoke instruction, add a branch to the normal
952 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
953 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
954 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
957 // If the return instruction returned a value, replace uses of the call with
958 // uses of the returned value.
959 if (!TheCall->use_empty()) {
960 ReturnInst *R = Returns[0];
961 if (TheCall == R->getReturnValue())
962 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
964 TheCall->replaceAllUsesWith(R->getReturnValue());
966 // Since we are now done with the Call/Invoke, we can delete it.
967 TheCall->eraseFromParent();
969 // Since we are now done with the return instruction, delete it also.
970 Returns[0]->eraseFromParent();
972 // We are now done with the inlining.
976 // Otherwise, we have the normal case, of more than one block to inline or
977 // multiple return sites.
979 // We want to clone the entire callee function into the hole between the
980 // "starter" and "ender" blocks. How we accomplish this depends on whether
981 // this is an invoke instruction or a call instruction.
982 BasicBlock *AfterCallBB;
983 BranchInst *CreatedBranchToNormalDest = nullptr;
984 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
986 // Add an unconditional branch to make this look like the CallInst case...
987 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
989 // Split the basic block. This guarantees that no PHI nodes will have to be
990 // updated due to new incoming edges, and make the invoke case more
991 // symmetric to the call case.
992 AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
993 CalledFunc->getName()+".exit");
995 } else { // It's a call
996 // If this is a call instruction, we need to split the basic block that
997 // the call lives in.
999 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
1000 CalledFunc->getName()+".exit");
1003 // Change the branch that used to go to AfterCallBB to branch to the first
1004 // basic block of the inlined function.
1006 TerminatorInst *Br = OrigBB->getTerminator();
1007 assert(Br && Br->getOpcode() == Instruction::Br &&
1008 "splitBasicBlock broken!");
1009 Br->setOperand(0, FirstNewBlock);
1012 // Now that the function is correct, make it a little bit nicer. In
1013 // particular, move the basic blocks inserted from the end of the function
1014 // into the space made by splitting the source basic block.
1015 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
1016 FirstNewBlock, Caller->end());
1018 // Handle all of the return instructions that we just cloned in, and eliminate
1019 // any users of the original call/invoke instruction.
1020 Type *RTy = CalledFunc->getReturnType();
1022 PHINode *PHI = nullptr;
1023 if (Returns.size() > 1) {
1024 // The PHI node should go at the front of the new basic block to merge all
1025 // possible incoming values.
1026 if (!TheCall->use_empty()) {
1027 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
1028 AfterCallBB->begin());
1029 // Anything that used the result of the function call should now use the
1030 // PHI node as their operand.
1031 TheCall->replaceAllUsesWith(PHI);
1034 // Loop over all of the return instructions adding entries to the PHI node
1037 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
1038 ReturnInst *RI = Returns[i];
1039 assert(RI->getReturnValue()->getType() == PHI->getType() &&
1040 "Ret value not consistent in function!");
1041 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
1046 // Add a branch to the merge points and remove return instructions.
1048 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
1049 ReturnInst *RI = Returns[i];
1050 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
1051 Loc = RI->getDebugLoc();
1052 BI->setDebugLoc(Loc);
1053 RI->eraseFromParent();
1055 // We need to set the debug location to *somewhere* inside the
1056 // inlined function. The line number may be nonsensical, but the
1057 // instruction will at least be associated with the right
1059 if (CreatedBranchToNormalDest)
1060 CreatedBranchToNormalDest->setDebugLoc(Loc);
1061 } else if (!Returns.empty()) {
1062 // Otherwise, if there is exactly one return value, just replace anything
1063 // using the return value of the call with the computed value.
1064 if (!TheCall->use_empty()) {
1065 if (TheCall == Returns[0]->getReturnValue())
1066 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1068 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
1071 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
1072 BasicBlock *ReturnBB = Returns[0]->getParent();
1073 ReturnBB->replaceAllUsesWith(AfterCallBB);
1075 // Splice the code from the return block into the block that it will return
1076 // to, which contains the code that was after the call.
1077 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
1078 ReturnBB->getInstList());
1080 if (CreatedBranchToNormalDest)
1081 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
1083 // Delete the return instruction now and empty ReturnBB now.
1084 Returns[0]->eraseFromParent();
1085 ReturnBB->eraseFromParent();
1086 } else if (!TheCall->use_empty()) {
1087 // No returns, but something is using the return value of the call. Just
1089 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
1092 // Since we are now done with the Call/Invoke, we can delete it.
1093 TheCall->eraseFromParent();
1095 // If we inlined any musttail calls and the original return is now
1096 // unreachable, delete it. It can only contain a bitcast and ret.
1097 if (InlinedMustTailCalls && pred_begin(AfterCallBB) == pred_end(AfterCallBB))
1098 AfterCallBB->eraseFromParent();
1100 // We should always be able to fold the entry block of the function into the
1101 // single predecessor of the block...
1102 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
1103 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
1105 // Splice the code entry block into calling block, right before the
1106 // unconditional branch.
1107 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
1108 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
1110 // Remove the unconditional branch.
1111 OrigBB->getInstList().erase(Br);
1113 // Now we can remove the CalleeEntry block, which is now empty.
1114 Caller->getBasicBlockList().erase(CalleeEntry);
1116 // If we inserted a phi node, check to see if it has a single value (e.g. all
1117 // the entries are the same or undef). If so, remove the PHI so it doesn't
1118 // block other optimizations.
1120 if (Value *V = SimplifyInstruction(PHI, IFI.DL)) {
1121 PHI->replaceAllUsesWith(V);
1122 PHI->eraseFromParent();