1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements inline cost analysis.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "inline-cost"
15 #include "llvm/Analysis/InlineCost.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/CallSite.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Operator.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/DataLayout.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
36 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
40 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
41 typedef InstVisitor<CallAnalyzer, bool> Base;
42 friend class InstVisitor<CallAnalyzer, bool>;
44 // DataLayout if available, or null.
45 const DataLayout *const TD;
47 // The called function.
52 const bool AlwaysInline;
54 bool IsCallerRecursive;
56 bool ExposesReturnsTwice;
57 bool HasDynamicAlloca;
58 /// Number of bytes allocated statically by the callee.
59 uint64_t AllocatedSize;
60 unsigned NumInstructions, NumVectorInstructions;
61 int FiftyPercentVectorBonus, TenPercentVectorBonus;
64 // While we walk the potentially-inlined instructions, we build up and
65 // maintain a mapping of simplified values specific to this callsite. The
66 // idea is to propagate any special information we have about arguments to
67 // this call through the inlinable section of the function, and account for
68 // likely simplifications post-inlining. The most important aspect we track
69 // is CFG altering simplifications -- when we prove a basic block dead, that
70 // can cause dramatic shifts in the cost of inlining a function.
71 DenseMap<Value *, Constant *> SimplifiedValues;
73 // Keep track of the values which map back (through function arguments) to
74 // allocas on the caller stack which could be simplified through SROA.
75 DenseMap<Value *, Value *> SROAArgValues;
77 // The mapping of caller Alloca values to their accumulated cost savings. If
78 // we have to disable SROA for one of the allocas, this tells us how much
79 // cost must be added.
80 DenseMap<Value *, int> SROAArgCosts;
82 // Keep track of values which map to a pointer base and constant offset.
83 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
85 // Custom simplification helper routines.
86 bool isAllocaDerivedArg(Value *V);
87 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
88 DenseMap<Value *, int>::iterator &CostIt);
89 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
90 void disableSROA(Value *V);
91 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
93 bool handleSROACandidate(bool IsSROAValid,
94 DenseMap<Value *, int>::iterator CostIt,
96 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
97 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
98 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
100 // Custom analysis routines.
101 bool analyzeBlock(BasicBlock *BB);
103 // Disable several entry points to the visitor so we don't accidentally use
104 // them by declaring but not defining them here.
105 void visit(Module *); void visit(Module &);
106 void visit(Function *); void visit(Function &);
107 void visit(BasicBlock *); void visit(BasicBlock &);
109 // Provide base case for our instruction visit.
110 bool visitInstruction(Instruction &I);
112 // Our visit overrides.
113 bool visitAlloca(AllocaInst &I);
114 bool visitPHI(PHINode &I);
115 bool visitGetElementPtr(GetElementPtrInst &I);
116 bool visitBitCast(BitCastInst &I);
117 bool visitPtrToInt(PtrToIntInst &I);
118 bool visitIntToPtr(IntToPtrInst &I);
119 bool visitCastInst(CastInst &I);
120 bool visitUnaryInstruction(UnaryInstruction &I);
121 bool visitICmp(ICmpInst &I);
122 bool visitSub(BinaryOperator &I);
123 bool visitBinaryOperator(BinaryOperator &I);
124 bool visitLoad(LoadInst &I);
125 bool visitStore(StoreInst &I);
126 bool visitCallSite(CallSite CS);
129 CallAnalyzer(const DataLayout *TD, Function &Callee, int Threshold)
130 : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
131 AlwaysInline(F.getFnAttributes().hasAttribute(Attributes::AlwaysInline)),
132 IsCallerRecursive(false), IsRecursiveCall(false),
133 ExposesReturnsTwice(false), HasDynamicAlloca(false), AllocatedSize(0),
134 NumInstructions(0), NumVectorInstructions(0),
135 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
136 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
137 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
138 NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLost(0) {
141 bool analyzeCall(CallSite CS);
143 int getThreshold() { return Threshold; }
144 int getCost() { return Cost; }
145 bool isAlwaysInline() { return AlwaysInline; }
147 // Keep a bunch of stats about the cost savings found so we can print them
148 // out when debugging.
149 unsigned NumConstantArgs;
150 unsigned NumConstantOffsetPtrArgs;
151 unsigned NumAllocaArgs;
152 unsigned NumConstantPtrCmps;
153 unsigned NumConstantPtrDiffs;
154 unsigned NumInstructionsSimplified;
155 unsigned SROACostSavings;
156 unsigned SROACostSavingsLost;
163 /// \brief Test whether the given value is an Alloca-derived function argument.
164 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
165 return SROAArgValues.count(V);
168 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
169 /// Returns false if V does not map to a SROA-candidate.
170 bool CallAnalyzer::lookupSROAArgAndCost(
171 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
172 if (SROAArgValues.empty() || SROAArgCosts.empty())
175 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
176 if (ArgIt == SROAArgValues.end())
180 CostIt = SROAArgCosts.find(Arg);
181 return CostIt != SROAArgCosts.end();
184 /// \brief Disable SROA for the candidate marked by this cost iterator.
186 /// This marks the candidate as no longer viable for SROA, and adds the cost
187 /// savings associated with it back into the inline cost measurement.
188 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
189 // If we're no longer able to perform SROA we need to undo its cost savings
190 // and prevent subsequent analysis.
191 Cost += CostIt->second;
192 SROACostSavings -= CostIt->second;
193 SROACostSavingsLost += CostIt->second;
194 SROAArgCosts.erase(CostIt);
197 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
198 void CallAnalyzer::disableSROA(Value *V) {
200 DenseMap<Value *, int>::iterator CostIt;
201 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
205 /// \brief Accumulate the given cost for a particular SROA candidate.
206 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
207 int InstructionCost) {
208 CostIt->second += InstructionCost;
209 SROACostSavings += InstructionCost;
212 /// \brief Helper for the common pattern of handling a SROA candidate.
213 /// Either accumulates the cost savings if the SROA remains valid, or disables
214 /// SROA for the candidate.
215 bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
216 DenseMap<Value *, int>::iterator CostIt,
217 int InstructionCost) {
219 accumulateSROACost(CostIt, InstructionCost);
227 /// \brief Check whether a GEP's indices are all constant.
229 /// Respects any simplified values known during the analysis of this callsite.
230 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
231 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
232 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
238 /// \brief Accumulate a constant GEP offset into an APInt if possible.
240 /// Returns false if unable to compute the offset for any reason. Respects any
241 /// simplified values known during the analysis of this callsite.
242 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
246 unsigned AS = GEP.getPointerAddressSpace();
247 unsigned IntPtrWidth = TD->getPointerSizeInBits(AS);
248 assert(IntPtrWidth == Offset.getBitWidth());
250 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
252 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
254 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
255 OpC = dyn_cast<ConstantInt>(SimpleOp);
258 if (OpC->isZero()) continue;
260 // Handle a struct index, which adds its field offset to the pointer.
261 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
262 unsigned ElementIdx = OpC->getZExtValue();
263 const StructLayout *SL = TD->getStructLayout(STy);
264 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
268 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
269 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
274 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
275 // FIXME: Check whether inlining will turn a dynamic alloca into a static
276 // alloca, and handle that case.
278 // Accumulate the allocated size.
279 if (I.isStaticAlloca()) {
280 Type *Ty = I.getAllocatedType();
281 AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
282 Ty->getPrimitiveSizeInBits());
285 // We will happily inline static alloca instructions or dynamic alloca
286 // instructions in always-inline situations.
287 if (AlwaysInline || I.isStaticAlloca())
288 return Base::visitAlloca(I);
290 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
291 // a variety of reasons, and so we would like to not inline them into
292 // functions which don't currently have a dynamic alloca. This simply
293 // disables inlining altogether in the presence of a dynamic alloca.
294 HasDynamicAlloca = true;
298 bool CallAnalyzer::visitPHI(PHINode &I) {
299 // FIXME: We should potentially be tracking values through phi nodes,
300 // especially when they collapse to a single value due to deleted CFG edges
303 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
304 // though we don't want to propagate it's bonuses. The idea is to disable
305 // SROA if it *might* be used in an inappropriate manner.
307 // Phi nodes are always zero-cost.
311 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
313 DenseMap<Value *, int>::iterator CostIt;
314 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
317 // Try to fold GEPs of constant-offset call site argument pointers. This
318 // requires target data and inbounds GEPs.
319 if (TD && I.isInBounds()) {
320 // Check if we have a base + offset for the pointer.
321 Value *Ptr = I.getPointerOperand();
322 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
323 if (BaseAndOffset.first) {
324 // Check if the offset of this GEP is constant, and if so accumulate it
326 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
327 // Non-constant GEPs aren't folded, and disable SROA.
333 // Add the result as a new mapping to Base + Offset.
334 ConstantOffsetPtrs[&I] = BaseAndOffset;
336 // Also handle SROA candidates here, we already know that the GEP is
337 // all-constant indexed.
339 SROAArgValues[&I] = SROAArg;
345 if (isGEPOffsetConstant(I)) {
347 SROAArgValues[&I] = SROAArg;
349 // Constant GEPs are modeled as free.
353 // Variable GEPs will require math and will disable SROA.
359 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
360 // Propagate constants through bitcasts.
361 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
362 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
363 SimplifiedValues[&I] = C;
367 // Track base/offsets through casts
368 std::pair<Value *, APInt> BaseAndOffset
369 = ConstantOffsetPtrs.lookup(I.getOperand(0));
370 // Casts don't change the offset, just wrap it up.
371 if (BaseAndOffset.first)
372 ConstantOffsetPtrs[&I] = BaseAndOffset;
374 // Also look for SROA candidates here.
376 DenseMap<Value *, int>::iterator CostIt;
377 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
378 SROAArgValues[&I] = SROAArg;
380 // Bitcasts are always zero cost.
384 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
385 // Propagate constants through ptrtoint.
386 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
387 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
388 SimplifiedValues[&I] = C;
392 // Track base/offset pairs when converted to a plain integer provided the
393 // integer is large enough to represent the pointer.
394 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
395 unsigned AS = I.getPointerAddressSpace();
396 if (TD && IntegerSize >= TD->getPointerSizeInBits(AS)) {
397 std::pair<Value *, APInt> BaseAndOffset
398 = ConstantOffsetPtrs.lookup(I.getOperand(0));
399 if (BaseAndOffset.first)
400 ConstantOffsetPtrs[&I] = BaseAndOffset;
403 // This is really weird. Technically, ptrtoint will disable SROA. However,
404 // unless that ptrtoint is *used* somewhere in the live basic blocks after
405 // inlining, it will be nuked, and SROA should proceed. All of the uses which
406 // would block SROA would also block SROA if applied directly to a pointer,
407 // and so we can just add the integer in here. The only places where SROA is
408 // preserved either cannot fire on an integer, or won't in-and-of themselves
409 // disable SROA (ext) w/o some later use that we would see and disable.
411 DenseMap<Value *, int>::iterator CostIt;
412 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
413 SROAArgValues[&I] = SROAArg;
415 return isInstructionFree(&I, TD);
418 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
419 // Propagate constants through ptrtoint.
420 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
421 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
422 SimplifiedValues[&I] = C;
426 // Track base/offset pairs when round-tripped through a pointer without
427 // modifications provided the integer is not too large.
428 Value *Op = I.getOperand(0);
429 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
430 unsigned AS = I.getAddressSpace();
431 if (TD && IntegerSize <= TD->getPointerSizeInBits(AS)) {
432 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
433 if (BaseAndOffset.first)
434 ConstantOffsetPtrs[&I] = BaseAndOffset;
437 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
439 DenseMap<Value *, int>::iterator CostIt;
440 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
441 SROAArgValues[&I] = SROAArg;
443 return isInstructionFree(&I, TD);
446 bool CallAnalyzer::visitCastInst(CastInst &I) {
447 // Propagate constants through ptrtoint.
448 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
449 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
450 SimplifiedValues[&I] = C;
454 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
455 disableSROA(I.getOperand(0));
457 return isInstructionFree(&I, TD);
460 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
461 Value *Operand = I.getOperand(0);
462 Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
463 if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
464 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
466 SimplifiedValues[&I] = C;
470 // Disable any SROA on the argument to arbitrary unary operators.
471 disableSROA(Operand);
476 bool CallAnalyzer::visitICmp(ICmpInst &I) {
477 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
478 // First try to handle simplified comparisons.
479 if (!isa<Constant>(LHS))
480 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
482 if (!isa<Constant>(RHS))
483 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
485 if (Constant *CLHS = dyn_cast<Constant>(LHS))
486 if (Constant *CRHS = dyn_cast<Constant>(RHS))
487 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
488 SimplifiedValues[&I] = C;
492 // Otherwise look for a comparison between constant offset pointers with
494 Value *LHSBase, *RHSBase;
495 APInt LHSOffset, RHSOffset;
496 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
498 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
499 if (RHSBase && LHSBase == RHSBase) {
500 // We have common bases, fold the icmp to a constant based on the
502 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
503 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
504 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
505 SimplifiedValues[&I] = C;
506 ++NumConstantPtrCmps;
512 // If the comparison is an equality comparison with null, we can simplify it
513 // for any alloca-derived argument.
514 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
515 if (isAllocaDerivedArg(I.getOperand(0))) {
516 // We can actually predict the result of comparisons between an
517 // alloca-derived value and null. Note that this fires regardless of
519 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
520 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
521 : ConstantInt::getFalse(I.getType());
525 // Finally check for SROA candidates in comparisons.
527 DenseMap<Value *, int>::iterator CostIt;
528 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
529 if (isa<ConstantPointerNull>(I.getOperand(1))) {
530 accumulateSROACost(CostIt, InlineConstants::InstrCost);
540 bool CallAnalyzer::visitSub(BinaryOperator &I) {
541 // Try to handle a special case: we can fold computing the difference of two
542 // constant-related pointers.
543 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
544 Value *LHSBase, *RHSBase;
545 APInt LHSOffset, RHSOffset;
546 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
548 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
549 if (RHSBase && LHSBase == RHSBase) {
550 // We have common bases, fold the subtract to a constant based on the
552 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
553 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
554 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
555 SimplifiedValues[&I] = C;
556 ++NumConstantPtrDiffs;
562 // Otherwise, fall back to the generic logic for simplifying and handling
564 return Base::visitSub(I);
567 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
568 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
569 if (!isa<Constant>(LHS))
570 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
572 if (!isa<Constant>(RHS))
573 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
575 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
576 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
577 SimplifiedValues[&I] = C;
581 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
588 bool CallAnalyzer::visitLoad(LoadInst &I) {
590 DenseMap<Value *, int>::iterator CostIt;
591 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
593 accumulateSROACost(CostIt, InlineConstants::InstrCost);
603 bool CallAnalyzer::visitStore(StoreInst &I) {
605 DenseMap<Value *, int>::iterator CostIt;
606 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
608 accumulateSROACost(CostIt, InlineConstants::InstrCost);
618 bool CallAnalyzer::visitCallSite(CallSite CS) {
619 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
620 !F.getFnAttributes().hasAttribute(Attributes::ReturnsTwice)) {
621 // This aborts the entire analysis.
622 ExposesReturnsTwice = true;
626 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
627 switch (II->getIntrinsicID()) {
629 return Base::visitCallSite(CS);
631 case Intrinsic::memset:
632 case Intrinsic::memcpy:
633 case Intrinsic::memmove:
634 // SROA can usually chew through these intrinsics, but they aren't free.
639 if (Function *F = CS.getCalledFunction()) {
640 if (F == CS.getInstruction()->getParent()->getParent()) {
641 // This flag will fully abort the analysis, so don't bother with anything
643 IsRecursiveCall = true;
647 if (!callIsSmall(CS)) {
648 // We account for the average 1 instruction per call argument setup
650 Cost += CS.arg_size() * InlineConstants::InstrCost;
652 // Everything other than inline ASM will also have a significant cost
653 // merely from making the call.
654 if (!isa<InlineAsm>(CS.getCalledValue()))
655 Cost += InlineConstants::CallPenalty;
658 return Base::visitCallSite(CS);
661 // Otherwise we're in a very special case -- an indirect function call. See
662 // if we can be particularly clever about this.
663 Value *Callee = CS.getCalledValue();
665 // First, pay the price of the argument setup. We account for the average
666 // 1 instruction per call argument setup here.
667 Cost += CS.arg_size() * InlineConstants::InstrCost;
669 // Next, check if this happens to be an indirect function call to a known
670 // function in this inline context. If not, we've done all we can.
671 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
673 return Base::visitCallSite(CS);
675 // If we have a constant that we are calling as a function, we can peer
676 // through it and see the function target. This happens not infrequently
677 // during devirtualization and so we want to give it a hefty bonus for
678 // inlining, but cap that bonus in the event that inlining wouldn't pan
679 // out. Pretend to inline the function, with a custom threshold.
680 CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
681 if (CA.analyzeCall(CS)) {
682 // We were able to inline the indirect call! Subtract the cost from the
683 // bonus we want to apply, but don't go below zero.
684 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
687 return Base::visitCallSite(CS);
690 bool CallAnalyzer::visitInstruction(Instruction &I) {
691 // Some instructions are free. All of the free intrinsics can also be
692 // handled by SROA, etc.
693 if (isInstructionFree(&I, TD))
696 // We found something we don't understand or can't handle. Mark any SROA-able
697 // values in the operand list as no longer viable.
698 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
705 /// \brief Analyze a basic block for its contribution to the inline cost.
707 /// This method walks the analyzer over every instruction in the given basic
708 /// block and accounts for their cost during inlining at this callsite. It
709 /// aborts early if the threshold has been exceeded or an impossible to inline
710 /// construct has been detected. It returns false if inlining is no longer
711 /// viable, and true if inlining remains viable.
712 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
713 for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
716 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
717 ++NumVectorInstructions;
719 // If the instruction simplified to a constant, there is no cost to this
720 // instruction. Visit the instructions using our InstVisitor to account for
721 // all of the per-instruction logic. The visit tree returns true if we
722 // consumed the instruction in any way, and false if the instruction's base
723 // cost should count against inlining.
725 ++NumInstructionsSimplified;
727 Cost += InlineConstants::InstrCost;
729 // If the visit this instruction detected an uninlinable pattern, abort.
730 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
733 // If the caller is a recursive function then we don't want to inline
734 // functions which allocate a lot of stack space because it would increase
735 // the caller stack usage dramatically.
736 if (IsCallerRecursive &&
737 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
740 if (NumVectorInstructions > NumInstructions/2)
741 VectorBonus = FiftyPercentVectorBonus;
742 else if (NumVectorInstructions > NumInstructions/10)
743 VectorBonus = TenPercentVectorBonus;
747 // Check if we've past the threshold so we don't spin in huge basic
748 // blocks that will never inline.
749 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
756 /// \brief Compute the base pointer and cumulative constant offsets for V.
758 /// This strips all constant offsets off of V, leaving it the base pointer, and
759 /// accumulates the total constant offset applied in the returned constant. It
760 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
761 /// no constant offsets applied.
762 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
763 if (!TD || !V->getType()->isPointerTy())
766 unsigned AS = cast<PointerType>(V->getType())->getAddressSpace();;
767 unsigned IntPtrWidth = TD->getPointerSizeInBits(AS);
768 APInt Offset = APInt::getNullValue(IntPtrWidth);
770 // Even though we don't look through PHI nodes, we could be called on an
771 // instruction in an unreachable block, which may be on a cycle.
772 SmallPtrSet<Value *, 4> Visited;
775 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
776 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
778 V = GEP->getPointerOperand();
779 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
780 V = cast<Operator>(V)->getOperand(0);
781 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
782 if (GA->mayBeOverridden())
784 V = GA->getAliasee();
788 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
789 } while (Visited.insert(V));
791 Type *IntPtrTy = TD->getIntPtrType(V->getType());
792 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
795 /// \brief Analyze a call site for potential inlining.
797 /// Returns true if inlining this call is viable, and false if it is not
798 /// viable. It computes the cost and adjusts the threshold based on numerous
799 /// factors and heuristics. If this method returns false but the computed cost
800 /// is below the computed threshold, then inlining was forcibly disabled by
801 /// some artifact of the rountine.
802 bool CallAnalyzer::analyzeCall(CallSite CS) {
805 // Track whether the post-inlining function would have more than one basic
806 // block. A single basic block is often intended for inlining. Balloon the
807 // threshold by 50% until we pass the single-BB phase.
808 bool SingleBB = true;
809 int SingleBBBonus = Threshold / 2;
810 Threshold += SingleBBBonus;
812 // Unless we are always-inlining, perform some tweaks to the cost and
813 // threshold based on the direct callsite information.
815 // We want to more aggressively inline vector-dense kernels, so up the
816 // threshold, and we'll lower it if the % of vector instructions gets too
818 assert(NumInstructions == 0);
819 assert(NumVectorInstructions == 0);
820 FiftyPercentVectorBonus = Threshold;
821 TenPercentVectorBonus = Threshold / 2;
823 // Give out bonuses per argument, as the instructions setting them up will
824 // be gone after inlining.
825 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
826 if (TD && CS.isByValArgument(I)) {
827 // We approximate the number of loads and stores needed by dividing the
828 // size of the byval type by the target's pointer size.
829 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
830 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
831 unsigned PointerSize = TD->getTypeSizeInBits(PTy);
833 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
835 // If it generates more than 8 stores it is likely to be expanded as an
836 // inline memcpy so we take that as an upper bound. Otherwise we assume
837 // one load and one store per word copied.
838 // FIXME: The maxStoresPerMemcpy setting from the target should be used
839 // here instead of a magic number of 8, but it's not available via
841 NumStores = std::min(NumStores, 8U);
843 Cost -= 2 * NumStores * InlineConstants::InstrCost;
845 // For non-byval arguments subtract off one instruction per call
847 Cost -= InlineConstants::InstrCost;
851 // If there is only one call of the function, and it has internal linkage,
852 // the cost of inlining it drops dramatically.
853 if (F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction())
854 Cost += InlineConstants::LastCallToStaticBonus;
856 // If the instruction after the call, or if the normal destination of the
857 // invoke is an unreachable instruction, the function is noreturn. As such,
858 // there is little point in inlining this unless there is literally zero
860 Instruction *Instr = CS.getInstruction();
861 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
862 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
864 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
867 // If this function uses the coldcc calling convention, prefer not to inline
869 if (F.getCallingConv() == CallingConv::Cold)
870 Cost += InlineConstants::ColdccPenalty;
872 // Check if we're done. This can happen due to bonuses and penalties.
873 if (Cost > Threshold)
880 Function *Caller = CS.getInstruction()->getParent()->getParent();
881 // Check if the caller function is recursive itself.
882 for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
884 CallSite Site(cast<Value>(*U));
887 Instruction *I = Site.getInstruction();
888 if (I->getParent()->getParent() == Caller) {
889 IsCallerRecursive = true;
894 // Track whether we've seen a return instruction. The first return
895 // instruction is free, as at least one will usually disappear in inlining.
896 bool HasReturn = false;
898 // Populate our simplified values by mapping from function arguments to call
899 // arguments with known important simplifications.
900 CallSite::arg_iterator CAI = CS.arg_begin();
901 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
902 FAI != FAE; ++FAI, ++CAI) {
903 assert(CAI != CS.arg_end());
904 if (Constant *C = dyn_cast<Constant>(CAI))
905 SimplifiedValues[FAI] = C;
907 Value *PtrArg = *CAI;
908 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
909 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
911 // We can SROA any pointer arguments derived from alloca instructions.
912 if (isa<AllocaInst>(PtrArg)) {
913 SROAArgValues[FAI] = PtrArg;
914 SROAArgCosts[PtrArg] = 0;
918 NumConstantArgs = SimplifiedValues.size();
919 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
920 NumAllocaArgs = SROAArgValues.size();
922 // The worklist of live basic blocks in the callee *after* inlining. We avoid
923 // adding basic blocks of the callee which can be proven to be dead for this
924 // particular call site in order to get more accurate cost estimates. This
925 // requires a somewhat heavyweight iteration pattern: we need to walk the
926 // basic blocks in a breadth-first order as we insert live successors. To
927 // accomplish this, prioritizing for small iterations because we exit after
928 // crossing our threshold, we use a small-size optimized SetVector.
929 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
930 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
931 BBSetVector BBWorklist;
932 BBWorklist.insert(&F.getEntryBlock());
933 // Note that we *must not* cache the size, this loop grows the worklist.
934 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
935 // Bail out the moment we cross the threshold. This means we'll under-count
936 // the cost, but only when undercounting doesn't matter.
937 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
940 BasicBlock *BB = BBWorklist[Idx];
944 // Handle the terminator cost here where we can track returns and other
945 // function-wide constructs.
946 TerminatorInst *TI = BB->getTerminator();
948 // We never want to inline functions that contain an indirectbr. This is
949 // incorrect because all the blockaddress's (in static global initializers
950 // for example) would be referring to the original function, and this
951 // indirect jump would jump from the inlined copy of the function into the
952 // original function which is extremely undefined behavior.
953 // FIXME: This logic isn't really right; we can safely inline functions
954 // with indirectbr's as long as no other function or global references the
955 // blockaddress of a block within the current function. And as a QOI issue,
956 // if someone is using a blockaddress without an indirectbr, and that
957 // reference somehow ends up in another function or global, we probably
958 // don't want to inline this function.
959 if (isa<IndirectBrInst>(TI))
962 if (!HasReturn && isa<ReturnInst>(TI))
965 Cost += InlineConstants::InstrCost;
967 // Analyze the cost of this block. If we blow through the threshold, this
968 // returns false, and we can bail on out.
969 if (!analyzeBlock(BB)) {
970 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
973 // If the caller is a recursive function then we don't want to inline
974 // functions which allocate a lot of stack space because it would increase
975 // the caller stack usage dramatically.
976 if (IsCallerRecursive &&
977 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
983 // Add in the live successors by first checking whether we have terminator
984 // that may be simplified based on the values simplified by this call.
985 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
986 if (BI->isConditional()) {
987 Value *Cond = BI->getCondition();
988 if (ConstantInt *SimpleCond
989 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
990 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
994 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
995 Value *Cond = SI->getCondition();
996 if (ConstantInt *SimpleCond
997 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
998 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1003 // If we're unable to select a particular successor, just count all of
1005 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1007 BBWorklist.insert(TI->getSuccessor(TIdx));
1009 // If we had any successors at this point, than post-inlining is likely to
1010 // have them as well. Note that we assume any basic blocks which existed
1011 // due to branches or switches which folded above will also fold after
1013 if (SingleBB && TI->getNumSuccessors() > 1) {
1014 // Take off the bonus we applied to the threshold.
1015 Threshold -= SingleBBBonus;
1020 Threshold += VectorBonus;
1022 return AlwaysInline || Cost < Threshold;
1025 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1026 /// \brief Dump stats about this call's analysis.
1027 void CallAnalyzer::dump() {
1028 #define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
1029 DEBUG_PRINT_STAT(NumConstantArgs);
1030 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1031 DEBUG_PRINT_STAT(NumAllocaArgs);
1032 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1033 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1034 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1035 DEBUG_PRINT_STAT(SROACostSavings);
1036 DEBUG_PRINT_STAT(SROACostSavingsLost);
1037 #undef DEBUG_PRINT_STAT
1041 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
1042 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1045 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
1047 // Don't inline functions which can be redefined at link-time to mean
1048 // something else. Don't inline functions marked noinline or call sites
1050 if (!Callee || Callee->mayBeOverridden() ||
1051 Callee->getFnAttributes().hasAttribute(Attributes::NoInline) ||
1053 return llvm::InlineCost::getNever();
1055 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1058 CallAnalyzer CA(TD, *Callee, Threshold);
1059 bool ShouldInline = CA.analyzeCall(CS);
1063 // Check if there was a reason to force inlining or no inlining.
1064 if (!ShouldInline && CA.getCost() < CA.getThreshold())
1065 return InlineCost::getNever();
1066 if (ShouldInline && (CA.isAlwaysInline() ||
1067 CA.getCost() >= CA.getThreshold()))
1068 return InlineCost::getAlways();
1070 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());