98dbb69fe6a56e89b7e346fce879861ab2545c35
[oota-llvm.git] / lib / Analysis / InlineCost.cpp
1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements inline cost analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/InlineCost.h"
15 #include "llvm/Support/CallSite.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 using namespace llvm;
20
21 // CountCodeReductionForConstant - Figure out an approximation for how many
22 // instructions will be constant folded if the specified value is constant.
23 //
24 unsigned InlineCostAnalyzer::FunctionInfo::
25 CountCodeReductionForConstant(Value *V) {
26   unsigned Reduction = 0;
27   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
28     User *U = *UI;
29     if (isa<BranchInst>(U) || isa<SwitchInst>(U)) {
30       // We will be able to eliminate all but one of the successors.
31       const TerminatorInst &TI = cast<TerminatorInst>(*U);
32       const unsigned NumSucc = TI.getNumSuccessors();
33       unsigned Instrs = 0;
34       for (unsigned I = 0; I != NumSucc; ++I)
35         Instrs += Metrics.NumBBInsts[TI.getSuccessor(I)];
36       // We don't know which blocks will be eliminated, so use the average size.
37       Reduction += InlineConstants::InstrCost*Instrs*(NumSucc-1)/NumSucc;
38     } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
39       // Turning an indirect call into a direct call is a BIG win
40       if (CI->getCalledValue() == V)
41         Reduction += InlineConstants::IndirectCallBonus;
42     } else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) {
43       // Turning an indirect call into a direct call is a BIG win
44       if (II->getCalledValue() == V)
45         Reduction += InlineConstants::IndirectCallBonus;
46     } else {
47       // Figure out if this instruction will be removed due to simple constant
48       // propagation.
49       Instruction &Inst = cast<Instruction>(*U);
50
51       // We can't constant propagate instructions which have effects or
52       // read memory.
53       //
54       // FIXME: It would be nice to capture the fact that a load from a
55       // pointer-to-constant-global is actually a *really* good thing to zap.
56       // Unfortunately, we don't know the pointer that may get propagated here,
57       // so we can't make this decision.
58       if (Inst.mayReadFromMemory() || Inst.mayHaveSideEffects() ||
59           isa<AllocaInst>(Inst))
60         continue;
61
62       bool AllOperandsConstant = true;
63       for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
64         if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
65           AllOperandsConstant = false;
66           break;
67         }
68
69       if (AllOperandsConstant) {
70         // We will get to remove this instruction...
71         Reduction += InlineConstants::InstrCost;
72
73         // And any other instructions that use it which become constants
74         // themselves.
75         Reduction += CountCodeReductionForConstant(&Inst);
76       }
77     }
78   }
79   return Reduction;
80 }
81
82 // CountCodeReductionForAlloca - Figure out an approximation of how much smaller
83 // the function will be if it is inlined into a context where an argument
84 // becomes an alloca.
85 //
86 unsigned InlineCostAnalyzer::FunctionInfo::
87          CountCodeReductionForAlloca(Value *V) {
88   if (!V->getType()->isPointerTy()) return 0;  // Not a pointer
89   unsigned Reduction = 0;
90   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
91     Instruction *I = cast<Instruction>(*UI);
92     if (isa<LoadInst>(I) || isa<StoreInst>(I))
93       Reduction += InlineConstants::InstrCost;
94     else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
95       // If the GEP has variable indices, we won't be able to do much with it.
96       if (GEP->hasAllConstantIndices())
97         Reduction += CountCodeReductionForAlloca(GEP);
98     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
99       // Track pointer through bitcasts.
100       Reduction += CountCodeReductionForAlloca(BCI);
101     } else {
102       // If there is some other strange instruction, we're not going to be able
103       // to do much if we inline this.
104       return 0;
105     }
106   }
107
108   return Reduction;
109 }
110
111 /// callIsSmall - If a call is likely to lower to a single target instruction,
112 /// or is otherwise deemed small return true.
113 /// TODO: Perhaps calls like memcpy, strcpy, etc?
114 bool llvm::callIsSmall(const Function *F) {
115   if (!F) return false;
116   
117   if (F->hasLocalLinkage()) return false;
118   
119   if (!F->hasName()) return false;
120   
121   StringRef Name = F->getName();
122   
123   // These will all likely lower to a single selection DAG node.
124   if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
125       Name == "fabs" || Name == "fabsf" || Name == "fabsl" ||
126       Name == "sin" || Name == "sinf" || Name == "sinl" ||
127       Name == "cos" || Name == "cosf" || Name == "cosl" ||
128       Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl" )
129     return true;
130   
131   // These are all likely to be optimized into something smaller.
132   if (Name == "pow" || Name == "powf" || Name == "powl" ||
133       Name == "exp2" || Name == "exp2l" || Name == "exp2f" ||
134       Name == "floor" || Name == "floorf" || Name == "ceil" ||
135       Name == "round" || Name == "ffs" || Name == "ffsl" ||
136       Name == "abs" || Name == "labs" || Name == "llabs")
137     return true;
138   
139   return false;
140 }
141
142 /// analyzeBasicBlock - Fill in the current structure with information gleaned
143 /// from the specified block.
144 void CodeMetrics::analyzeBasicBlock(const BasicBlock *BB) {
145   ++NumBlocks;
146   unsigned NumInstsBeforeThisBB = NumInsts;
147   for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
148        II != E; ++II) {
149     if (isa<PHINode>(II)) continue;           // PHI nodes don't count.
150
151     // Special handling for calls.
152     if (isa<CallInst>(II) || isa<InvokeInst>(II)) {
153       if (isa<DbgInfoIntrinsic>(II))
154         continue;  // Debug intrinsics don't count as size.
155       
156       CallSite CS = CallSite::get(const_cast<Instruction*>(&*II));
157       
158       // If this function contains a call to setjmp or _setjmp, never inline
159       // it.  This is a hack because we depend on the user marking their local
160       // variables as volatile if they are live across a setjmp call, and they
161       // probably won't do this in callers.
162       if (Function *F = CS.getCalledFunction()) {
163         if (F->isDeclaration() && 
164             (F->getName() == "setjmp" || F->getName() == "_setjmp"))
165           NeverInline = true;
166        
167         // If this call is to function itself, then the function is recursive.
168         // Inlining it into other functions is a bad idea, because this is
169         // basically just a form of loop peeling, and our metrics aren't useful
170         // for that case.
171         if (F == BB->getParent())
172           NeverInline = true;
173       }
174
175       if (!isa<IntrinsicInst>(II) && !callIsSmall(CS.getCalledFunction())) {
176         // Each argument to a call takes on average one instruction to set up.
177         NumInsts += CS.arg_size();
178
179         // We don't want inline asm to count as a call - that would prevent loop
180         // unrolling. The argument setup cost is still real, though.
181         if (!isa<InlineAsm>(CS.getCalledValue()))
182           ++NumCalls;
183       }
184     }
185     
186     if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
187       if (!AI->isStaticAlloca())
188         this->usesDynamicAlloca = true;
189     }
190
191     if (isa<ExtractElementInst>(II) || II->getType()->isVectorTy())
192       ++NumVectorInsts; 
193     
194     if (const CastInst *CI = dyn_cast<CastInst>(II)) {
195       // Noop casts, including ptr <-> int,  don't count.
196       if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) || 
197           isa<PtrToIntInst>(CI))
198         continue;
199       // Result of a cmp instruction is often extended (to be used by other
200       // cmp instructions, logical or return instructions). These are usually
201       // nop on most sane targets.
202       if (isa<CmpInst>(CI->getOperand(0)))
203         continue;
204     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(II)){
205       // If a GEP has all constant indices, it will probably be folded with
206       // a load/store.
207       if (GEPI->hasAllConstantIndices())
208         continue;
209     }
210
211     ++NumInsts;
212   }
213   
214   if (isa<ReturnInst>(BB->getTerminator()))
215     ++NumRets;
216   
217   // We never want to inline functions that contain an indirectbr.  This is
218   // incorrect because all the blockaddress's (in static global initializers
219   // for example) would be referring to the original function, and this indirect
220   // jump would jump from the inlined copy of the function into the original
221   // function which is extremely undefined behavior.
222   if (isa<IndirectBrInst>(BB->getTerminator()))
223     NeverInline = true;
224
225   // Remember NumInsts for this BB.
226   NumBBInsts[BB] = NumInsts - NumInstsBeforeThisBB;
227 }
228
229 /// analyzeFunction - Fill in the current structure with information gleaned
230 /// from the specified function.
231 void CodeMetrics::analyzeFunction(Function *F) {
232   // Look at the size of the callee.
233   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
234     analyzeBasicBlock(&*BB);
235 }
236
237 /// analyzeFunction - Fill in the current structure with information gleaned
238 /// from the specified function.
239 void InlineCostAnalyzer::FunctionInfo::analyzeFunction(Function *F) {
240   Metrics.analyzeFunction(F);
241
242   // A function with exactly one return has it removed during the inlining
243   // process (see InlineFunction), so don't count it.
244   // FIXME: This knowledge should really be encoded outside of FunctionInfo.
245   if (Metrics.NumRets==1)
246     --Metrics.NumInsts;
247
248   // Don't bother calculating argument weights if we are never going to inline
249   // the function anyway.
250   if (Metrics.NeverInline)
251     return;
252
253   // Check out all of the arguments to the function, figuring out how much
254   // code can be eliminated if one of the arguments is a constant.
255   ArgumentWeights.reserve(F->arg_size());
256   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
257     ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
258                                       CountCodeReductionForAlloca(I)));
259 }
260
261 // getInlineCost - The heuristic used to determine if we should inline the
262 // function call or not.
263 //
264 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS,
265                                SmallPtrSet<const Function*, 16> &NeverInline) {
266   return getInlineCost(CS, CS.getCalledFunction(), NeverInline);
267 }
268
269 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS,
270                                Function *Callee,
271                                SmallPtrSet<const Function*, 16> &NeverInline) {
272   Instruction *TheCall = CS.getInstruction();
273   Function *Caller = TheCall->getParent()->getParent();
274   bool isDirectCall = CS.getCalledFunction() == Callee;
275
276   // Don't inline functions which can be redefined at link-time to mean
277   // something else.  Don't inline functions marked noinline or call sites
278   // marked noinline.
279   if (Callee->mayBeOverridden() ||
280       Callee->hasFnAttr(Attribute::NoInline) || NeverInline.count(Callee) ||
281       CS.isNoInline())
282     return llvm::InlineCost::getNever();
283
284   // InlineCost - This value measures how good of an inline candidate this call
285   // site is to inline.  A lower inline cost make is more likely for the call to
286   // be inlined.  This value may go negative.
287   //
288   int InlineCost = 0;
289
290   // If there is only one call of the function, and it has internal linkage,
291   // make it almost guaranteed to be inlined.
292   //
293   if (Callee->hasLocalLinkage() && Callee->hasOneUse() && isDirectCall)
294     InlineCost += InlineConstants::LastCallToStaticBonus;
295   
296   // If this function uses the coldcc calling convention, prefer not to inline
297   // it.
298   if (Callee->getCallingConv() == CallingConv::Cold)
299     InlineCost += InlineConstants::ColdccPenalty;
300   
301   // If the instruction after the call, or if the normal destination of the
302   // invoke is an unreachable instruction, the function is noreturn.  As such,
303   // there is little point in inlining this.
304   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
305     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
306       InlineCost += InlineConstants::NoreturnPenalty;
307   } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
308     InlineCost += InlineConstants::NoreturnPenalty;
309   
310   // Get information about the callee.
311   FunctionInfo *CalleeFI = &CachedFunctionInfo[Callee];
312   
313   // If we haven't calculated this information yet, do so now.
314   if (CalleeFI->Metrics.NumBlocks == 0)
315     CalleeFI->analyzeFunction(Callee);
316
317   // If we should never inline this, return a huge cost.
318   if (CalleeFI->Metrics.NeverInline)
319     return InlineCost::getNever();
320
321   // FIXME: It would be nice to kill off CalleeFI->NeverInline. Then we
322   // could move this up and avoid computing the FunctionInfo for
323   // things we are going to just return always inline for. This
324   // requires handling setjmp somewhere else, however.
325   if (!Callee->isDeclaration() && Callee->hasFnAttr(Attribute::AlwaysInline))
326     return InlineCost::getAlways();
327     
328   if (CalleeFI->Metrics.usesDynamicAlloca) {
329     // Get infomation about the caller.
330     FunctionInfo &CallerFI = CachedFunctionInfo[Caller];
331
332     // If we haven't calculated this information yet, do so now.
333     if (CallerFI.Metrics.NumBlocks == 0) {
334       CallerFI.analyzeFunction(Caller);
335      
336       // Recompute the CalleeFI pointer, getting Caller could have invalidated
337       // it.
338       CalleeFI = &CachedFunctionInfo[Callee];
339     }
340
341     // Don't inline a callee with dynamic alloca into a caller without them.
342     // Functions containing dynamic alloca's are inefficient in various ways;
343     // don't create more inefficiency.
344     if (!CallerFI.Metrics.usesDynamicAlloca)
345       return InlineCost::getNever();
346   }
347
348   // Add to the inline quality for properties that make the call valuable to
349   // inline.  This includes factors that indicate that the result of inlining
350   // the function will be optimizable.  Currently this just looks at arguments
351   // passed into the function.
352   //
353   unsigned ArgNo = 0;
354   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
355        I != E; ++I, ++ArgNo) {
356     // Each argument passed in has a cost at both the caller and the callee
357     // sides.  Measurements show that each argument costs about the same as an
358     // instruction.
359     InlineCost -= InlineConstants::InstrCost;
360
361     // If an alloca is passed in, inlining this function is likely to allow
362     // significant future optimization possibilities (like scalar promotion, and
363     // scalarization), so encourage the inlining of the function.
364     //
365     if (isa<AllocaInst>(I)) {
366       if (ArgNo < CalleeFI->ArgumentWeights.size())
367         InlineCost -= CalleeFI->ArgumentWeights[ArgNo].AllocaWeight;
368
369       // If this is a constant being passed into the function, use the argument
370       // weights calculated for the callee to determine how much will be folded
371       // away with this information.
372     } else if (isa<Constant>(I)) {
373       if (ArgNo < CalleeFI->ArgumentWeights.size())
374         InlineCost -= CalleeFI->ArgumentWeights[ArgNo].ConstantWeight;
375     }
376   }
377   
378   // Now that we have considered all of the factors that make the call site more
379   // likely to be inlined, look at factors that make us not want to inline it.
380
381   // Calls usually take a long time, so they make the inlining gain smaller.
382   InlineCost += CalleeFI->Metrics.NumCalls * InlineConstants::CallPenalty;
383
384   // Look at the size of the callee. Each instruction counts as 5.
385   InlineCost += CalleeFI->Metrics.NumInsts*InlineConstants::InstrCost;
386
387   return llvm::InlineCost::get(InlineCost);
388 }
389
390 // getInlineFudgeFactor - Return a > 1.0 factor if the inliner should use a
391 // higher threshold to determine if the function call should be inlined.
392 float InlineCostAnalyzer::getInlineFudgeFactor(CallSite CS) {
393   Function *Callee = CS.getCalledFunction();
394   
395   // Get information about the callee.
396   FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
397   
398   // If we haven't calculated this information yet, do so now.
399   if (CalleeFI.Metrics.NumBlocks == 0)
400     CalleeFI.analyzeFunction(Callee);
401
402   float Factor = 1.0f;
403   // Single BB functions are often written to be inlined.
404   if (CalleeFI.Metrics.NumBlocks == 1)
405     Factor += 0.5f;
406
407   // Be more aggressive if the function contains a good chunk (if it mades up
408   // at least 10% of the instructions) of vector instructions.
409   if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/2)
410     Factor += 2.0f;
411   else if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/10)
412     Factor += 1.5f;
413   return Factor;
414 }
415
416 /// growCachedCostInfo - update the cached cost info for Caller after Callee has
417 /// been inlined.
418 void
419 InlineCostAnalyzer::growCachedCostInfo(Function *Caller, Function *Callee) {
420   CodeMetrics &CallerMetrics = CachedFunctionInfo[Caller].Metrics;
421
422   // For small functions we prefer to recalculate the cost for better accuracy.
423   if (CallerMetrics.NumBlocks < 10 || CallerMetrics.NumInsts < 1000) {
424     resetCachedCostInfo(Caller);
425     return;
426   }
427
428   // For large functions, we can save a lot of computation time by skipping
429   // recalculations.
430   if (CallerMetrics.NumCalls > 0)
431     --CallerMetrics.NumCalls;
432
433   if (Callee == 0) return;
434   
435   CodeMetrics &CalleeMetrics = CachedFunctionInfo[Callee].Metrics;
436
437   // If we don't have metrics for the callee, don't recalculate them just to
438   // update an approximation in the caller.  Instead, just recalculate the
439   // caller info from scratch.
440   if (CalleeMetrics.NumBlocks == 0) {
441     resetCachedCostInfo(Caller);
442     return;
443   }
444   
445   // Since CalleeMetrics were already calculated, we know that the CallerMetrics
446   // reference isn't invalidated: both were in the DenseMap.  
447   CallerMetrics.NeverInline |= CalleeMetrics.NeverInline;
448   CallerMetrics.usesDynamicAlloca |= CalleeMetrics.usesDynamicAlloca;
449
450   CallerMetrics.NumInsts += CalleeMetrics.NumInsts;
451   CallerMetrics.NumBlocks += CalleeMetrics.NumBlocks;
452   CallerMetrics.NumCalls += CalleeMetrics.NumCalls;
453   CallerMetrics.NumVectorInsts += CalleeMetrics.NumVectorInsts;
454   CallerMetrics.NumRets += CalleeMetrics.NumRets;
455
456   // analyzeBasicBlock counts each function argument as an inst.
457   if (CallerMetrics.NumInsts >= Callee->arg_size())
458     CallerMetrics.NumInsts -= Callee->arg_size();
459   else
460     CallerMetrics.NumInsts = 0;
461   
462   // We are not updating the argument weights. We have already determined that
463   // Caller is a fairly large function, so we accept the loss of precision.
464 }
465
466 /// clear - empty the cache of inline costs
467 void InlineCostAnalyzer::clear() {
468   CachedFunctionInfo.clear();
469 }