1 //===- MethodInlining.cpp - Code to perform method inlining ---------------===//
3 // This file implements inlining of methods.
6 // * Exports functionality to inline any method call
7 // * Inlines methods that consist of a single basic block
8 // * Is able to inline ANY method call
9 // . Has a smart heuristic for when to inline a method
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 // TODO: Currently this throws away all of the symbol names in the method being
17 // inlined. This shouldn't happen.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/MethodInlining.h"
22 #include "llvm/Module.h"
23 #include "llvm/Method.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/iPHINode.h"
26 #include "llvm/iOther.h"
32 #include "llvm/Assembly/Writer.h"
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 // InlineMethod - This function forcibly inlines the called method 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 // method by one level.
65 bool InlineMethod(BasicBlock::iterator CIIt) {
66 assert(isa<CallInst>(*CIIt) && "InlineMethod only works on CallInst nodes!");
67 assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
68 assert((*CIIt)->getParent()->getParent() && "Instruction not in method!");
70 CallInst *CI = cast<CallInst>(*CIIt);
71 const Method *CalledMeth = CI->getCalledMethod();
72 if (CalledMeth == 0 || // Can't inline external method or indirect call!
73 CalledMeth->isExternal()) return false;
75 //cerr << "Inlining " << CalledMeth->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(CIIt);
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 (CalledMeth->getReturnType() != Type::VoidTy) {
96 PHI = new PHINode(CalledMeth->getReturnType(), CI->getName());
98 // The PHI node should go at the front of the new basic block to merge all
99 // possible incoming values.
101 NewBB->getInstList().push_front(PHI);
103 // Anything that used the result of the function call should now use the PHI
104 // node as their operand.
106 CI->replaceAllUsesWith(PHI);
109 // Keep a mapping between the original method's values and the new duplicated
110 // code's values. This includes all of: Method arguments, instruction values,
111 // constant pool entries, and basic blocks.
113 std::map<const Value *, Value*> ValueMap;
115 // Add the method arguments to the mapping: (start counting at 1 to skip the
116 // method reference itself)
118 Method::ArgumentListType::const_iterator PTI =
119 CalledMeth->getArgumentList().begin();
120 for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
121 ValueMap[*PTI] = CI->getOperand(a);
123 ValueMap[NewBB] = NewBB; // Returns get converted to reference NewBB
125 // Loop over all of the basic blocks in the method, inlining them as
126 // appropriate. Keep track of the first basic block of the method...
128 for (Method::const_iterator BI = CalledMeth->begin();
129 BI != CalledMeth->end(); ++BI) {
130 const BasicBlock *BB = *BI;
131 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
133 // Create a new basic block to copy instructions into!
134 BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
135 if (BB->hasName()) IBB->setName(BB->getName()+".i"); // .i = inlined once
137 ValueMap[BB] = IBB; // Add basic block mapping.
139 // Make sure to capture the mapping that a return will use...
140 // TODO: This assumes that the RET is returning a value computed in the same
141 // basic block as the return was issued from!
143 const TerminatorInst *TI = BB->getTerminator();
145 // Loop over all instructions copying them over...
146 Instruction *NewInst;
147 for (BasicBlock::const_iterator II = BB->begin();
148 II != (BB->end()-1); ++II) {
149 IBB->getInstList().push_back((NewInst = (*II)->clone()));
150 ValueMap[*II] = NewInst; // Add instruction map to value.
151 if ((*II)->hasName())
152 NewInst->setName((*II)->getName()+".i"); // .i = inlined once
155 // Copy over the terminator now...
156 switch (TI->getOpcode()) {
157 case Instruction::Ret: {
158 const ReturnInst *RI = cast<const ReturnInst>(TI);
160 if (PHI) { // The PHI node should include this value!
161 assert(RI->getReturnValue() && "Ret should have value!");
162 assert(RI->getReturnValue()->getType() == PHI->getType() &&
163 "Ret value not consistent in method!");
164 PHI->addIncoming((Value*)RI->getReturnValue(), cast<BasicBlock>(BB));
167 // Add a branch to the code that was after the original Call.
168 IBB->getInstList().push_back(new BranchInst(NewBB));
171 case Instruction::Br:
172 IBB->getInstList().push_back(TI->clone());
176 cerr << "MethodInlining: Don't know how to handle terminator: " << TI;
182 // Loop over all of the instructions in the method, fixing up operand
183 // references as we go. This uses ValueMap to do all the hard work.
185 for (Method::const_iterator BI = CalledMeth->begin();
186 BI != CalledMeth->end(); ++BI) {
187 const BasicBlock *BB = *BI;
188 BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
190 // Loop over all instructions, fixing each one as we find it...
192 for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); II++)
193 RemapInstruction(*II, ValueMap);
196 if (PHI) RemapInstruction(PHI, ValueMap); // Fix the PHI node also...
198 // Change the branch that used to go to NewBB to branch to the first basic
199 // block of the inlined method.
201 TerminatorInst *Br = OrigBB->getTerminator();
202 assert(Br && Br->getOpcode() == Instruction::Br &&
203 "splitBasicBlock broken!");
204 Br->setOperand(0, ValueMap[CalledMeth->front()]);
206 // Since we are now done with the CallInst, we can finally delete it.
211 bool InlineMethod(CallInst *CI) {
212 assert(CI->getParent() && "CallInst not embeded in BasicBlock!");
213 BasicBlock *PBB = CI->getParent();
215 BasicBlock::iterator CallIt = find(PBB->begin(), PBB->end(), CI);
217 assert(CallIt != PBB->end() &&
218 "CallInst has parent that doesn't contain CallInst?!?");
219 return InlineMethod(CallIt);
222 static inline bool ShouldInlineMethod(const CallInst *CI, const Method *M) {
223 assert(CI->getParent() && CI->getParent()->getParent() &&
224 "Call not embedded into a method!");
226 // Don't inline a recursive call.
227 if (CI->getParent()->getParent() == M) return false;
229 // Don't inline something too big. This is a really crappy heuristic
230 if (M->size() > 3) return false;
232 // Don't inline into something too big. This is a **really** crappy heuristic
233 if (CI->getParent()->getParent()->size() > 10) return false;
235 // Go ahead and try just about anything else.
240 static inline bool DoMethodInlining(BasicBlock *BB) {
241 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
242 if (CallInst *CI = dyn_cast<CallInst>(*I)) {
243 // Check to see if we should inline this method
244 Method *M = CI->getCalledMethod();
245 if (M && ShouldInlineMethod(CI, M))
246 return InlineMethod(I);
252 bool MethodInlining::doMethodInlining(Method *M) {
253 bool Changed = false;
255 // Loop through now and inline instructions a basic block at a time...
256 for (Method::iterator I = M->begin(); I != M->end(); )
257 if (DoMethodInlining(*I)) {
259 // Iterator is now invalidated by new basic blocks inserted