Fix PR1395, by passing the ID correctly
[oota-llvm.git] / lib / Transforms / IPO / InlineSimple.cpp
1 //===- InlineSimple.cpp - Code to perform simple function inlining --------===//
2 //
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 //===----------------------------------------------------------------------===//
9 //
10 // This file implements bottom-up inlining of functions into callees.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Inliner.h"
15 #include "llvm/CallingConv.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Function.h"
19 #include "llvm/Type.h"
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Transforms/IPO.h"
23 using namespace llvm;
24
25 namespace {
26   struct VISIBILITY_HIDDEN ArgInfo {
27     unsigned ConstantWeight;
28     unsigned AllocaWeight;
29
30     ArgInfo(unsigned CWeight, unsigned AWeight)
31       : ConstantWeight(CWeight), AllocaWeight(AWeight) {}
32   };
33
34   // FunctionInfo - For each function, calculate the size of it in blocks and
35   // instructions.
36   struct VISIBILITY_HIDDEN FunctionInfo {
37     // NumInsts, NumBlocks - Keep track of how large each function is, which is
38     // used to estimate the code size cost of inlining it.
39     unsigned NumInsts, NumBlocks;
40
41     // ArgumentWeights - Each formal argument of the function is inspected to
42     // see if it is used in any contexts where making it a constant or alloca
43     // would reduce the code size.  If so, we add some value to the argument
44     // entry here.
45     std::vector<ArgInfo> ArgumentWeights;
46
47     FunctionInfo() : NumInsts(0), NumBlocks(0) {}
48
49     /// analyzeFunction - Fill in the current structure with information gleaned
50     /// from the specified function.
51     void analyzeFunction(Function *F);
52   };
53
54   class VISIBILITY_HIDDEN SimpleInliner : public Inliner {
55     std::map<const Function*, FunctionInfo> CachedFunctionInfo;
56   public:
57     SimpleInliner() : Inliner(&ID) {}
58     static char ID; // Pass identification, replacement for typeid
59     int getInlineCost(CallSite CS);
60   };
61   char SimpleInliner::ID = 0;
62   RegisterPass<SimpleInliner> X("inline", "Function Integration/Inlining");
63 }
64
65 Pass *llvm::createFunctionInliningPass() { return new SimpleInliner(); }
66
67 // CountCodeReductionForConstant - Figure out an approximation for how many
68 // instructions will be constant folded if the specified value is constant.
69 //
70 static unsigned CountCodeReductionForConstant(Value *V) {
71   unsigned Reduction = 0;
72   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
73     if (isa<BranchInst>(*UI))
74       Reduction += 40;          // Eliminating a conditional branch is a big win
75     else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI))
76       // Eliminating a switch is a big win, proportional to the number of edges
77       // deleted.
78       Reduction += (SI->getNumSuccessors()-1) * 40;
79     else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
80       // Turning an indirect call into a direct call is a BIG win
81       Reduction += CI->getCalledValue() == V ? 500 : 0;
82     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
83       // Turning an indirect call into a direct call is a BIG win
84       Reduction += II->getCalledValue() == V ? 500 : 0;
85     } else {
86       // Figure out if this instruction will be removed due to simple constant
87       // propagation.
88       Instruction &Inst = cast<Instruction>(**UI);
89       bool AllOperandsConstant = true;
90       for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
91         if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
92           AllOperandsConstant = false;
93           break;
94         }
95
96       if (AllOperandsConstant) {
97         // We will get to remove this instruction...
98         Reduction += 7;
99
100         // And any other instructions that use it which become constants
101         // themselves.
102         Reduction += CountCodeReductionForConstant(&Inst);
103       }
104     }
105
106   return Reduction;
107 }
108
109 // CountCodeReductionForAlloca - Figure out an approximation of how much smaller
110 // the function will be if it is inlined into a context where an argument
111 // becomes an alloca.
112 //
113 static unsigned CountCodeReductionForAlloca(Value *V) {
114   if (!isa<PointerType>(V->getType())) return 0;  // Not a pointer
115   unsigned Reduction = 0;
116   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
117     Instruction *I = cast<Instruction>(*UI);
118     if (isa<LoadInst>(I) || isa<StoreInst>(I))
119       Reduction += 10;
120     else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
121       // If the GEP has variable indices, we won't be able to do much with it.
122       for (Instruction::op_iterator I = GEP->op_begin()+1, E = GEP->op_end();
123            I != E; ++I)
124         if (!isa<Constant>(*I)) return 0;
125       Reduction += CountCodeReductionForAlloca(GEP)+15;
126     } else {
127       // If there is some other strange instruction, we're not going to be able
128       // to do much if we inline this.
129       return 0;
130     }
131   }
132
133   return Reduction;
134 }
135
136 /// analyzeFunction - Fill in the current structure with information gleaned
137 /// from the specified function.
138 void FunctionInfo::analyzeFunction(Function *F) {
139   unsigned NumInsts = 0, NumBlocks = 0;
140
141   // Look at the size of the callee.  Each basic block counts as 20 units, and
142   // each instruction counts as 10.
143   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
144     for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
145          II != E; ++II) {
146       if (isa<DbgInfoIntrinsic>(II)) continue;  // Debug intrinsics don't count.
147       
148       // Noop casts, including ptr <-> int,  don't count.
149       if (const CastInst *CI = dyn_cast<CastInst>(II)) {
150         if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) || 
151             isa<PtrToIntInst>(CI))
152           continue;
153       } else if (const GetElementPtrInst *GEPI =
154                          dyn_cast<GetElementPtrInst>(II)) {
155         // If a GEP has all constant indices, it will probably be folded with
156         // a load/store.
157         bool AllConstant = true;
158         for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
159           if (!isa<ConstantInt>(GEPI->getOperand(i))) {
160             AllConstant = false;
161             break;
162           }
163         if (AllConstant) continue;
164       }
165       
166       ++NumInsts;
167     }
168
169     ++NumBlocks;
170   }
171
172   this->NumBlocks = NumBlocks;
173   this->NumInsts  = NumInsts;
174
175   // Check out all of the arguments to the function, figuring out how much
176   // code can be eliminated if one of the arguments is a constant.
177   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
178     ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
179                                       CountCodeReductionForAlloca(I)));
180 }
181
182
183 // getInlineCost - The heuristic used to determine if we should inline the
184 // function call or not.
185 //
186 int SimpleInliner::getInlineCost(CallSite CS) {
187   Instruction *TheCall = CS.getInstruction();
188   Function *Callee = CS.getCalledFunction();
189   const Function *Caller = TheCall->getParent()->getParent();
190
191   // Don't inline a directly recursive call.
192   if (Caller == Callee) return 2000000000;
193
194   // InlineCost - This value measures how good of an inline candidate this call
195   // site is to inline.  A lower inline cost make is more likely for the call to
196   // be inlined.  This value may go negative.
197   //
198   int InlineCost = 0;
199
200   // If there is only one call of the function, and it has internal linkage,
201   // make it almost guaranteed to be inlined.
202   //
203   if (Callee->hasInternalLinkage() && Callee->hasOneUse())
204     InlineCost -= 30000;
205
206   // If this function uses the coldcc calling convention, prefer not to inline
207   // it.
208   if (Callee->getCallingConv() == CallingConv::Cold)
209     InlineCost += 2000;
210
211   // If the instruction after the call, or if the normal destination of the
212   // invoke is an unreachable instruction, the function is noreturn.  As such,
213   // there is little point in inlining this.
214   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
215     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
216       InlineCost += 10000;
217   } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
218     InlineCost += 10000;
219
220   // Get information about the callee...
221   FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
222
223   // If we haven't calculated this information yet, do so now.
224   if (CalleeFI.NumBlocks == 0)
225     CalleeFI.analyzeFunction(Callee);
226
227   // Add to the inline quality for properties that make the call valuable to
228   // inline.  This includes factors that indicate that the result of inlining
229   // the function will be optimizable.  Currently this just looks at arguments
230   // passed into the function.
231   //
232   unsigned ArgNo = 0;
233   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
234        I != E; ++I, ++ArgNo) {
235     // Each argument passed in has a cost at both the caller and the callee
236     // sides.  This favors functions that take many arguments over functions
237     // that take few arguments.
238     InlineCost -= 20;
239
240     // If this is a function being passed in, it is very likely that we will be
241     // able to turn an indirect function call into a direct function call.
242     if (isa<Function>(I))
243       InlineCost -= 100;
244
245     // If an alloca is passed in, inlining this function is likely to allow
246     // significant future optimization possibilities (like scalar promotion, and
247     // scalarization), so encourage the inlining of the function.
248     //
249     else if (isa<AllocaInst>(I)) {
250       if (ArgNo < CalleeFI.ArgumentWeights.size())
251         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
252
253     // If this is a constant being passed into the function, use the argument
254     // weights calculated for the callee to determine how much will be folded
255     // away with this information.
256     } else if (isa<Constant>(I)) {
257       if (ArgNo < CalleeFI.ArgumentWeights.size())
258         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
259     }
260   }
261
262   // Now that we have considered all of the factors that make the call site more
263   // likely to be inlined, look at factors that make us not want to inline it.
264
265   // Don't inline into something too big, which would make it bigger.  Here, we
266   // count each basic block as a single unit.
267   //
268   InlineCost += Caller->size()/20;
269
270
271   // Look at the size of the callee.  Each basic block counts as 20 units, and
272   // each instruction counts as 5.
273   InlineCost += CalleeFI.NumInsts*5 + CalleeFI.NumBlocks*20;
274   return InlineCost;
275 }
276