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 IntPtrWidth = TD->getPointerSizeInBits();
247 assert(IntPtrWidth == Offset.getBitWidth());
249 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
251 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
253 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
254 OpC = dyn_cast<ConstantInt>(SimpleOp);
257 if (OpC->isZero()) continue;
259 // Handle a struct index, which adds its field offset to the pointer.
260 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
261 unsigned ElementIdx = OpC->getZExtValue();
262 const StructLayout *SL = TD->getStructLayout(STy);
263 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
267 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
268 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
273 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
274 // FIXME: Check whether inlining will turn a dynamic alloca into a static
275 // alloca, and handle that case.
277 // Accumulate the allocated size.
278 if (I.isStaticAlloca()) {
279 Type *Ty = I.getAllocatedType();
280 AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
281 Ty->getPrimitiveSizeInBits());
284 // We will happily inline static alloca instructions or dynamic alloca
285 // instructions in always-inline situations.
286 if (AlwaysInline || I.isStaticAlloca())
287 return Base::visitAlloca(I);
289 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
290 // a variety of reasons, and so we would like to not inline them into
291 // functions which don't currently have a dynamic alloca. This simply
292 // disables inlining altogether in the presence of a dynamic alloca.
293 HasDynamicAlloca = true;
297 bool CallAnalyzer::visitPHI(PHINode &I) {
298 // FIXME: We should potentially be tracking values through phi nodes,
299 // especially when they collapse to a single value due to deleted CFG edges
302 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
303 // though we don't want to propagate it's bonuses. The idea is to disable
304 // SROA if it *might* be used in an inappropriate manner.
306 // Phi nodes are always zero-cost.
310 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
312 DenseMap<Value *, int>::iterator CostIt;
313 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
316 // Try to fold GEPs of constant-offset call site argument pointers. This
317 // requires target data and inbounds GEPs.
318 if (TD && I.isInBounds()) {
319 // Check if we have a base + offset for the pointer.
320 Value *Ptr = I.getPointerOperand();
321 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
322 if (BaseAndOffset.first) {
323 // Check if the offset of this GEP is constant, and if so accumulate it
325 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
326 // Non-constant GEPs aren't folded, and disable SROA.
332 // Add the result as a new mapping to Base + Offset.
333 ConstantOffsetPtrs[&I] = BaseAndOffset;
335 // Also handle SROA candidates here, we already know that the GEP is
336 // all-constant indexed.
338 SROAArgValues[&I] = SROAArg;
344 if (isGEPOffsetConstant(I)) {
346 SROAArgValues[&I] = SROAArg;
348 // Constant GEPs are modeled as free.
352 // Variable GEPs will require math and will disable SROA.
358 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
359 // Propagate constants through bitcasts.
360 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
361 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
362 SimplifiedValues[&I] = C;
366 // Track base/offsets through casts
367 std::pair<Value *, APInt> BaseAndOffset
368 = ConstantOffsetPtrs.lookup(I.getOperand(0));
369 // Casts don't change the offset, just wrap it up.
370 if (BaseAndOffset.first)
371 ConstantOffsetPtrs[&I] = BaseAndOffset;
373 // Also look for SROA candidates here.
375 DenseMap<Value *, int>::iterator CostIt;
376 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
377 SROAArgValues[&I] = SROAArg;
379 // Bitcasts are always zero cost.
383 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
384 // Propagate constants through ptrtoint.
385 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
386 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
387 SimplifiedValues[&I] = C;
391 // Track base/offset pairs when converted to a plain integer provided the
392 // integer is large enough to represent the pointer.
393 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
394 if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
395 std::pair<Value *, APInt> BaseAndOffset
396 = ConstantOffsetPtrs.lookup(I.getOperand(0));
397 if (BaseAndOffset.first)
398 ConstantOffsetPtrs[&I] = BaseAndOffset;
401 // This is really weird. Technically, ptrtoint will disable SROA. However,
402 // unless that ptrtoint is *used* somewhere in the live basic blocks after
403 // inlining, it will be nuked, and SROA should proceed. All of the uses which
404 // would block SROA would also block SROA if applied directly to a pointer,
405 // and so we can just add the integer in here. The only places where SROA is
406 // preserved either cannot fire on an integer, or won't in-and-of themselves
407 // disable SROA (ext) w/o some later use that we would see and disable.
409 DenseMap<Value *, int>::iterator CostIt;
410 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
411 SROAArgValues[&I] = SROAArg;
413 return isInstructionFree(&I, TD);
416 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
417 // Propagate constants through ptrtoint.
418 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
419 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
420 SimplifiedValues[&I] = C;
424 // Track base/offset pairs when round-tripped through a pointer without
425 // modifications provided the integer is not too large.
426 Value *Op = I.getOperand(0);
427 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
428 if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
429 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
430 if (BaseAndOffset.first)
431 ConstantOffsetPtrs[&I] = BaseAndOffset;
434 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
436 DenseMap<Value *, int>::iterator CostIt;
437 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
438 SROAArgValues[&I] = SROAArg;
440 return isInstructionFree(&I, TD);
443 bool CallAnalyzer::visitCastInst(CastInst &I) {
444 // Propagate constants through ptrtoint.
445 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
446 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
447 SimplifiedValues[&I] = C;
451 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
452 disableSROA(I.getOperand(0));
454 return isInstructionFree(&I, TD);
457 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
458 Value *Operand = I.getOperand(0);
459 Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
460 if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
461 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
463 SimplifiedValues[&I] = C;
467 // Disable any SROA on the argument to arbitrary unary operators.
468 disableSROA(Operand);
473 bool CallAnalyzer::visitICmp(ICmpInst &I) {
474 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
475 // First try to handle simplified comparisons.
476 if (!isa<Constant>(LHS))
477 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
479 if (!isa<Constant>(RHS))
480 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
482 if (Constant *CLHS = dyn_cast<Constant>(LHS))
483 if (Constant *CRHS = dyn_cast<Constant>(RHS))
484 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
485 SimplifiedValues[&I] = C;
489 // Otherwise look for a comparison between constant offset pointers with
491 Value *LHSBase, *RHSBase;
492 APInt LHSOffset, RHSOffset;
493 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
495 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
496 if (RHSBase && LHSBase == RHSBase) {
497 // We have common bases, fold the icmp to a constant based on the
499 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
500 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
501 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
502 SimplifiedValues[&I] = C;
503 ++NumConstantPtrCmps;
509 // If the comparison is an equality comparison with null, we can simplify it
510 // for any alloca-derived argument.
511 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
512 if (isAllocaDerivedArg(I.getOperand(0))) {
513 // We can actually predict the result of comparisons between an
514 // alloca-derived value and null. Note that this fires regardless of
516 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
517 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
518 : ConstantInt::getFalse(I.getType());
522 // Finally check for SROA candidates in comparisons.
524 DenseMap<Value *, int>::iterator CostIt;
525 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
526 if (isa<ConstantPointerNull>(I.getOperand(1))) {
527 accumulateSROACost(CostIt, InlineConstants::InstrCost);
537 bool CallAnalyzer::visitSub(BinaryOperator &I) {
538 // Try to handle a special case: we can fold computing the difference of two
539 // constant-related pointers.
540 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
541 Value *LHSBase, *RHSBase;
542 APInt LHSOffset, RHSOffset;
543 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
545 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
546 if (RHSBase && LHSBase == RHSBase) {
547 // We have common bases, fold the subtract to a constant based on the
549 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
550 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
551 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
552 SimplifiedValues[&I] = C;
553 ++NumConstantPtrDiffs;
559 // Otherwise, fall back to the generic logic for simplifying and handling
561 return Base::visitSub(I);
564 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
565 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
566 if (!isa<Constant>(LHS))
567 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
569 if (!isa<Constant>(RHS))
570 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
572 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
573 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
574 SimplifiedValues[&I] = C;
578 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
585 bool CallAnalyzer::visitLoad(LoadInst &I) {
587 DenseMap<Value *, int>::iterator CostIt;
588 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
590 accumulateSROACost(CostIt, InlineConstants::InstrCost);
600 bool CallAnalyzer::visitStore(StoreInst &I) {
602 DenseMap<Value *, int>::iterator CostIt;
603 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
605 accumulateSROACost(CostIt, InlineConstants::InstrCost);
615 bool CallAnalyzer::visitCallSite(CallSite CS) {
616 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
617 !F.getFnAttributes().hasAttribute(Attributes::ReturnsTwice)) {
618 // This aborts the entire analysis.
619 ExposesReturnsTwice = true;
623 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
624 switch (II->getIntrinsicID()) {
626 return Base::visitCallSite(CS);
628 case Intrinsic::memset:
629 case Intrinsic::memcpy:
630 case Intrinsic::memmove:
631 // SROA can usually chew through these intrinsics, but they aren't free.
636 if (Function *F = CS.getCalledFunction()) {
637 if (F == CS.getInstruction()->getParent()->getParent()) {
638 // This flag will fully abort the analysis, so don't bother with anything
640 IsRecursiveCall = true;
644 if (!callIsSmall(CS)) {
645 // We account for the average 1 instruction per call argument setup
647 Cost += CS.arg_size() * InlineConstants::InstrCost;
649 // Everything other than inline ASM will also have a significant cost
650 // merely from making the call.
651 if (!isa<InlineAsm>(CS.getCalledValue()))
652 Cost += InlineConstants::CallPenalty;
655 return Base::visitCallSite(CS);
658 // Otherwise we're in a very special case -- an indirect function call. See
659 // if we can be particularly clever about this.
660 Value *Callee = CS.getCalledValue();
662 // First, pay the price of the argument setup. We account for the average
663 // 1 instruction per call argument setup here.
664 Cost += CS.arg_size() * InlineConstants::InstrCost;
666 // Next, check if this happens to be an indirect function call to a known
667 // function in this inline context. If not, we've done all we can.
668 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
670 return Base::visitCallSite(CS);
672 // If we have a constant that we are calling as a function, we can peer
673 // through it and see the function target. This happens not infrequently
674 // during devirtualization and so we want to give it a hefty bonus for
675 // inlining, but cap that bonus in the event that inlining wouldn't pan
676 // out. Pretend to inline the function, with a custom threshold.
677 CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
678 if (CA.analyzeCall(CS)) {
679 // We were able to inline the indirect call! Subtract the cost from the
680 // bonus we want to apply, but don't go below zero.
681 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
684 return Base::visitCallSite(CS);
687 bool CallAnalyzer::visitInstruction(Instruction &I) {
688 // Some instructions are free. All of the free intrinsics can also be
689 // handled by SROA, etc.
690 if (isInstructionFree(&I, TD))
693 // We found something we don't understand or can't handle. Mark any SROA-able
694 // values in the operand list as no longer viable.
695 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
702 /// \brief Analyze a basic block for its contribution to the inline cost.
704 /// This method walks the analyzer over every instruction in the given basic
705 /// block and accounts for their cost during inlining at this callsite. It
706 /// aborts early if the threshold has been exceeded or an impossible to inline
707 /// construct has been detected. It returns false if inlining is no longer
708 /// viable, and true if inlining remains viable.
709 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
710 for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
713 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
714 ++NumVectorInstructions;
716 // If the instruction simplified to a constant, there is no cost to this
717 // instruction. Visit the instructions using our InstVisitor to account for
718 // all of the per-instruction logic. The visit tree returns true if we
719 // consumed the instruction in any way, and false if the instruction's base
720 // cost should count against inlining.
722 ++NumInstructionsSimplified;
724 Cost += InlineConstants::InstrCost;
726 // If the visit this instruction detected an uninlinable pattern, abort.
727 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
730 // If the caller is a recursive function then we don't want to inline
731 // functions which allocate a lot of stack space because it would increase
732 // the caller stack usage dramatically.
733 if (IsCallerRecursive &&
734 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
737 if (NumVectorInstructions > NumInstructions/2)
738 VectorBonus = FiftyPercentVectorBonus;
739 else if (NumVectorInstructions > NumInstructions/10)
740 VectorBonus = TenPercentVectorBonus;
744 // Check if we've past the threshold so we don't spin in huge basic
745 // blocks that will never inline.
746 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
753 /// \brief Compute the base pointer and cumulative constant offsets for V.
755 /// This strips all constant offsets off of V, leaving it the base pointer, and
756 /// accumulates the total constant offset applied in the returned constant. It
757 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
758 /// no constant offsets applied.
759 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
760 if (!TD || !V->getType()->isPointerTy())
763 unsigned IntPtrWidth = TD->getPointerSizeInBits();
764 APInt Offset = APInt::getNullValue(IntPtrWidth);
766 // Even though we don't look through PHI nodes, we could be called on an
767 // instruction in an unreachable block, which may be on a cycle.
768 SmallPtrSet<Value *, 4> Visited;
771 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
772 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
774 V = GEP->getPointerOperand();
775 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
776 V = cast<Operator>(V)->getOperand(0);
777 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
778 if (GA->mayBeOverridden())
780 V = GA->getAliasee();
784 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
785 } while (Visited.insert(V));
787 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
788 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
791 /// \brief Analyze a call site for potential inlining.
793 /// Returns true if inlining this call is viable, and false if it is not
794 /// viable. It computes the cost and adjusts the threshold based on numerous
795 /// factors and heuristics. If this method returns false but the computed cost
796 /// is below the computed threshold, then inlining was forcibly disabled by
797 /// some artifact of the routine.
798 bool CallAnalyzer::analyzeCall(CallSite CS) {
801 // Track whether the post-inlining function would have more than one basic
802 // block. A single basic block is often intended for inlining. Balloon the
803 // threshold by 50% until we pass the single-BB phase.
804 bool SingleBB = true;
805 int SingleBBBonus = Threshold / 2;
806 Threshold += SingleBBBonus;
808 // Unless we are always-inlining, perform some tweaks to the cost and
809 // threshold based on the direct callsite information.
811 // We want to more aggressively inline vector-dense kernels, so up the
812 // threshold, and we'll lower it if the % of vector instructions gets too
814 assert(NumInstructions == 0);
815 assert(NumVectorInstructions == 0);
816 FiftyPercentVectorBonus = Threshold;
817 TenPercentVectorBonus = Threshold / 2;
819 // Give out bonuses per argument, as the instructions setting them up will
820 // be gone after inlining.
821 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
822 if (TD && CS.isByValArgument(I)) {
823 // We approximate the number of loads and stores needed by dividing the
824 // size of the byval type by the target's pointer size.
825 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
826 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
827 unsigned PointerSize = TD->getPointerSizeInBits();
829 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
831 // If it generates more than 8 stores it is likely to be expanded as an
832 // inline memcpy so we take that as an upper bound. Otherwise we assume
833 // one load and one store per word copied.
834 // FIXME: The maxStoresPerMemcpy setting from the target should be used
835 // here instead of a magic number of 8, but it's not available via
837 NumStores = std::min(NumStores, 8U);
839 Cost -= 2 * NumStores * InlineConstants::InstrCost;
841 // For non-byval arguments subtract off one instruction per call
843 Cost -= InlineConstants::InstrCost;
847 // If there is only one call of the function, and it has internal linkage,
848 // the cost of inlining it drops dramatically.
849 if (F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction())
850 Cost += InlineConstants::LastCallToStaticBonus;
852 // If the instruction after the call, or if the normal destination of the
853 // invoke is an unreachable instruction, the function is noreturn. As such,
854 // there is little point in inlining this unless there is literally zero
856 Instruction *Instr = CS.getInstruction();
857 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
858 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
860 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
863 // If this function uses the coldcc calling convention, prefer not to inline
865 if (F.getCallingConv() == CallingConv::Cold)
866 Cost += InlineConstants::ColdccPenalty;
868 // Check if we're done. This can happen due to bonuses and penalties.
869 if (Cost > Threshold)
876 Function *Caller = CS.getInstruction()->getParent()->getParent();
877 // Check if the caller function is recursive itself.
878 for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
880 CallSite Site(cast<Value>(*U));
883 Instruction *I = Site.getInstruction();
884 if (I->getParent()->getParent() == Caller) {
885 IsCallerRecursive = true;
890 // Track whether we've seen a return instruction. The first return
891 // instruction is free, as at least one will usually disappear in inlining.
892 bool HasReturn = false;
894 // Populate our simplified values by mapping from function arguments to call
895 // arguments with known important simplifications.
896 CallSite::arg_iterator CAI = CS.arg_begin();
897 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
898 FAI != FAE; ++FAI, ++CAI) {
899 assert(CAI != CS.arg_end());
900 if (Constant *C = dyn_cast<Constant>(CAI))
901 SimplifiedValues[FAI] = C;
903 Value *PtrArg = *CAI;
904 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
905 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
907 // We can SROA any pointer arguments derived from alloca instructions.
908 if (isa<AllocaInst>(PtrArg)) {
909 SROAArgValues[FAI] = PtrArg;
910 SROAArgCosts[PtrArg] = 0;
914 NumConstantArgs = SimplifiedValues.size();
915 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
916 NumAllocaArgs = SROAArgValues.size();
918 // The worklist of live basic blocks in the callee *after* inlining. We avoid
919 // adding basic blocks of the callee which can be proven to be dead for this
920 // particular call site in order to get more accurate cost estimates. This
921 // requires a somewhat heavyweight iteration pattern: we need to walk the
922 // basic blocks in a breadth-first order as we insert live successors. To
923 // accomplish this, prioritizing for small iterations because we exit after
924 // crossing our threshold, we use a small-size optimized SetVector.
925 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
926 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
927 BBSetVector BBWorklist;
928 BBWorklist.insert(&F.getEntryBlock());
929 // Note that we *must not* cache the size, this loop grows the worklist.
930 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
931 // Bail out the moment we cross the threshold. This means we'll under-count
932 // the cost, but only when undercounting doesn't matter.
933 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
936 BasicBlock *BB = BBWorklist[Idx];
940 // Handle the terminator cost here where we can track returns and other
941 // function-wide constructs.
942 TerminatorInst *TI = BB->getTerminator();
944 // We never want to inline functions that contain an indirectbr. This is
945 // incorrect because all the blockaddress's (in static global initializers
946 // for example) would be referring to the original function, and this
947 // indirect jump would jump from the inlined copy of the function into the
948 // original function which is extremely undefined behavior.
949 // FIXME: This logic isn't really right; we can safely inline functions
950 // with indirectbr's as long as no other function or global references the
951 // blockaddress of a block within the current function. And as a QOI issue,
952 // if someone is using a blockaddress without an indirectbr, and that
953 // reference somehow ends up in another function or global, we probably
954 // don't want to inline this function.
955 if (isa<IndirectBrInst>(TI))
958 if (!HasReturn && isa<ReturnInst>(TI))
961 Cost += InlineConstants::InstrCost;
963 // Analyze the cost of this block. If we blow through the threshold, this
964 // returns false, and we can bail on out.
965 if (!analyzeBlock(BB)) {
966 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
969 // If the caller is a recursive function then we don't want to inline
970 // functions which allocate a lot of stack space because it would increase
971 // the caller stack usage dramatically.
972 if (IsCallerRecursive &&
973 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
979 // Add in the live successors by first checking whether we have terminator
980 // that may be simplified based on the values simplified by this call.
981 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
982 if (BI->isConditional()) {
983 Value *Cond = BI->getCondition();
984 if (ConstantInt *SimpleCond
985 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
986 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
990 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
991 Value *Cond = SI->getCondition();
992 if (ConstantInt *SimpleCond
993 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
994 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
999 // If we're unable to select a particular successor, just count all of
1001 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1003 BBWorklist.insert(TI->getSuccessor(TIdx));
1005 // If we had any successors at this point, than post-inlining is likely to
1006 // have them as well. Note that we assume any basic blocks which existed
1007 // due to branches or switches which folded above will also fold after
1009 if (SingleBB && TI->getNumSuccessors() > 1) {
1010 // Take off the bonus we applied to the threshold.
1011 Threshold -= SingleBBBonus;
1016 Threshold += VectorBonus;
1018 return AlwaysInline || Cost < Threshold;
1021 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1022 /// \brief Dump stats about this call's analysis.
1023 void CallAnalyzer::dump() {
1024 #define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
1025 DEBUG_PRINT_STAT(NumConstantArgs);
1026 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1027 DEBUG_PRINT_STAT(NumAllocaArgs);
1028 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1029 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1030 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1031 DEBUG_PRINT_STAT(SROACostSavings);
1032 DEBUG_PRINT_STAT(SROACostSavingsLost);
1033 #undef DEBUG_PRINT_STAT
1037 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
1038 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1041 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
1043 // Don't inline functions which can be redefined at link-time to mean
1044 // something else. Don't inline functions marked noinline or call sites
1046 if (!Callee || Callee->mayBeOverridden() ||
1047 Callee->getFnAttributes().hasAttribute(Attributes::NoInline) ||
1049 return llvm::InlineCost::getNever();
1051 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1054 CallAnalyzer CA(TD, *Callee, Threshold);
1055 bool ShouldInline = CA.analyzeCall(CS);
1059 // Check if there was a reason to force inlining or no inlining.
1060 if (!ShouldInline && CA.getCost() < CA.getThreshold())
1061 return InlineCost::getNever();
1062 if (ShouldInline && (CA.isAlwaysInline() ||
1063 CA.getCost() >= CA.getThreshold()))
1064 return InlineCost::getAlways();
1066 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());