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/StatisticReporter.h"
32 static Statistic<> NumInlined("inline\t\t- Number of functions inlined");
35 // RemapInstruction - Convert the instruction operands from referencing the
36 // current values into those specified by ValueMap.
38 static inline void RemapInstruction(Instruction *I,
39 std::map<const Value *, Value*> &ValueMap) {
41 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
42 const Value *Op = I->getOperand(op);
43 Value *V = ValueMap[Op];
44 if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
45 continue; // Globals and constants don't get relocated
48 cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
49 cerr << "\nInst = " << I;
51 assert(V && "Referenced value not in value map!");
56 // InlineFunction - This function forcibly inlines the called function into the
57 // basic block of the caller. This returns false if it is not possible to
58 // inline this call. The program is still in a well defined state if this
61 // Note that this only does one level of inlining. For example, if the
62 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
63 // exists in the instruction stream. Similiarly this will inline a recursive
64 // function by one level.
66 bool InlineFunction(CallInst *CI) {
67 assert(isa<CallInst>(CI) && "InlineFunction only works on CallInst nodes");
68 assert(CI->getParent() && "Instruction not embedded in basic block!");
69 assert(CI->getParent()->getParent() && "Instruction not in function!");
71 const Function *CalledFunc = CI->getCalledFunction();
72 if (CalledFunc == 0 || // Can't inline external function or indirect call!
73 CalledFunc->isExternal()) return false;
75 //cerr << "Inlining " << CalledFunc->getName() << " into "
76 // << CurrentMeth->getName() << "\n";
78 BasicBlock *OrigBB = CI->getParent();
80 // Call splitBasicBlock - The original basic block now ends at the instruction
81 // immediately before the call. The original basic block now ends with an
82 // unconditional branch to NewBB, and NewBB starts with the call instruction.
84 BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
85 NewBB->setName("InlinedFunctionReturnNode");
87 // Remove (unlink) the CallInst from the start of the new basic block.
88 NewBB->getInstList().remove(CI);
90 // If we have a return value generated by this call, convert it into a PHI
91 // node that gets values from each of the old RET instructions in the original
95 if (CalledFunc->getReturnType() != Type::VoidTy) {
96 // The PHI node should go at the front of the new basic block to merge all
97 // possible incoming values.
99 PHI = new PHINode(CalledFunc->getReturnType(), CI->getName(),
102 // Anything that used the result of the function call should now use the PHI
103 // node as their operand.
105 CI->replaceAllUsesWith(PHI);
108 // Keep a mapping between the original function's values and the new
109 // duplicated code's values. This includes all of: Function arguments,
110 // instruction values, constant pool entries, and basic blocks.
112 std::map<const Value *, Value*> ValueMap;
114 // Add the function arguments to the mapping: (start counting at 1 to skip the
115 // function reference itself)
117 Function::const_aiterator PTI = CalledFunc->abegin();
118 for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
119 ValueMap[PTI] = CI->getOperand(a);
121 ValueMap[NewBB] = NewBB; // Returns get converted to reference NewBB
123 // Loop over all of the basic blocks in the function, inlining them as
124 // appropriate. Keep track of the first basic block of the function...
126 for (Function::const_iterator BB = CalledFunc->begin();
127 BB != CalledFunc->end(); ++BB) {
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(); ++II) {
146 IBB->getInstList().push_back((NewInst = II->clone()));
147 ValueMap[II] = NewInst; // Add instruction map to value.
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<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(),
162 (BasicBlock*)cast<BasicBlock>(&*BB));
165 // Add a branch to the code that was after the original Call.
166 IBB->getInstList().push_back(new BranchInst(NewBB));
169 case Instruction::Br:
170 IBB->getInstList().push_back(TI->clone());
174 cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
180 // Loop over all of the instructions in the function, fixing up operand
181 // references as we go. This uses ValueMap to do all the hard work.
183 for (Function::const_iterator BB = CalledFunc->begin();
184 BB != CalledFunc->end(); ++BB) {
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[&CalledFunc->front()]);
203 // Since we are now done with the CallInst, we can finally delete it.
208 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
209 assert(CI->getParent() && CI->getParent()->getParent() &&
210 "Call not embedded into a function!");
212 // Don't inline a recursive call.
213 if (CI->getParent()->getParent() == F) return false;
215 // Don't inline something too big. This is a really crappy heuristic
216 if (F->size() > 3) return false;
218 // Don't inline into something too big. This is a **really** crappy heuristic
219 if (CI->getParent()->getParent()->size() > 10) return false;
221 // Go ahead and try just about anything else.
226 static inline bool DoFunctionInlining(BasicBlock *BB) {
227 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
228 if (CallInst *CI = dyn_cast<CallInst>(&*I)) {
229 // Check to see if we should inline this function
230 Function *F = CI->getCalledFunction();
231 if (F && ShouldInlineFunction(CI, F)) {
232 return InlineFunction(CI);
239 // doFunctionInlining - Use a heuristic based approach to inline functions that
240 // seem to look good.
242 static bool doFunctionInlining(Function &F) {
243 bool Changed = false;
245 // Loop through now and inline instructions a basic block at a time...
246 for (Function::iterator I = F.begin(); I != F.end(); )
247 if (DoFunctionInlining(I)) {
258 struct FunctionInlining : public FunctionPass {
259 virtual bool runOnFunction(Function &F) {
260 return doFunctionInlining(F);
263 RegisterOpt<FunctionInlining> X("inline", "Function Integration/Inlining");
266 Pass *createFunctionInliningPass() { return new FunctionInlining(); }