blob: f4152dd490ac4dc5b80dcc9841c62966ff6513e0 [file] [log] [blame]
Chris Lattner530d4bf2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner530d4bf2003-05-29 15:11:31 +00009//
10// This file implements inlining of a function into a call site, resolving
11// parameters and the return value as appropriate.
12//
Chris Lattner530d4bf2003-05-29 15:11:31 +000013//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Cloning.h"
Hal Finkel94146652014-07-24 14:25:39 +000016#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallVector.h"
Hal Finkel94146652014-07-24 14:25:39 +000018#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/StringExtras.h"
20#include "llvm/Analysis/CallGraph.h"
21#include "llvm/Analysis/InstructionSimplify.h"
Hal Finkel94146652014-07-24 14:25:39 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Attributes.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000024#include "llvm/IR/CallSite.h"
Reid Klecknerf0915aa2014-05-15 20:11:28 +000025#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000028#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#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"
Hal Finkel94146652014-07-24 14:25:39 +000034#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Module.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000036#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000037using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000038
Eric Christopherf16bee82012-03-26 19:09:38 +000039bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
40 bool InsertLifetime) {
Chad Rosier07d37bc2012-02-25 02:56:01 +000041 return InlineFunction(CallSite(CI), IFI, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000042}
Eric Christopherf16bee82012-03-26 19:09:38 +000043bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
44 bool InsertLifetime) {
Chad Rosier07d37bc2012-02-25 02:56:01 +000045 return InlineFunction(CallSite(II), IFI, InsertLifetime);
Chris Lattner0841fb12006-01-14 20:07:50 +000046}
Chris Lattner0cc265e2003-08-24 06:59:16 +000047
John McCallbd04b742011-05-27 18:34:38 +000048namespace {
49 /// A class for recording information about inlining through an invoke.
50 class InvokeInliningInfo {
Dmitri Gribenkodbeafa72012-06-09 00:01:45 +000051 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.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000055 SmallVector<Value*, 8> UnwindDestPHIValues;
Bill Wendlingfa284402011-07-28 07:31:46 +000056
Bill Wendling55421f02011-08-14 08:01:36 +000057 public:
58 InvokeInliningInfo(InvokeInst *II)
Craig Topperf40110f2014-04-25 05:29:35 +000059 : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(nullptr),
60 CallerLPad(nullptr), InnerEHValuesPHI(nullptr) {
Bill Wendling55421f02011-08-14 08:01:36 +000061 // 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();
Bill Wendlingea6e9352012-01-31 01:25:54 +000065 BasicBlock::iterator I = OuterResumeDest->begin();
Bill Wendling55421f02011-08-14 08:01:36 +000066 for (; isa<PHINode>(I); ++I) {
John McCallbd04b742011-05-27 18:34:38 +000067 // Save the value to use for this edge.
Bill Wendling55421f02011-08-14 08:01:36 +000068 PHINode *PHI = cast<PHINode>(I);
69 UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB));
70 }
71
Bill Wendlingf3cae512012-01-31 00:56:53 +000072 CallerLPad = cast<LandingPadInst>(I);
John McCallbd04b742011-05-27 18:34:38 +000073 }
74
Bill Wendlingea6e9352012-01-31 01:25:54 +000075 /// getOuterResumeDest - The outer unwind destination is the target of
76 /// unwind edges introduced for calls within the inlined function.
Bill Wendling0c2d82b2012-01-31 01:22:03 +000077 BasicBlock *getOuterResumeDest() const {
Bill Wendlingea6e9352012-01-31 01:25:54 +000078 return OuterResumeDest;
John McCallbd04b742011-05-27 18:34:38 +000079 }
80
Bill Wendling3fd879d2012-01-31 01:48:40 +000081 BasicBlock *getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +000082
83 LandingPadInst *getLandingPadInst() const { return CallerLPad; }
84
Bill Wendling55421f02011-08-14 08:01:36 +000085 /// 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
89 /// to there.
Bill Wendling56f15bf2013-03-22 20:31:05 +000090 void forwardResume(ResumeInst *RI,
91 SmallPtrSet<LandingPadInst*, 16> &InlinedLPads);
Bill Wendling55421f02011-08-14 08:01:36 +000092
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.
John McCallbd04b742011-05-27 18:34:38 +000096 void addIncomingPHIValuesFor(BasicBlock *BB) const {
Bill Wendlingea6e9352012-01-31 01:25:54 +000097 addIncomingPHIValuesForInto(BB, OuterResumeDest);
John McCall046c47e2011-05-28 07:45:59 +000098 }
Bill Wendlingad088e62011-07-30 05:42:50 +000099
John McCall046c47e2011-05-28 07:45:59 +0000100 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
101 BasicBlock::iterator I = dest->begin();
John McCallbd04b742011-05-27 18:34:38 +0000102 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
Bill Wendlingad088e62011-07-30 05:42:50 +0000103 PHINode *phi = cast<PHINode>(I);
104 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCallbd04b742011-05-27 18:34:38 +0000105 }
106 }
107 };
108}
109
Bill Wendling3fd879d2012-01-31 01:48:40 +0000110/// getInnerResumeDest - Get or create a target for the branch from ResumeInsts.
111BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
Bill Wendling55421f02011-08-14 08:01:36 +0000112 if (InnerResumeDest) return InnerResumeDest;
113
114 // Split the landing pad.
115 BasicBlock::iterator SplitPoint = CallerLPad; ++SplitPoint;
116 InnerResumeDest =
117 OuterResumeDest->splitBasicBlock(SplitPoint,
118 OuterResumeDest->getName() + ".body");
119
120 // The number of incoming edges we expect to the inner landing pad.
121 const unsigned PHICapacity = 2;
122
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",
130 InsertPoint);
131 OuterPHI->replaceAllUsesWith(InnerPHI);
132 InnerPHI->addIncoming(OuterPHI, OuterResumeDest);
133 }
134
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);
140
141 // All done.
142 return InnerResumeDest;
143}
144
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.
Bill Wendling173c71f2013-03-21 23:30:12 +0000149void InvokeInliningInfo::forwardResume(ResumeInst *RI,
Bill Wendling56f15bf2013-03-22 20:31:05 +0000150 SmallPtrSet<LandingPadInst*, 16> &InlinedLPads) {
Bill Wendling3fd879d2012-01-31 01:48:40 +0000151 BasicBlock *Dest = getInnerResumeDest();
Bill Wendling55421f02011-08-14 08:01:36 +0000152 BasicBlock *Src = RI->getParent();
153
154 BranchInst::Create(Dest, Src);
155
156 // Update the PHIs in the destination. They were inserted in an order which
157 // makes this work.
158 addIncomingPHIValuesForInto(Src, Dest);
159
160 InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src);
161 RI->eraseFromParent();
162}
163
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000164/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
Eric Christopher66d8555f2009-09-06 22:20:54 +0000165/// an invoke, we have to turn all of the calls that can throw into
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000166/// 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
Chris Lattner8900f3e2009-09-01 18:44:06 +0000168/// nodes in that block with the values specified in InvokeDestPHIValues.
Mark Seabornd91fa222013-12-02 20:50:59 +0000169static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
John McCallbd04b742011-05-27 18:34:38 +0000170 InvokeInliningInfo &Invoke) {
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000171 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
172 Instruction *I = BBI++;
Bill Wendling55421f02011-08-14 08:01:36 +0000173
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000174 // We only need to check for function calls: inlined invoke
175 // instructions require no special handling.
176 CallInst *CI = dyn_cast<CallInst>(I);
John McCallbd04b742011-05-27 18:34:38 +0000177
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000178 // If this call cannot unwind, don't convert it to an invoke.
Manman Ren87a2adc2013-10-31 21:56:03 +0000179 // Inline asm calls cannot throw.
180 if (!CI || CI->doesNotThrow() || isa<InlineAsm>(CI->getCalledValue()))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000181 continue;
Bill Wendling518a2052012-01-31 01:05:20 +0000182
183 // Convert this function call into an invoke instruction. First, split the
184 // basic block.
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000185 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
John McCallbd04b742011-05-27 18:34:38 +0000186
John McCall046c47e2011-05-28 07:45:59 +0000187 // Delete the unconditional branch inserted by splitBasicBlock
188 BB->getInstList().pop_back();
John McCallbd04b742011-05-27 18:34:38 +0000189
Bill Wendling621699d2012-01-31 01:14:49 +0000190 // Create the new invoke instruction.
John McCall046c47e2011-05-28 07:45:59 +0000191 ImmutableCallSite CS(CI);
192 SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
Bill Wendlingce0c2292012-01-31 01:01:16 +0000193 InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split,
Bill Wendling0c2d82b2012-01-31 01:22:03 +0000194 Invoke.getOuterResumeDest(),
Bill Wendlingce0c2292012-01-31 01:01:16 +0000195 InvokeArgs, CI->getName(), BB);
David Blaikie644d2ee2014-06-30 20:30:39 +0000196 II->setDebugLoc(CI->getDebugLoc());
John McCall046c47e2011-05-28 07:45:59 +0000197 II->setCallingConv(CI->getCallingConv());
198 II->setAttributes(CI->getAttributes());
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000199
John McCall046c47e2011-05-28 07:45:59 +0000200 // 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);
John McCallbd04b742011-05-27 18:34:38 +0000203
Bill Wendlingce0c2292012-01-31 01:01:16 +0000204 // Delete the original call
205 Split->getInstList().pop_front();
John McCall046c47e2011-05-28 07:45:59 +0000206
Bill Wendlingce0c2292012-01-31 01:01:16 +0000207 // Update any PHI nodes in the exceptional block to indicate that there is
208 // now a new entry in them.
John McCallbd04b742011-05-27 18:34:38 +0000209 Invoke.addIncomingPHIValuesFor(BB);
Mark Seabornd91fa222013-12-02 20:50:59 +0000210 return;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000211 }
212}
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000213
Chris Lattner908d7952006-01-13 19:05:59 +0000214/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
Bill Wendling0aef16a2012-02-06 21:44:22 +0000215/// in the body of the inlined function into invokes.
Chris Lattner908d7952006-01-13 19:05:59 +0000216///
Nick Lewycky12a130b2009-02-03 04:34:40 +0000217/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattner908d7952006-01-13 19:05:59 +0000218/// 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.
220static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
Chris Lattner8900f3e2009-09-01 18:44:06 +0000221 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattner908d7952006-01-13 19:05:59 +0000222 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner908d7952006-01-13 19:05:59 +0000223
224 Function *Caller = FirstNewBlock->getParent();
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000225
Chris Lattner908d7952006-01-13 19:05:59 +0000226 // 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
Bill Wendling173c71f2013-03-21 23:30:12 +0000228 // rewrite.
John McCallbd04b742011-05-27 18:34:38 +0000229 InvokeInliningInfo Invoke(II);
Bill Wendling173c71f2013-03-21 23:30:12 +0000230
Bill Wendling56f15bf2013-03-22 20:31:05 +0000231 // 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());
236
Mark Seabornef3dbb92013-12-08 00:50:58 +0000237 // 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));
Mark Seaborn1b3dd352013-12-08 00:51:21 +0000247 if (OuterLPad->isCleanup())
248 InlinedLPad->setCleanup(true);
Mark Seabornef3dbb92013-12-08 00:50:58 +0000249 }
250
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000251 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
252 if (InlinedCodeInfo.ContainsCalls)
Mark Seabornd91fa222013-12-02 20:50:59 +0000253 HandleCallsInBlockInlinedThroughInvoke(BB, Invoke);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000254
Bill Wendling173c71f2013-03-21 23:30:12 +0000255 // Forward any resumes that are remaining here.
Bill Wendling621699d2012-01-31 01:14:49 +0000256 if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator()))
Bill Wendling56f15bf2013-03-22 20:31:05 +0000257 Invoke.forwardResume(RI, InlinedLPads);
Chris Lattner908d7952006-01-13 19:05:59 +0000258 }
259
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
Bill Wendling173c71f2013-03-21 23:30:12 +0000262 // invoke instruction. Eliminate these entries (which might even delete the
Chris Lattner908d7952006-01-13 19:05:59 +0000263 // PHI node) now.
264 InvokeDest->removePredecessor(II->getParent());
265}
266
Hal Finkel94146652014-07-24 14:25:39 +0000267/// 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).
274static void CloneAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap) {
275 const Function *CalledFunc = CS.getCalledFunction();
276 SetVector<const MDNode *> MD;
277
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.
282
283 for (Function::const_iterator I = CalledFunc->begin(), IE = CalledFunc->end();
284 I != IE; ++I)
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))
287 MD.insert(M);
288 if (const MDNode *M = J->getMetadata(LLVMContext::MD_noalias))
289 MD.insert(M);
290 }
291
292 if (MD.empty())
293 return;
294
295 // Walk the existing metadata, adding the complete (perhaps cyclic) chain to
296 // the set.
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)))
302 if (MD.insert(M1))
303 Queue.push_back(M1);
304 }
305
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();
311 I != IE; ++I) {
312 MDNode *Dummy = MDNode::getTemporary(CalledFunc->getContext(),
313 ArrayRef<Value*>());
314 DummyNodes.push_back(Dummy);
315 MDMap[*I] = Dummy;
316 }
317
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
320 // node.
321 for (SetVector<const MDNode *>::iterator I = MD.begin(), IE = MD.end();
322 I != IE; ++I) {
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]);
328 else
329 NewOps.push_back(const_cast<Value *>(V));
330 }
331
332 MDNode *NewM = MDNode::get(CalledFunc->getContext(), NewOps),
333 *TempM = MDMap[*I];
334
335 TempM->replaceAllUsesWith(NewM);
336 }
337
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) {
342 if (!VMI->second)
343 continue;
344
345 Instruction *NI = dyn_cast<Instruction>(VMI->second);
346 if (!NI)
347 continue;
348
349 if (MDNode *M = NI->getMetadata(LLVMContext::MD_alias_scope))
350 NI->setMetadata(LLVMContext::MD_alias_scope, MDMap[M]);
351
352 if (MDNode *M = NI->getMetadata(LLVMContext::MD_noalias))
353 NI->setMetadata(LLVMContext::MD_noalias, MDMap[M]);
354 }
355
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]);
359}
360
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000361/// 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
Duncan Sands46911f12008-09-08 11:05:51 +0000364/// some edges of the callgraph may remain.
365static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000366 Function::iterator FirstNewBlock,
Rafael Espindola229e38f2010-10-13 01:36:30 +0000367 ValueToValueMapTy &VMap,
Chris Lattner2eee5d32010-04-22 23:37:35 +0000368 InlineFunctionInfo &IFI) {
369 CallGraph &CG = *IFI.CG;
Duncan Sands46911f12008-09-08 11:05:51 +0000370 const Function *Caller = CS.getInstruction()->getParent()->getParent();
371 const Function *Callee = CS.getCalledFunction();
Chris Lattner0841fb12006-01-14 20:07:50 +0000372 CallGraphNode *CalleeNode = CG[Callee];
373 CallGraphNode *CallerNode = CG[Caller];
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000374
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000375 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner0841fb12006-01-14 20:07:50 +0000376 // add edges from the caller to all of the callees of the callee.
Gabor Greif5aa19222009-01-15 18:40:09 +0000377 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
378
379 // Consider the case where CalleeNode == CallerNode.
Gabor Greiff1abfdc2009-01-17 00:09:08 +0000380 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greif5aa19222009-01-15 18:40:09 +0000381 if (CalleeNode == CallerNode) {
382 CallCache.assign(I, E);
383 I = CallCache.begin();
384 E = CallCache.end();
385 }
386
387 for (; I != E; ++I) {
Chris Lattner063d0652009-09-01 06:31:31 +0000388 const Value *OrigCall = I->first;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000389
Rafael Espindola229e38f2010-10-13 01:36:30 +0000390 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattnerb3c64f72006-07-12 21:37:11 +0000391 // Only copy the edge if the call was inlined!
Craig Topperf40110f2014-04-25 05:29:35 +0000392 if (VMI == VMap.end() || VMI->second == nullptr)
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000393 continue;
394
395 // If the call was inlined, but then constant folded, there is no edge to
396 // add. Check for this case.
Chris Lattner016c00a2010-04-22 21:31:00 +0000397 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
Craig Topperf40110f2014-04-25 05:29:35 +0000398 if (!NewCall) continue;
Chris Lattnerc2432b92010-05-01 01:26:13 +0000399
400 // Remember that this call site got inlined for the client of
401 // InlineFunction.
402 IFI.InlinedCalls.push_back(NewCall);
403
Chris Lattner016c00a2010-04-22 21:31:00 +0000404 // 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.
Craig Topperf40110f2014-04-25 05:29:35 +0000409 if (!I->second->getFunction())
Chris Lattner016c00a2010-04-22 21:31:00 +0000410 if (Function *F = CallSite(NewCall).getCalledFunction()) {
411 // Indirect call site resolved to direct call.
Gabor Greif7b0a5fd2010-07-27 15:02:37 +0000412 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
413
Chris Lattner016c00a2010-04-22 21:31:00 +0000414 continue;
415 }
Gabor Greif7b0a5fd2010-07-27 15:02:37 +0000416
417 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000418 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000419
Dale Johannesen0aeabdf2009-01-13 22:43:37 +0000420 // 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);
Chris Lattner0841fb12006-01-14 20:07:50 +0000423}
424
Julien Lerouge957e91c2014-04-15 18:01:54 +0000425static 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");
436
437 Value *Size;
Craig Topperf40110f2014-04-25 05:29:35 +0000438 if (IFI.DL == nullptr)
Julien Lerouge957e91c2014-04-15 18:01:54 +0000439 Size = ConstantExpr::getSizeOf(AggTy);
440 else
441 Size = ConstantInt::get(Type::getInt64Ty(Context),
442 IFI.DL->getTypeStoreSize(AggTy));
443
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
446 // better alignment.
447 Value *CallArgs[] = {
448 DstCast, SrcCast, Size,
449 ConstantInt::get(Type::getInt32Ty(Context), 1),
450 ConstantInt::getFalse(Context) // isVolatile
451 };
452 builder.CreateCall(MemCpyFn, CallArgs);
453}
454
Chris Lattner0f114952010-12-20 08:10:40 +0000455/// HandleByValArgument - When inlining a call site that has a byval argument,
456/// we have to make the implicit memcpy explicit by adding it.
David Majnemer120f4a02013-11-03 12:22:13 +0000457static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
Chris Lattner00997442010-12-20 07:57:41 +0000458 const Function *CalledFunc,
459 InlineFunctionInfo &IFI,
460 unsigned ByValAlignment) {
Matt Arsenaultbe558882014-04-23 20:58:57 +0000461 PointerType *ArgTy = cast<PointerType>(Arg->getType());
462 Type *AggTy = ArgTy->getElementType();
Chris Lattner0f114952010-12-20 08:10:40 +0000463
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
466 // temporary.
David Majnemer120f4a02013-11-03 12:22:13 +0000467 if (CalledFunc->onlyReadsMemory()) {
Chris Lattner0f114952010-12-20 08:10:40 +0000468 // 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.
David Majnemer120f4a02013-11-03 12:22:13 +0000472 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +0000473
Chris Lattner20fca482010-12-25 20:42:38 +0000474 // 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.
David Majnemer120f4a02013-11-03 12:22:13 +0000476 if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000477 IFI.DL) >= ByValAlignment)
David Majnemer120f4a02013-11-03 12:22:13 +0000478 return Arg;
Chris Lattner0f114952010-12-20 08:10:40 +0000479
Chris Lattner20fca482010-12-25 20:42:38 +0000480 // 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.
Chris Lattner0f114952010-12-20 08:10:40 +0000482 }
Chris Lattner00997442010-12-20 07:57:41 +0000483
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000484 // Create the alloca. If we have DataLayout, use nice alignment.
Chris Lattner00997442010-12-20 07:57:41 +0000485 unsigned Align = 1;
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000486 if (IFI.DL)
487 Align = IFI.DL->getPrefTypeAlignment(AggTy);
Chris Lattner00997442010-12-20 07:57:41 +0000488
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);
493
494 Function *Caller = TheCall->getParent()->getParent();
495
Craig Topperf40110f2014-04-25 05:29:35 +0000496 Value *NewAlloca = new AllocaInst(AggTy, nullptr, Align, Arg->getName(),
Chris Lattner00997442010-12-20 07:57:41 +0000497 &*Caller->begin()->begin());
Julien Lerougebe4fe322014-04-15 18:06:46 +0000498 IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca));
Chris Lattner00997442010-12-20 07:57:41 +0000499
500 // Uses of the argument in the function should use our new alloca
501 // instead.
502 return NewAlloca;
503}
504
Nick Lewyckya68ec832011-05-22 05:22:10 +0000505// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
506// intrinsic.
507static bool isUsedByLifetimeMarker(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000508 for (User *U : V->users()) {
509 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckya68ec832011-05-22 05:22:10 +0000510 switch (II->getIntrinsicID()) {
511 default: break;
512 case Intrinsic::lifetime_start:
513 case Intrinsic::lifetime_end:
514 return true;
515 }
516 }
517 }
518 return false;
519}
520
521// hasLifetimeMarkers - Check whether the given alloca already has
522// lifetime.start or lifetime.end intrinsics.
523static bool hasLifetimeMarkers(AllocaInst *AI) {
Matt Arsenaultbe558882014-04-23 20:58:57 +0000524 Type *Ty = AI->getType();
525 Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(),
526 Ty->getPointerAddressSpace());
527 if (Ty == Int8PtrTy)
Nick Lewyckya68ec832011-05-22 05:22:10 +0000528 return isUsedByLifetimeMarker(AI);
529
Nick Lewycky9711b5c2011-06-14 00:59:24 +0000530 // Do a scan to find all the casts to i8*.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000531 for (User *U : AI->users()) {
532 if (U->getType() != Int8PtrTy) continue;
533 if (U->stripPointerCasts() != AI) continue;
534 if (isUsedByLifetimeMarker(U))
Nick Lewyckya68ec832011-05-22 05:22:10 +0000535 return true;
536 }
537 return false;
538}
539
Eric Christopherf16bee82012-03-26 19:09:38 +0000540/// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
541/// recursively update InlinedAtEntry of a DebugLoc.
Devang Patel35797402011-07-08 18:01:31 +0000542static DebugLoc updateInlinedAtInfo(const DebugLoc &DL,
543 const DebugLoc &InlinedAtDL,
544 LLVMContext &Ctx) {
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));
550 }
Eric Christopherf16bee82012-03-26 19:09:38 +0000551
Devang Patel35797402011-07-08 18:01:31 +0000552 return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
553 InlinedAtDL.getAsMDNode(Ctx));
554}
555
Devang Patel35797402011-07-08 18:01:31 +0000556/// fixupLineNumbers - Update inlined instructions' line numbers to
557/// to encode location where these instructions are inlined.
558static void fixupLineNumbers(Function *Fn, Function::iterator FI,
Eric Christopher2b40fdf2012-03-26 19:09:40 +0000559 Instruction *TheCall) {
Devang Patel35797402011-07-08 18:01:31 +0000560 DebugLoc TheCallDL = TheCall->getDebugLoc();
561 if (TheCallDL.isUnknown())
562 return;
563
564 for (; FI != Fn->end(); ++FI) {
565 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
566 BI != BE; ++BI) {
567 DebugLoc DL = BI->getDebugLoc();
Evgeniy Stepanov2be29922014-06-09 09:09:19 +0000568 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);
574 } else {
Devang Patel35797402011-07-08 18:01:31 +0000575 BI->setDebugLoc(updateInlinedAtInfo(DL, TheCallDL, BI->getContext()));
Devang Patelbb23a4a2011-08-10 21:50:54 +0000576 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(),
580 InlinedAt, Ctx));
581 }
582 }
Devang Patel35797402011-07-08 18:01:31 +0000583 }
584 }
585}
586
Reid Klecknerf0915aa2014-05-15 20:11:28 +0000587/// Returns a musttail call instruction if one immediately precedes the given
588/// return instruction with an optional bitcast instruction between them.
589static CallInst *getPrecedingMustTailCall(ReturnInst *RI) {
590 Instruction *Prev = RI->getPrevNode();
591 if (!Prev)
592 return nullptr;
593
594 if (Value *RV = RI->getReturnValue()) {
595 if (RV != Prev)
596 return nullptr;
597
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)
603 return nullptr;
604 }
605 }
606
607 if (auto *CI = dyn_cast<CallInst>(Prev)) {
608 if (CI->isMustTailCall())
609 return CI;
610 }
611 return nullptr;
612}
613
Bill Wendlingce0c2292012-01-31 01:01:16 +0000614/// 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
617/// though.
618///
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.
Eric Christopherf16bee82012-03-26 19:09:38 +0000623bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
624 bool InsertLifetime) {
Chris Lattner0cc265e2003-08-24 06:59:16 +0000625 Instruction *TheCall = CS.getInstruction();
626 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
627 "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +0000628
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000629 // If IFI has any state in it, zap it before we fill it in.
630 IFI.reset();
631
Chris Lattner0cc265e2003-08-24 06:59:16 +0000632 const Function *CalledFunc = CS.getCalledFunction();
Craig Topperf40110f2014-04-25 05:29:35 +0000633 if (!CalledFunc || // Can't inline external function or indirect
Reid Spencer5301e7c2007-01-30 20:08:39 +0000634 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher1d385382010-03-24 23:35:21 +0000635 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattner530d4bf2003-05-29 15:11:31 +0000636
Duncan Sandsaa31b922007-12-19 21:13:37 +0000637 // If the call to the callee cannot throw, set the 'nounwind' flag on any
638 // calls that we inline.
639 bool MarkNoUnwind = CS.doesNotThrow();
640
Chris Lattner0cc265e2003-08-24 06:59:16 +0000641 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +0000642 Function *Caller = OrigBB->getParent();
643
Gordon Henriksenb969c592007-12-25 03:10:07 +0000644 // 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
646 // caller.
647 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksend930f912008-08-17 18:44:35 +0000648 if (CalledFunc->hasGC()) {
649 if (!Caller->hasGC())
650 Caller->setGC(CalledFunc->getGC());
651 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksenb969c592007-12-25 03:10:07 +0000652 return false;
653 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000654
Benjamin Kramer4d2b8712011-12-02 18:37:31 +0000655 // Get the personality function from the callee if it contains a landing pad.
Craig Topperf40110f2014-04-25 05:29:35 +0000656 Value *CalleePersonality = nullptr;
Benjamin Kramer4d2b8712011-12-02 18:37:31 +0000657 for (Function::const_iterator I = CalledFunc->begin(), E = CalledFunc->end();
658 I != E; ++I)
659 if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
660 const BasicBlock *BB = II->getUnwindDest();
Bill Wendlingf3cae512012-01-31 00:56:53 +0000661 const LandingPadInst *LP = BB->getLandingPadInst();
662 CalleePersonality = LP->getPersonalityFn();
Benjamin Kramer4d2b8712011-12-02 18:37:31 +0000663 break;
664 }
665
Bill Wendling55421f02011-08-14 08:01:36 +0000666 // 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
668 // the callee.
Bill Wendlingce0c2292012-01-31 01:01:16 +0000669 if (CalleePersonality) {
Benjamin Kramer4d2b8712011-12-02 18:37:31 +0000670 for (Function::const_iterator I = Caller->begin(), E = Caller->end();
671 I != E; ++I)
672 if (const InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
673 const BasicBlock *BB = II->getUnwindDest();
Bill Wendlingf3cae512012-01-31 00:56:53 +0000674 const LandingPadInst *LP = BB->getLandingPadInst();
Bill Wendling55421f02011-08-14 08:01:36 +0000675
Benjamin Kramer4d2b8712011-12-02 18:37:31 +0000676 // 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)
681 return false;
Bill Wendling55421f02011-08-14 08:01:36 +0000682
Benjamin Kramer4d2b8712011-12-02 18:37:31 +0000683 break;
684 }
Bill Wendlingce0c2292012-01-31 01:01:16 +0000685 }
Bill Wendling55421f02011-08-14 08:01:36 +0000686
Chris Lattner9fc977e2004-02-04 01:41:09 +0000687 // Get an iterator to the last basic block in the function, which will have
688 // the new function inlined after it.
Chris Lattner9fc977e2004-02-04 01:41:09 +0000689 Function::iterator LastBlock = &Caller->back();
690
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000691 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +0000692 // function.
Chris Lattnerd84dbb32009-08-27 04:02:30 +0000693 SmallVector<ReturnInst*, 8> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +0000694 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen845e5822009-03-04 02:09:48 +0000695 Function::iterator FirstNewBlock;
Duncan Sandsaa31b922007-12-19 21:13:37 +0000696
Devang Patelb8f11de2010-06-23 23:55:51 +0000697 { // Scope to destroy VMap after cloning.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000698 ValueToValueMapTy VMap;
Julien Lerouge957e91c2014-04-15 18:01:54 +0000699 // Keep a list of pair (dst, src) to emit byval initializations.
700 SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
Chris Lattnerbe853d72006-05-27 01:28:04 +0000701
Dan Gohman3ada1e12008-06-20 17:11:32 +0000702 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000703 "No varargs calls can be inlined!");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000704
Chris Lattner908117b2008-01-11 06:09:30 +0000705 // Calculate the vector of arguments to pass into the function cloner, which
706 // matches up the formal to the actual argument values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000707 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner908117b2008-01-11 06:09:30 +0000708 unsigned ArgNo = 0;
Chris Lattner531f9e92005-03-15 04:54:21 +0000709 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattner908117b2008-01-11 06:09:30 +0000710 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
711 Value *ActualArg = *AI;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000712
Duncan Sands053c9872008-01-27 18:12:58 +0000713 // 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.
Nick Lewycky612d70b2011-11-20 19:09:04 +0000717 if (CS.isByValArgument(ArgNo)) {
David Majnemer120f4a02013-11-03 12:22:13 +0000718 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
Chris Lattner00997442010-12-20 07:57:41 +0000719 CalledFunc->getParamAlignment(ArgNo+1));
Reid Kleckner9b2cc642014-04-21 20:48:47 +0000720 if (ActualArg != *AI)
Julien Lerouge957e91c2014-04-15 18:01:54 +0000721 ByValInit.push_back(std::make_pair(ActualArg, (Value*) *AI));
Chris Lattner908117b2008-01-11 06:09:30 +0000722 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000723
Devang Patelb8f11de2010-06-23 23:55:51 +0000724 VMap[I] = ActualArg;
Chris Lattner908117b2008-01-11 06:09:30 +0000725 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000726
Chris Lattnerbe853d72006-05-27 01:28:04 +0000727 // 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.
Dan Gohmanca26f792010-08-26 15:41:53 +0000731 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
732 /*ModuleLevelChanges=*/false, Returns, ".i",
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000733 &InlinedFunctionInfo, IFI.DL, TheCall);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000734
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000735 // Remember the first block that is newly cloned over.
736 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000737
Julien Lerouge957e91c2014-04-15 18:01:54 +0000738 // Inject byval arguments initialization.
739 for (std::pair<Value*, Value*> &Init : ByValInit)
740 HandleByValArgumentInit(Init.first, Init.second, Caller->getParent(),
741 FirstNewBlock, IFI);
742
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000743 // Update the callgraph if requested.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000744 if (IFI.CG)
Devang Patelb8f11de2010-06-23 23:55:51 +0000745 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Devang Patel35797402011-07-08 18:01:31 +0000746
747 // Update inlined instructions' line number information.
748 fixupLineNumbers(Caller, FirstNewBlock, TheCall);
Hal Finkel94146652014-07-24 14:25:39 +0000749
750 // Clone existing noalias metadata if necessary.
751 CloneAliasScopeMetadata(CS, VMap);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000752 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000753
Chris Lattner530d4bf2003-05-29 15:11:31 +0000754 // 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.
Chris Lattner257492c2006-01-13 18:16:48 +0000758 {
Chris Lattner0cc265e2003-08-24 06:59:16 +0000759 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000760 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000761 E = FirstNewBlock->end(); I != E; ) {
762 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
Craig Topperf40110f2014-04-25 05:29:35 +0000763 if (!AI) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000764
765 // If the alloca is now dead, remove it. This often occurs due to code
766 // specialization.
767 if (AI->use_empty()) {
768 AI->eraseFromParent();
769 continue;
Chris Lattner6ef6d062006-09-13 19:23:57 +0000770 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000771
772 if (!isa<Constant>(AI->getArraySize()))
773 continue;
774
Chris Lattnercd3af962010-12-06 07:43:04 +0000775 // Keep track of the static allocas that we inline into the caller.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000776 IFI.StaticAllocas.push_back(AI);
Chris Lattnerb1cba3f2009-08-27 04:20:52 +0000777
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000778 // Scan for the block of allocas that we can move over, and move them
779 // all at once.
780 while (isa<AllocaInst>(I) &&
Chris Lattnerb1cba3f2009-08-27 04:20:52 +0000781 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000782 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000783 ++I;
Chris Lattnerb1cba3f2009-08-27 04:20:52 +0000784 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000785
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
788 // reinserted.
789 Caller->getEntryBlock().getInstList().splice(InsertPoint,
790 FirstNewBlock->getInstList(),
791 AI, I);
792 }
Chris Lattner0cc265e2003-08-24 06:59:16 +0000793 }
Chris Lattner530d4bf2003-05-29 15:11:31 +0000794
Reid Klecknerf0915aa2014-05-15 20:11:28 +0000795 bool InlinedMustTailCalls = false;
796 if (InlinedFunctionInfo.ContainsCalls) {
Reid Kleckner6af21242014-05-15 20:39:42 +0000797 CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None;
798 if (CallInst *CI = dyn_cast<CallInst>(TheCall))
799 CallSiteTailKind = CI->getTailCallKind();
800
Reid Klecknerf0915aa2014-05-15 20:11:28 +0000801 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E;
802 ++BB) {
803 for (Instruction &I : *BB) {
804 CallInst *CI = dyn_cast<CallInst>(&I);
805 if (!CI)
806 continue;
807
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:
816 //
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();
825
826 // Calls inlined through a 'nounwind' call site should be marked
827 // 'nounwind'.
828 if (MarkNoUnwind)
829 CI->setDoesNotThrow();
830 }
831 }
832 }
833
Nick Lewyckya68ec832011-05-22 05:22:10 +0000834 // Leave lifetime markers for the static alloca's, scoping them to the
835 // function we just inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +0000836 if (InsertLifetime && !IFI.StaticAllocas.empty()) {
Nick Lewyckya68ec832011-05-22 05:22:10 +0000837 IRBuilder<> builder(FirstNewBlock->begin());
838 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
839 AllocaInst *AI = IFI.StaticAllocas[ai];
840
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))
844 continue;
845
Alexey Samsonovcfd662f2012-11-13 07:15:32 +0000846 // Try to determine the size of the allocation.
Craig Topperf40110f2014-04-25 05:29:35 +0000847 ConstantInt *AllocaSize = nullptr;
Alexey Samsonovcfd662f2012-11-13 07:15:32 +0000848 if (ConstantInt *AIArraySize =
849 dyn_cast<ConstantInt>(AI->getArraySize())) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000850 if (IFI.DL) {
Alexey Samsonovcfd662f2012-11-13 07:15:32 +0000851 Type *AllocaType = AI->getAllocatedType();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000852 uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType);
Alexey Samsonovcfd662f2012-11-13 07:15:32 +0000853 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);
861 }
862 }
863 }
864
865 builder.CreateLifetimeStart(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +0000866 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))
870 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +0000871 IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize);
Reid Kleckner900d46f2014-05-15 21:10:46 +0000872 }
Nick Lewyckya68ec832011-05-22 05:22:10 +0000873 }
874 }
875
Chris Lattner2be06072006-01-13 19:34:14 +0000876 // 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();
Chris Lattner2be06072006-01-13 19:34:14 +0000880 // Get the two intrinsics we care about.
Chris Lattner88b36f12009-10-17 05:39:39 +0000881 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
882 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000883
Chris Lattner2be06072006-01-13 19:34:14 +0000884 // Insert the llvm.stacksave.
John McCall5af84522011-06-14 02:51:53 +0000885 CallInst *SavedPtr = IRBuilder<>(FirstNewBlock, FirstNewBlock->begin())
886 .CreateCall(StackSave, "savedstack");
Duncan Sands7c8fb1a2008-09-05 12:37:12 +0000887
Chris Lattner2be06072006-01-13 19:34:14 +0000888 // Insert a call to llvm.stackrestore before any return instructions in the
889 // inlined function.
Reid Kleckner900d46f2014-05-15 21:10:46 +0000890 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))
894 continue;
Reid Klecknerf0915aa2014-05-15 20:11:28 +0000895 IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr);
Reid Kleckner900d46f2014-05-15 21:10:46 +0000896 }
Chris Lattner9f3dced2005-05-06 06:47:52 +0000897 }
898
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000899 // If we are inlining for an invoke instruction, we must make sure to rewrite
Bill Wendling0aef16a2012-02-06 21:44:22 +0000900 // any call instructions into invoke instructions.
Chris Lattner908d7952006-01-13 19:05:59 +0000901 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Chris Lattner8900f3e2009-09-01 18:44:06 +0000902 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000903
Reid Klecknerf0915aa2014-05-15 20:11:28 +0000904 // 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
907 // phi below.
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;
912
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);
919 continue;
920 }
921 if (!NeedBitCast)
922 continue;
923
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();
928 if (OldCast)
929 OldCast->eraseFromParent();
930
931 // Insert a new bitcast and return with the right type.
932 IRBuilder<> Builder(CurBB);
933 Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy));
934 }
935
936 // Leave behind the normal returns so we can merge control flow.
937 std::swap(Returns, NormalReturns);
938 }
939
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000940 // 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();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000949
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000950 // If the call site was an invoke instruction, add a branch to the normal
951 // destination.
Adrian Prantl15db52b2013-04-23 19:56:03 +0000952 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
953 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
954 NewBr->setDebugLoc(Returns[0]->getDebugLoc());
955 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000956
957 // If the return instruction returned a value, replace uses of the call with
958 // uses of the returned value.
Devang Patel841322b2008-03-04 21:15:15 +0000959 if (!TheCall->use_empty()) {
960 ReturnInst *R = Returns[0];
Eli Friedman36b90262009-05-08 00:22:04 +0000961 if (TheCall == R->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +0000962 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +0000963 else
964 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Patel841322b2008-03-04 21:15:15 +0000965 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000966 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman158ff2c2008-06-21 22:08:46 +0000967 TheCall->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000968
969 // Since we are now done with the return instruction, delete it also.
Dan Gohman158ff2c2008-06-21 22:08:46 +0000970 Returns[0]->eraseFromParent();
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000971
972 // We are now done with the inlining.
973 return true;
974 }
975
976 // Otherwise, we have the normal case, of more than one block to inline or
977 // multiple return sites.
978
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000979 // 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;
Craig Topperf40110f2014-04-25 05:29:35 +0000983 BranchInst *CreatedBranchToNormalDest = nullptr;
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000984 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000985
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000986 // Add an unconditional branch to make this look like the CallInst case...
Adrian Prantl15db52b2013-04-23 19:56:03 +0000987 CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000988
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000989 // 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.
Adrian Prantl15db52b2013-04-23 19:56:03 +0000992 AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest,
Chris Lattnerffefea02004-12-11 16:59:54 +0000993 CalledFunc->getName()+".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000994
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000995 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000996 // If this is a call instruction, we need to split the basic block that
997 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000998 //
999 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattnerffefea02004-12-11 16:59:54 +00001000 CalledFunc->getName()+".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001001 }
1002
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00001003 // Change the branch that used to go to AfterCallBB to branch to the first
1004 // basic block of the inlined function.
1005 //
1006 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001007 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00001008 "splitBasicBlock broken!");
1009 Br->setOperand(0, FirstNewBlock);
1010
1011
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.
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00001015 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
1016 FirstNewBlock, Caller->end());
1017
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001018 // Handle all of the return instructions that we just cloned in, and eliminate
1019 // any users of the original call/invoke instruction.
Chris Lattner229907c2011-07-18 04:54:35 +00001020 Type *RTy = CalledFunc->getReturnType();
Dan Gohman3b18fd72008-06-20 01:03:44 +00001021
Craig Topperf40110f2014-04-25 05:29:35 +00001022 PHINode *PHI = nullptr;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001023 if (Returns.size() > 1) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001024 // The PHI node should go at the front of the new basic block to merge all
1025 // possible incoming values.
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001026 if (!TheCall->use_empty()) {
Jay Foad52131342011-03-30 11:28:46 +00001027 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001028 AfterCallBB->begin());
1029 // Anything that used the result of the function call should now use the
1030 // PHI node as their operand.
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001031 TheCall->replaceAllUsesWith(PHI);
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001032 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001033
Gabor Greif5aa19222009-01-15 18:40:09 +00001034 // Loop over all of the return instructions adding entries to the PHI node
1035 // as appropriate.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001036 if (PHI) {
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());
Devang Patel780b3ca62008-03-07 20:06:16 +00001042 }
1043 }
1044
Chris Lattnerc6b3b252009-10-27 05:39:41 +00001045
Gabor Greif8c573f72009-01-16 23:08:50 +00001046 // Add a branch to the merge points and remove return instructions.
Richard Trieu624c2eb2013-04-30 22:45:10 +00001047 DebugLoc Loc;
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001048 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Richard Trieu624c2eb2013-04-30 22:45:10 +00001049 ReturnInst *RI = Returns[i];
Adrian Prantl09416382013-04-30 17:08:16 +00001050 BranchInst* BI = BranchInst::Create(AfterCallBB, RI);
Richard Trieu624c2eb2013-04-30 22:45:10 +00001051 Loc = RI->getDebugLoc();
1052 BI->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00001053 RI->eraseFromParent();
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001054 }
Adrian Prantl09416382013-04-30 17:08:16 +00001055 // We need to set the debug location to *somewhere* inside the
Adrian Prantl8beccf92013-04-30 17:33:32 +00001056 // inlined function. The line number may be nonsensical, but the
Adrian Prantl09416382013-04-30 17:08:16 +00001057 // instruction will at least be associated with the right
1058 // function.
1059 if (CreatedBranchToNormalDest)
Richard Trieu624c2eb2013-04-30 22:45:10 +00001060 CreatedBranchToNormalDest->setDebugLoc(Loc);
Devang Patel64d0f072008-03-10 18:34:00 +00001061 } 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.
Eli Friedman36b90262009-05-08 00:22:04 +00001064 if (!TheCall->use_empty()) {
1065 if (TheCall == Returns[0]->getReturnValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001066 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman36b90262009-05-08 00:22:04 +00001067 else
1068 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
1069 }
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001070
Jay Foad61ea0e42011-06-23 09:09:15 +00001071 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
1072 BasicBlock *ReturnBB = Returns[0]->getParent();
1073 ReturnBB->replaceAllUsesWith(AfterCallBB);
1074
Devang Patel64d0f072008-03-10 18:34:00 +00001075 // 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.
Devang Patel64d0f072008-03-10 18:34:00 +00001077 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
1078 ReturnBB->getInstList());
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001079
Adrian Prantl15db52b2013-04-23 19:56:03 +00001080 if (CreatedBranchToNormalDest)
1081 CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc());
1082
Devang Patel64d0f072008-03-10 18:34:00 +00001083 // Delete the return instruction now and empty ReturnBB now.
1084 Returns[0]->eraseFromParent();
1085 ReturnBB->eraseFromParent();
Chris Lattner6e79e552004-10-17 23:21:07 +00001086 } else if (!TheCall->use_empty()) {
1087 // No returns, but something is using the return value of the call. Just
1088 // nuke the result.
Owen Andersonb292b8c2009-07-30 23:03:37 +00001089 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001090 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001091
Chris Lattner18ef3fd2004-02-04 02:51:48 +00001092 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +00001093 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +00001094
Reid Klecknerf0915aa2014-05-15 20:11:28 +00001095 // 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();
1099
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00001100 // We should always be able to fold the entry block of the function into the
1101 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +00001102 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +00001103 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +00001104
Chris Lattner0328d752004-04-16 05:17:59 +00001105 // Splice the code entry block into calling block, right before the
1106 // unconditional branch.
Eric Christopher96513122011-06-23 06:24:52 +00001107 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
Jay Foad61ea0e42011-06-23 09:09:15 +00001108 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +00001109
1110 // Remove the unconditional branch.
1111 OrigBB->getInstList().erase(Br);
1112
1113 // Now we can remove the CalleeEntry block, which is now empty.
1114 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sands7c8fb1a2008-09-05 12:37:12 +00001115
Duncan Sands9d9a4e22010-11-17 11:16:23 +00001116 // 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.
Bill Wendlingce0c2292012-01-31 01:01:16 +00001119 if (PHI) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001120 if (Value *V = SimplifyInstruction(PHI, IFI.DL)) {
Duncan Sands9d9a4e22010-11-17 11:16:23 +00001121 PHI->replaceAllUsesWith(V);
1122 PHI->eraseFromParent();
1123 }
Bill Wendlingce0c2292012-01-31 01:01:16 +00001124 }
Duncan Sands9d9a4e22010-11-17 11:16:23 +00001125
Chris Lattner530d4bf2003-05-29 15:11:31 +00001126 return true;
1127}