blob: 5c1564b0ed85479189f3fdc947a4d3021bead900 [file] [log] [blame]
Chris Lattner530d4bf2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
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//
13// FIXME: This pass should transform alloca instructions in the called function
Chris Lattner9fc977e2004-02-04 01:41:09 +000014// into alloca/dealloca pairs! Or perhaps it should refuse to inline them!
Chris Lattner530d4bf2003-05-29 15:11:31 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner0cc265e2003-08-24 06:59:16 +000019#include "llvm/Constant.h"
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +000020#include "llvm/DerivedTypes.h"
Chris Lattner530d4bf2003-05-29 15:11:31 +000021#include "llvm/Module.h"
Chris Lattner0cc265e2003-08-24 06:59:16 +000022#include "llvm/Instructions.h"
23#include "llvm/Intrinsics.h"
24#include "llvm/Support/CallSite.h"
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +000025#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000026using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000027
Chris Lattnerdf3c3422004-01-09 06:12:26 +000028bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
29bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));}
Chris Lattner0cc265e2003-08-24 06:59:16 +000030
Chris Lattner530d4bf2003-05-29 15:11:31 +000031// InlineFunction - This function inlines the called function into the basic
32// block of the caller. This returns false if it is not possible to inline this
33// call. The program is still in a well defined state if this occurs though.
34//
35// Note that this only does one level of inlining. For example, if the
36// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
37// exists in the instruction stream. Similiarly this will inline a recursive
38// function by one level.
39//
Chris Lattnerdf3c3422004-01-09 06:12:26 +000040bool llvm::InlineFunction(CallSite CS) {
Chris Lattner0cc265e2003-08-24 06:59:16 +000041 Instruction *TheCall = CS.getInstruction();
42 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
43 "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +000044
Chris Lattner0cc265e2003-08-24 06:59:16 +000045 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattner530d4bf2003-05-29 15:11:31 +000046 if (CalledFunc == 0 || // Can't inline external function or indirect
47 CalledFunc->isExternal() || // call, or call to a vararg function!
48 CalledFunc->getFunctionType()->isVarArg()) return false;
49
Chris Lattner0cc265e2003-08-24 06:59:16 +000050 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +000051 Function *Caller = OrigBB->getParent();
52
Chris Lattner9fc977e2004-02-04 01:41:09 +000053 // Get an iterator to the last basic block in the function, which will have
54 // the new function inlined after it.
55 //
56 Function::iterator LastBlock = &Caller->back();
57
Chris Lattner18ef3fd2004-02-04 02:51:48 +000058 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +000059 // function.
Chris Lattner18ef3fd2004-02-04 02:51:48 +000060 std::vector<ReturnInst*> Returns;
61 { // Scope to destroy ValueMap after cloning.
62 // Calculate the vector of arguments to pass into the function cloner...
63 std::map<const Value*, Value*> ValueMap;
64 assert(std::distance(CalledFunc->abegin(), CalledFunc->aend()) ==
65 std::distance(CS.arg_begin(), CS.arg_end()) &&
66 "No varargs calls can be inlined!");
67
68 CallSite::arg_iterator AI = CS.arg_begin();
69 for (Function::const_aiterator I = CalledFunc->abegin(),
70 E = CalledFunc->aend(); I != E; ++I, ++AI)
71 ValueMap[I] = *AI;
72
73 // Clone the entire body of the callee into the caller.
74 CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
75 }
76
77 // Remember the first block that is newly cloned over.
78 Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
Chris Lattner530d4bf2003-05-29 15:11:31 +000079
80 // If there are any alloca instructions in the block that used to be the entry
81 // block for the callee, move them to the entry block of the caller. First
82 // calculate which instruction they should be inserted before. We insert the
83 // instructions at the end of the current alloca list.
84 //
Chris Lattner18ef3fd2004-02-04 02:51:48 +000085 if (isa<AllocaInst>(FirstNewBlock->begin())) {
Chris Lattner0cc265e2003-08-24 06:59:16 +000086 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
87 while (isa<AllocaInst>(InsertPoint)) ++InsertPoint;
88
Chris Lattner18ef3fd2004-02-04 02:51:48 +000089 for (BasicBlock::iterator I = FirstNewBlock->begin(),
90 E = FirstNewBlock->end(); I != E; )
Chris Lattnerb4778c72003-10-14 01:11:07 +000091 if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
92 if (isa<Constant>(AI->getArraySize())) {
Chris Lattner18ef3fd2004-02-04 02:51:48 +000093 FirstNewBlock->getInstList().remove(AI);
Chris Lattnerb4778c72003-10-14 01:11:07 +000094 Caller->front().getInstList().insert(InsertPoint, AI);
95 }
Chris Lattner0cc265e2003-08-24 06:59:16 +000096 }
Chris Lattner530d4bf2003-05-29 15:11:31 +000097
Chris Lattner18ef3fd2004-02-04 02:51:48 +000098 // If we are inlining for an invoke instruction, we must make sure to rewrite
99 // any inlined 'unwind' instructions into branches to the invoke exception
100 // destination, and call instructions into invoke instructions.
101 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
102 BasicBlock *InvokeDest = II->getExceptionalDest();
103 std::vector<Value*> InvokeDestPHIValues;
104
105 // If there are PHI nodes in the exceptional destination block, we need to
106 // keep track of which values came into them from this invoke, then remove
107 // the entry for this block.
108 for (BasicBlock::iterator I = InvokeDest->begin();
109 PHINode *PN = dyn_cast<PHINode>(I); ++I)
110 // Save the value to use for this edge...
111 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
112
113 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
114 BB != E; ++BB) {
Chris Lattner0cc265e2003-08-24 06:59:16 +0000115 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
116 // We only need to check for function calls: inlined invoke instructions
117 // require no special handling...
118 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Chris Lattnercaa12cf2003-09-08 19:00:30 +0000119 // Convert this function call into an invoke instruction...
Chris Lattner0cc265e2003-08-24 06:59:16 +0000120
Chris Lattnercaa12cf2003-09-08 19:00:30 +0000121 // First, split the basic block...
122 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
123
124 // Next, create the new invoke instruction, inserting it at the end
125 // of the old basic block.
Chris Lattner7f89ea72003-09-15 02:10:16 +0000126 InvokeInst *II =
127 new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
128 std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
129 CI->getName(), BB->getTerminator());
130
131 // Make sure that anything using the call now uses the invoke!
132 CI->replaceAllUsesWith(II);
133
Chris Lattnercaa12cf2003-09-08 19:00:30 +0000134 // Delete the unconditional branch inserted by splitBasicBlock
135 BB->getInstList().pop_back();
136 Split->getInstList().pop_front(); // Delete the original call
137
Chris Lattner0178d262003-09-22 21:59:27 +0000138 // Update any PHI nodes in the exceptional block to indicate that
139 // there is now a new entry in them.
140 unsigned i = 0;
141 for (BasicBlock::iterator I = InvokeDest->begin();
142 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
143 PN->addIncoming(InvokeDestPHIValues[i], BB);
144
Chris Lattnercaa12cf2003-09-08 19:00:30 +0000145 // This basic block is now complete, start scanning the next one.
146 break;
Chris Lattner0cc265e2003-08-24 06:59:16 +0000147 } else {
148 ++I;
149 }
150 }
Chris Lattner530d4bf2003-05-29 15:11:31 +0000151
Chris Lattner04ecefe2003-09-08 19:44:26 +0000152 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
153 // An UnwindInst requires special handling when it gets inlined into an
154 // invoke site. Once this happens, we know that the unwind would cause
155 // a control transfer to the invoke exception destination, so we can
156 // transform it into a direct branch to the exception destination.
Chris Lattner2af51722003-11-20 18:25:24 +0000157 new BranchInst(InvokeDest, UI);
Chris Lattner04ecefe2003-09-08 19:44:26 +0000158
159 // Delete the unwind instruction!
160 UI->getParent()->getInstList().pop_back();
Chris Lattnerd9f4ffd2003-10-27 05:33:09 +0000161
162 // Update any PHI nodes in the exceptional block to indicate that
163 // there is now a new entry in them.
164 unsigned i = 0;
165 for (BasicBlock::iterator I = InvokeDest->begin();
166 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
167 PN->addIncoming(InvokeDestPHIValues[i], BB);
Chris Lattner04ecefe2003-09-08 19:44:26 +0000168 }
169 }
170
Chris Lattner0178d262003-09-22 21:59:27 +0000171 // Now that everything is happy, we have one final detail. The PHI nodes in
172 // the exception destination block still have entries due to the original
173 // invoke instruction. Eliminate these entries (which might even delete the
174 // PHI node) now.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000175 InvokeDest->removePredecessor(II->getParent());
Chris Lattner0178d262003-09-22 21:59:27 +0000176 }
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000177
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000178 // If we cloned in _exactly one_ basic block, and if that block ends in a
179 // return instruction, we splice the body of the inlined callee directly into
180 // the calling basic block.
181 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
182 // Move all of the instructions right before the call.
183 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
184 FirstNewBlock->begin(), FirstNewBlock->end());
185 // Remove the cloned basic block.
186 Caller->getBasicBlockList().pop_back();
187
188 // If the call site was an invoke instruction, add a branch to the normal
189 // destination.
190 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
191 new BranchInst(II->getNormalDest(), TheCall);
192
193 // If the return instruction returned a value, replace uses of the call with
194 // uses of the returned value.
195 if (!TheCall->use_empty())
196 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
197
198 // Since we are now done with the Call/Invoke, we can delete it.
199 TheCall->getParent()->getInstList().erase(TheCall);
200
201 // Since we are now done with the return instruction, delete it also.
202 Returns[0]->getParent()->getInstList().erase(Returns[0]);
203
204 // We are now done with the inlining.
205 return true;
206 }
207
208 // Otherwise, we have the normal case, of more than one block to inline or
209 // multiple return sites.
210
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000211 // We want to clone the entire callee function into the hole between the
212 // "starter" and "ender" blocks. How we accomplish this depends on whether
213 // this is an invoke instruction or a call instruction.
214 BasicBlock *AfterCallBB;
215 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000216
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000217 // Add an unconditional branch to make this look like the CallInst case...
218 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000219
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000220 // Split the basic block. This guarantees that no PHI nodes will have to be
221 // updated due to new incoming edges, and make the invoke case more
222 // symmetric to the call case.
223 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
224 CalledFunc->getName()+".entry");
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000225
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000226 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000227 // If this is a call instruction, we need to split the basic block that
228 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000229 //
230 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
231 CalledFunc->getName()+".entry");
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000232 }
233
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000234 // Change the branch that used to go to AfterCallBB to branch to the first
235 // basic block of the inlined function.
236 //
237 TerminatorInst *Br = OrigBB->getTerminator();
238 assert(Br && Br->getOpcode() == Instruction::Br &&
239 "splitBasicBlock broken!");
240 Br->setOperand(0, FirstNewBlock);
241
242
243 // Now that the function is correct, make it a little bit nicer. In
244 // particular, move the basic blocks inserted from the end of the function
245 // into the space made by splitting the source basic block.
246 //
247 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
248 FirstNewBlock, Caller->end());
249
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000250 // Handle all of the return instructions that we just cloned in, and eliminate
251 // any users of the original call/invoke instruction.
252 if (Returns.size() > 1) {
253 // The PHI node should go at the front of the new basic block to merge all
254 // possible incoming values.
255 //
256 PHINode *PHI = 0;
257 if (!TheCall->use_empty()) {
258 PHI = new PHINode(CalledFunc->getReturnType(),
259 TheCall->getName(), AfterCallBB->begin());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000260
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000261 // Anything that used the result of the function call should now use the
262 // PHI node as their operand.
263 //
264 TheCall->replaceAllUsesWith(PHI);
265 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000266
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000267 // Loop over all of the return instructions, turning them into unconditional
268 // branches to the merge point now, and adding entries to the PHI node as
269 // appropriate.
270 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
271 ReturnInst *RI = Returns[i];
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000272
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000273 if (PHI) {
274 assert(RI->getReturnValue() && "Ret should have value!");
275 assert(RI->getReturnValue()->getType() == PHI->getType() &&
276 "Ret value not consistent in function!");
277 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
278 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000279
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000280 // Add a branch to the merge point where the PHI node lives if it exists.
281 new BranchInst(AfterCallBB, RI);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000282
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000283 // Delete the return instruction now
284 RI->getParent()->getInstList().erase(RI);
285 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000286
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000287 } else if (!Returns.empty()) {
288 // Otherwise, if there is exactly one return value, just replace anything
289 // using the return value of the call with the computed value.
290 if (!TheCall->use_empty())
291 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000292
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000293 // Add a branch to the merge point where the PHI node lives if it exists.
294 new BranchInst(AfterCallBB, Returns[0]);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000295
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000296 // Delete the return instruction now
297 Returns[0]->getParent()->getInstList().erase(Returns[0]);
298 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000299
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000300 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000301 TheCall->getParent()->getInstList().erase(TheCall);
Chris Lattner530d4bf2003-05-29 15:11:31 +0000302
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +0000303 // We should always be able to fold the entry block of the function into the
304 // single predecessor of the block...
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000305 assert(cast<BranchInst>(Br)->isUnconditional() &&"splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +0000306 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
307 SimplifyCFG(CalleeEntry);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000308
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +0000309 // Okay, continue the CFG cleanup. It's often the case that there is only a
310 // single return instruction in the callee function. If this is the case,
Chris Lattner0cc265e2003-08-24 06:59:16 +0000311 // then we have an unconditional branch from the return block to the
312 // 'AfterCallBB'. Check for this case, and eliminate the branch is possible.
313 SimplifyCFG(AfterCallBB);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000314
Chris Lattner530d4bf2003-05-29 15:11:31 +0000315 return true;
316}