1 //===- FunctionInlining.cpp - Code to perform function inlining -----------===//
3 // This file implements inlining of functions.
6 // * Exports functionality to inline any function call
7 // * Inlines functions that consist of a single basic block
8 // * Is able to inline ANY function call
9 // . Has a smart heuristic for when to inline a function
12 // * This pass opens up a lot of opportunities for constant propogation. It
13 // is a good idea to to run a constant propogation pass, then a DCE pass
14 // sometime after running this pass.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/MethodInlining.h"
19 #include "llvm/Module.h"
20 #include "llvm/Function.h"
21 #include "llvm/Pass.h"
22 #include "llvm/iTerminators.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Type.h"
31 // RemapInstruction - Convert the instruction operands from referencing the
32 // current values into those specified by ValueMap.
34 static inline void RemapInstruction(Instruction *I,
35 std::map<const Value *, Value*> &ValueMap) {
37 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
38 const Value *Op = I->getOperand(op);
39 Value *V = ValueMap[Op];
40 if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
41 continue; // Globals and constants don't get relocated
44 cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
45 cerr << "\nInst = " << I;
47 assert(V && "Referenced value not in value map!");
52 // InlineMethod - This function forcibly inlines the called function into the
53 // basic block of the caller. This returns false if it is not possible to
54 // inline this call. The program is still in a well defined state if this
57 // Note that this only does one level of inlining. For example, if the
58 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
59 // exists in the instruction stream. Similiarly this will inline a recursive
60 // function by one level.
62 bool InlineMethod(BasicBlock::iterator CIIt) {
63 assert(isa<CallInst>(*CIIt) && "InlineMethod only works on CallInst nodes!");
64 assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
65 assert((*CIIt)->getParent()->getParent() && "Instruction not in function!");
67 CallInst *CI = cast<CallInst>(*CIIt);
68 const Function *CalledMeth = CI->getCalledFunction();
69 if (CalledMeth == 0 || // Can't inline external function or indirect call!
70 CalledMeth->isExternal()) return false;
72 //cerr << "Inlining " << CalledMeth->getName() << " into "
73 // << CurrentMeth->getName() << "\n";
75 BasicBlock *OrigBB = CI->getParent();
77 // Call splitBasicBlock - The original basic block now ends at the instruction
78 // immediately before the call. The original basic block now ends with an
79 // unconditional branch to NewBB, and NewBB starts with the call instruction.
81 BasicBlock *NewBB = OrigBB->splitBasicBlock(CIIt);
82 NewBB->setName("InlinedFunctionReturnNode");
84 // Remove (unlink) the CallInst from the start of the new basic block.
85 NewBB->getInstList().remove(CI);
87 // If we have a return value generated by this call, convert it into a PHI
88 // node that gets values from each of the old RET instructions in the original
92 if (CalledMeth->getReturnType() != Type::VoidTy) {
93 PHI = new PHINode(CalledMeth->getReturnType(), CI->getName());
95 // The PHI node should go at the front of the new basic block to merge all
96 // possible incoming values.
98 NewBB->getInstList().push_front(PHI);
100 // Anything that used the result of the function call should now use the PHI
101 // node as their operand.
103 CI->replaceAllUsesWith(PHI);
106 // Keep a mapping between the original function's values and the new
107 // duplicated code's values. This includes all of: Function arguments,
108 // instruction values, constant pool entries, and basic blocks.
110 std::map<const Value *, Value*> ValueMap;
112 // Add the function arguments to the mapping: (start counting at 1 to skip the
113 // function reference itself)
115 Function::ArgumentListType::const_iterator PTI =
116 CalledMeth->getArgumentList().begin();
117 for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
118 ValueMap[*PTI] = CI->getOperand(a);
120 ValueMap[NewBB] = NewBB; // Returns get converted to reference NewBB
122 // Loop over all of the basic blocks in the function, inlining them as
123 // appropriate. Keep track of the first basic block of the function...
125 for (Function::const_iterator BI = CalledMeth->begin();
126 BI != CalledMeth->end(); ++BI) {
127 const BasicBlock *BB = *BI;
128 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
130 // Create a new basic block to copy instructions into!
131 BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
132 if (BB->hasName()) IBB->setName(BB->getName()+".i"); // .i = inlined once
134 ValueMap[BB] = IBB; // Add basic block mapping.
136 // Make sure to capture the mapping that a return will use...
137 // TODO: This assumes that the RET is returning a value computed in the same
138 // basic block as the return was issued from!
140 const TerminatorInst *TI = BB->getTerminator();
142 // Loop over all instructions copying them over...
143 Instruction *NewInst;
144 for (BasicBlock::const_iterator II = BB->begin();
145 II != (BB->end()-1); ++II) {
146 IBB->getInstList().push_back((NewInst = (*II)->clone()));
147 ValueMap[*II] = NewInst; // Add instruction map to value.
148 if ((*II)->hasName())
149 NewInst->setName((*II)->getName()+".i"); // .i = inlined once
152 // Copy over the terminator now...
153 switch (TI->getOpcode()) {
154 case Instruction::Ret: {
155 const ReturnInst *RI = cast<const ReturnInst>(TI);
157 if (PHI) { // The PHI node should include this value!
158 assert(RI->getReturnValue() && "Ret should have value!");
159 assert(RI->getReturnValue()->getType() == PHI->getType() &&
160 "Ret value not consistent in function!");
161 PHI->addIncoming((Value*)RI->getReturnValue(), cast<BasicBlock>(BB));
164 // Add a branch to the code that was after the original Call.
165 IBB->getInstList().push_back(new BranchInst(NewBB));
168 case Instruction::Br:
169 IBB->getInstList().push_back(TI->clone());
173 cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
179 // Loop over all of the instructions in the function, fixing up operand
180 // references as we go. This uses ValueMap to do all the hard work.
182 for (Function::const_iterator BI = CalledMeth->begin();
183 BI != CalledMeth->end(); ++BI) {
184 const BasicBlock *BB = *BI;
185 BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
187 // Loop over all instructions, fixing each one as we find it...
189 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
190 RemapInstruction(*II, ValueMap);
193 if (PHI) RemapInstruction(PHI, ValueMap); // Fix the PHI node also...
195 // Change the branch that used to go to NewBB to branch to the first basic
196 // block of the inlined function.
198 TerminatorInst *Br = OrigBB->getTerminator();
199 assert(Br && Br->getOpcode() == Instruction::Br &&
200 "splitBasicBlock broken!");
201 Br->setOperand(0, ValueMap[CalledMeth->front()]);
203 // Since we are now done with the CallInst, we can finally delete it.
208 bool InlineMethod(CallInst *CI) {
209 assert(CI->getParent() && "CallInst not embeded in BasicBlock!");
210 BasicBlock *PBB = CI->getParent();
212 BasicBlock::iterator CallIt = find(PBB->begin(), PBB->end(), CI);
214 assert(CallIt != PBB->end() &&
215 "CallInst has parent that doesn't contain CallInst?!?");
216 return InlineMethod(CallIt);
219 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
220 assert(CI->getParent() && CI->getParent()->getParent() &&
221 "Call not embedded into a method!");
223 // Don't inline a recursive call.
224 if (CI->getParent()->getParent() == F) return false;
226 // Don't inline something too big. This is a really crappy heuristic
227 if (F->size() > 3) return false;
229 // Don't inline into something too big. This is a **really** crappy heuristic
230 if (CI->getParent()->getParent()->size() > 10) return false;
232 // Go ahead and try just about anything else.
237 static inline bool DoFunctionInlining(BasicBlock *BB) {
238 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
239 if (CallInst *CI = dyn_cast<CallInst>(*I)) {
240 // Check to see if we should inline this function
241 Function *F = CI->getCalledFunction();
242 if (F && ShouldInlineFunction(CI, F))
243 return InlineMethod(I);
249 // doFunctionInlining - Use a heuristic based approach to inline functions that
250 // seem to look good.
252 static bool doFunctionInlining(Function *F) {
253 bool Changed = false;
255 // Loop through now and inline instructions a basic block at a time...
256 for (Function::iterator I = F->begin(); I != F->end(); )
257 if (DoFunctionInlining(*I)) {
259 // Iterator is now invalidated by new basic blocks inserted
269 struct FunctionInlining : public MethodPass {
270 virtual bool runOnMethod(Function *F) {
271 return doFunctionInlining(F);
276 Pass *createMethodInliningPass() { return new FunctionInlining(); }