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 // FIXME: This pass should transform alloca instructions in the called function
17 // into malloc/free pairs!
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/FunctionInlining.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/iPHINode.h"
26 #include "llvm/iOther.h"
27 #include "llvm/Type.h"
28 #include "Support/Statistic.h"
31 static Statistic<> NumInlined("inline", "Number of functions inlined");
34 // RemapInstruction - Convert the instruction operands from referencing the
35 // current values into those specified by ValueMap.
37 static inline void RemapInstruction(Instruction *I,
38 std::map<const Value *, Value*> &ValueMap) {
40 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
41 const Value *Op = I->getOperand(op);
42 Value *V = ValueMap[Op];
43 if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
44 continue; // Globals and constants don't get relocated
47 cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
48 cerr << "\nInst = " << I;
50 assert(V && "Referenced value not in value map!");
55 // InlineFunction - This function forcibly inlines the called function into the
56 // basic block of the caller. This returns false if it is not possible to
57 // inline this call. The program is still in a well defined state if this
60 // Note that this only does one level of inlining. For example, if the
61 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
62 // exists in the instruction stream. Similiarly this will inline a recursive
63 // function by one level.
65 bool InlineFunction(CallInst *CI) {
66 assert(isa<CallInst>(CI) && "InlineFunction only works on CallInst nodes");
67 assert(CI->getParent() && "Instruction not embedded in basic block!");
68 assert(CI->getParent()->getParent() && "Instruction not in function!");
70 const Function *CalledFunc = CI->getCalledFunction();
71 if (CalledFunc == 0 || // Can't inline external function or indirect call!
72 CalledFunc->isExternal()) return false;
74 //cerr << "Inlining " << CalledFunc->getName() << " into "
75 // << CurrentMeth->getName() << "\n";
77 BasicBlock *OrigBB = CI->getParent();
79 // Call splitBasicBlock - The original basic block now ends at the instruction
80 // immediately before the call. The original basic block now ends with an
81 // unconditional branch to NewBB, and NewBB starts with the call instruction.
83 BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
84 NewBB->setName("InlinedFunctionReturnNode");
86 // Remove (unlink) the CallInst from the start of the new basic block.
87 NewBB->getInstList().remove(CI);
89 // If we have a return value generated by this call, convert it into a PHI
90 // node that gets values from each of the old RET instructions in the original
94 if (CalledFunc->getReturnType() != Type::VoidTy) {
95 // The PHI node should go at the front of the new basic block to merge all
96 // possible incoming values.
98 PHI = new PHINode(CalledFunc->getReturnType(), CI->getName(),
101 // Anything that used the result of the function call should now use the PHI
102 // node as their operand.
104 CI->replaceAllUsesWith(PHI);
107 // Keep a mapping between the original function's values and the new
108 // duplicated code's values. This includes all of: Function arguments,
109 // instruction values, constant pool entries, and basic blocks.
111 std::map<const Value *, Value*> ValueMap;
113 // Add the function arguments to the mapping: (start counting at 1 to skip the
114 // function reference itself)
116 Function::const_aiterator PTI = CalledFunc->abegin();
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 BB = CalledFunc->begin();
126 BB != CalledFunc->end(); ++BB) {
127 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
129 // Create a new basic block to copy instructions into!
130 BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
131 if (BB->hasName()) IBB->setName(BB->getName()+".i"); // .i = inlined once
133 ValueMap[BB] = IBB; // Add basic block mapping.
135 // Make sure to capture the mapping that a return will use...
136 // TODO: This assumes that the RET is returning a value computed in the same
137 // basic block as the return was issued from!
139 const TerminatorInst *TI = BB->getTerminator();
141 // Loop over all instructions copying them over...
142 Instruction *NewInst;
143 for (BasicBlock::const_iterator II = BB->begin();
144 II != --BB->end(); ++II) {
145 IBB->getInstList().push_back((NewInst = II->clone()));
146 ValueMap[II] = NewInst; // Add instruction map to value.
148 NewInst->setName(II->getName()+".i"); // .i = inlined once
151 // Copy over the terminator now...
152 switch (TI->getOpcode()) {
153 case Instruction::Ret: {
154 const ReturnInst *RI = cast<ReturnInst>(TI);
156 if (PHI) { // The PHI node should include this value!
157 assert(RI->getReturnValue() && "Ret should have value!");
158 assert(RI->getReturnValue()->getType() == PHI->getType() &&
159 "Ret value not consistent in function!");
160 PHI->addIncoming((Value*)RI->getReturnValue(),
161 (BasicBlock*)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 BB = CalledFunc->begin();
183 BB != CalledFunc->end(); ++BB) {
184 BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
186 // Loop over all instructions, fixing each one as we find it...
188 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); ++II)
189 RemapInstruction(II, ValueMap);
193 RemapInstruction(PHI, ValueMap); // Fix the PHI node also...
195 // Check to see if the PHI node only has one argument. This is a common
196 // case resulting from there only being a single return instruction in the
197 // function call. Because this is so common, eliminate the PHI node.
199 if (PHI->getNumIncomingValues() == 1) {
200 PHI->replaceAllUsesWith(PHI->getIncomingValue(0));
201 PHI->getParent()->getInstList().erase(PHI);
205 // Change the branch that used to go to NewBB to branch to the first basic
206 // block of the inlined function.
208 TerminatorInst *Br = OrigBB->getTerminator();
209 assert(Br && Br->getOpcode() == Instruction::Br &&
210 "splitBasicBlock broken!");
211 Br->setOperand(0, ValueMap[&CalledFunc->front()]);
213 // Since we are now done with the CallInst, we can finally delete it.
218 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
219 assert(CI->getParent() && CI->getParent()->getParent() &&
220 "Call not embedded into a function!");
222 // Don't inline a recursive call.
223 if (CI->getParent()->getParent() == F) return false;
225 // Don't inline something too big. This is a really crappy heuristic
226 if (F->size() > 3) return false;
228 // Don't inline into something too big. This is a **really** crappy heuristic
229 if (CI->getParent()->getParent()->size() > 10) return false;
231 // Go ahead and try just about anything else.
236 static inline bool DoFunctionInlining(BasicBlock *BB) {
237 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
238 if (CallInst *CI = dyn_cast<CallInst>(&*I)) {
239 // Check to see if we should inline this function
240 Function *F = CI->getCalledFunction();
241 if (F && ShouldInlineFunction(CI, F)) {
242 return InlineFunction(CI);
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)) {
268 struct FunctionInlining : public FunctionPass {
269 virtual bool runOnFunction(Function &F) {
270 return doFunctionInlining(F);
273 RegisterOpt<FunctionInlining> X("inline", "Function Integration/Inlining");
276 Pass *createFunctionInliningPass() { return new FunctionInlining(); }