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/ADT/STLExtras.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DataLayout.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/InstVisitor.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Operator.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/raw_ostream.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.
53 bool IsCallerRecursive;
55 bool ExposesReturnsTwice;
56 bool HasDynamicAlloca;
57 /// Number of bytes allocated statically by the callee.
58 uint64_t AllocatedSize;
59 unsigned NumInstructions, NumVectorInstructions;
60 int FiftyPercentVectorBonus, TenPercentVectorBonus;
63 // While we walk the potentially-inlined instructions, we build up and
64 // maintain a mapping of simplified values specific to this callsite. The
65 // idea is to propagate any special information we have about arguments to
66 // this call through the inlinable section of the function, and account for
67 // likely simplifications post-inlining. The most important aspect we track
68 // is CFG altering simplifications -- when we prove a basic block dead, that
69 // can cause dramatic shifts in the cost of inlining a function.
70 DenseMap<Value *, Constant *> SimplifiedValues;
72 // Keep track of the values which map back (through function arguments) to
73 // allocas on the caller stack which could be simplified through SROA.
74 DenseMap<Value *, Value *> SROAArgValues;
76 // The mapping of caller Alloca values to their accumulated cost savings. If
77 // we have to disable SROA for one of the allocas, this tells us how much
78 // cost must be added.
79 DenseMap<Value *, int> SROAArgCosts;
81 // Keep track of values which map to a pointer base and constant offset.
82 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
84 // Custom simplification helper routines.
85 bool isAllocaDerivedArg(Value *V);
86 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
87 DenseMap<Value *, int>::iterator &CostIt);
88 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
89 void disableSROA(Value *V);
90 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
92 bool handleSROACandidate(bool IsSROAValid,
93 DenseMap<Value *, int>::iterator CostIt,
95 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
96 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
97 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
99 // Custom analysis routines.
100 bool analyzeBlock(BasicBlock *BB);
102 // Disable several entry points to the visitor so we don't accidentally use
103 // them by declaring but not defining them here.
104 void visit(Module *); void visit(Module &);
105 void visit(Function *); void visit(Function &);
106 void visit(BasicBlock *); void visit(BasicBlock &);
108 // Provide base case for our instruction visit.
109 bool visitInstruction(Instruction &I);
111 // Our visit overrides.
112 bool visitAlloca(AllocaInst &I);
113 bool visitPHI(PHINode &I);
114 bool visitGetElementPtr(GetElementPtrInst &I);
115 bool visitBitCast(BitCastInst &I);
116 bool visitPtrToInt(PtrToIntInst &I);
117 bool visitIntToPtr(IntToPtrInst &I);
118 bool visitCastInst(CastInst &I);
119 bool visitUnaryInstruction(UnaryInstruction &I);
120 bool visitICmp(ICmpInst &I);
121 bool visitSub(BinaryOperator &I);
122 bool visitBinaryOperator(BinaryOperator &I);
123 bool visitLoad(LoadInst &I);
124 bool visitStore(StoreInst &I);
125 bool visitCallSite(CallSite CS);
128 CallAnalyzer(const DataLayout *TD, Function &Callee, int Threshold)
129 : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
130 IsCallerRecursive(false), IsRecursiveCall(false),
131 ExposesReturnsTwice(false), HasDynamicAlloca(false), AllocatedSize(0),
132 NumInstructions(0), NumVectorInstructions(0),
133 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
134 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
135 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
136 NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLost(0) {
139 bool analyzeCall(CallSite CS);
141 int getThreshold() { return Threshold; }
142 int getCost() { return Cost; }
144 // Keep a bunch of stats about the cost savings found so we can print them
145 // out when debugging.
146 unsigned NumConstantArgs;
147 unsigned NumConstantOffsetPtrArgs;
148 unsigned NumAllocaArgs;
149 unsigned NumConstantPtrCmps;
150 unsigned NumConstantPtrDiffs;
151 unsigned NumInstructionsSimplified;
152 unsigned SROACostSavings;
153 unsigned SROACostSavingsLost;
160 /// \brief Test whether the given value is an Alloca-derived function argument.
161 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
162 return SROAArgValues.count(V);
165 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
166 /// Returns false if V does not map to a SROA-candidate.
167 bool CallAnalyzer::lookupSROAArgAndCost(
168 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
169 if (SROAArgValues.empty() || SROAArgCosts.empty())
172 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
173 if (ArgIt == SROAArgValues.end())
177 CostIt = SROAArgCosts.find(Arg);
178 return CostIt != SROAArgCosts.end();
181 /// \brief Disable SROA for the candidate marked by this cost iterator.
183 /// This marks the candidate as no longer viable for SROA, and adds the cost
184 /// savings associated with it back into the inline cost measurement.
185 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
186 // If we're no longer able to perform SROA we need to undo its cost savings
187 // and prevent subsequent analysis.
188 Cost += CostIt->second;
189 SROACostSavings -= CostIt->second;
190 SROACostSavingsLost += CostIt->second;
191 SROAArgCosts.erase(CostIt);
194 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
195 void CallAnalyzer::disableSROA(Value *V) {
197 DenseMap<Value *, int>::iterator CostIt;
198 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
202 /// \brief Accumulate the given cost for a particular SROA candidate.
203 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
204 int InstructionCost) {
205 CostIt->second += InstructionCost;
206 SROACostSavings += InstructionCost;
209 /// \brief Helper for the common pattern of handling a SROA candidate.
210 /// Either accumulates the cost savings if the SROA remains valid, or disables
211 /// SROA for the candidate.
212 bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
213 DenseMap<Value *, int>::iterator CostIt,
214 int InstructionCost) {
216 accumulateSROACost(CostIt, InstructionCost);
224 /// \brief Check whether a GEP's indices are all constant.
226 /// Respects any simplified values known during the analysis of this callsite.
227 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
228 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
229 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
235 /// \brief Accumulate a constant GEP offset into an APInt if possible.
237 /// Returns false if unable to compute the offset for any reason. Respects any
238 /// simplified values known during the analysis of this callsite.
239 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
243 unsigned IntPtrWidth = TD->getPointerSizeInBits();
244 assert(IntPtrWidth == Offset.getBitWidth());
246 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
248 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
250 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
251 OpC = dyn_cast<ConstantInt>(SimpleOp);
254 if (OpC->isZero()) continue;
256 // Handle a struct index, which adds its field offset to the pointer.
257 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
258 unsigned ElementIdx = OpC->getZExtValue();
259 const StructLayout *SL = TD->getStructLayout(STy);
260 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
264 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
265 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
270 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
271 // FIXME: Check whether inlining will turn a dynamic alloca into a static
272 // alloca, and handle that case.
274 // Accumulate the allocated size.
275 if (I.isStaticAlloca()) {
276 Type *Ty = I.getAllocatedType();
277 AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
278 Ty->getPrimitiveSizeInBits());
281 // We will happily inline static alloca instructions.
282 if (I.isStaticAlloca())
283 return Base::visitAlloca(I);
285 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
286 // a variety of reasons, and so we would like to not inline them into
287 // functions which don't currently have a dynamic alloca. This simply
288 // disables inlining altogether in the presence of a dynamic alloca.
289 HasDynamicAlloca = true;
293 bool CallAnalyzer::visitPHI(PHINode &I) {
294 // FIXME: We should potentially be tracking values through phi nodes,
295 // especially when they collapse to a single value due to deleted CFG edges
298 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
299 // though we don't want to propagate it's bonuses. The idea is to disable
300 // SROA if it *might* be used in an inappropriate manner.
302 // Phi nodes are always zero-cost.
306 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
308 DenseMap<Value *, int>::iterator CostIt;
309 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
312 // Try to fold GEPs of constant-offset call site argument pointers. This
313 // requires target data and inbounds GEPs.
314 if (TD && I.isInBounds()) {
315 // Check if we have a base + offset for the pointer.
316 Value *Ptr = I.getPointerOperand();
317 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
318 if (BaseAndOffset.first) {
319 // Check if the offset of this GEP is constant, and if so accumulate it
321 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
322 // Non-constant GEPs aren't folded, and disable SROA.
328 // Add the result as a new mapping to Base + Offset.
329 ConstantOffsetPtrs[&I] = BaseAndOffset;
331 // Also handle SROA candidates here, we already know that the GEP is
332 // all-constant indexed.
334 SROAArgValues[&I] = SROAArg;
340 if (isGEPOffsetConstant(I)) {
342 SROAArgValues[&I] = SROAArg;
344 // Constant GEPs are modeled as free.
348 // Variable GEPs will require math and will disable SROA.
354 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
355 // Propagate constants through bitcasts.
356 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
357 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
358 SimplifiedValues[&I] = C;
362 // Track base/offsets through casts
363 std::pair<Value *, APInt> BaseAndOffset
364 = ConstantOffsetPtrs.lookup(I.getOperand(0));
365 // Casts don't change the offset, just wrap it up.
366 if (BaseAndOffset.first)
367 ConstantOffsetPtrs[&I] = BaseAndOffset;
369 // Also look for SROA candidates here.
371 DenseMap<Value *, int>::iterator CostIt;
372 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
373 SROAArgValues[&I] = SROAArg;
375 // Bitcasts are always zero cost.
379 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
380 // Propagate constants through ptrtoint.
381 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
382 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
383 SimplifiedValues[&I] = C;
387 // Track base/offset pairs when converted to a plain integer provided the
388 // integer is large enough to represent the pointer.
389 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
390 if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
391 std::pair<Value *, APInt> BaseAndOffset
392 = ConstantOffsetPtrs.lookup(I.getOperand(0));
393 if (BaseAndOffset.first)
394 ConstantOffsetPtrs[&I] = BaseAndOffset;
397 // This is really weird. Technically, ptrtoint will disable SROA. However,
398 // unless that ptrtoint is *used* somewhere in the live basic blocks after
399 // inlining, it will be nuked, and SROA should proceed. All of the uses which
400 // would block SROA would also block SROA if applied directly to a pointer,
401 // and so we can just add the integer in here. The only places where SROA is
402 // preserved either cannot fire on an integer, or won't in-and-of themselves
403 // disable SROA (ext) w/o some later use that we would see and disable.
405 DenseMap<Value *, int>::iterator CostIt;
406 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
407 SROAArgValues[&I] = SROAArg;
409 return isInstructionFree(&I, TD);
412 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
413 // Propagate constants through ptrtoint.
414 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
415 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
416 SimplifiedValues[&I] = C;
420 // Track base/offset pairs when round-tripped through a pointer without
421 // modifications provided the integer is not too large.
422 Value *Op = I.getOperand(0);
423 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
424 if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
425 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
426 if (BaseAndOffset.first)
427 ConstantOffsetPtrs[&I] = BaseAndOffset;
430 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
432 DenseMap<Value *, int>::iterator CostIt;
433 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
434 SROAArgValues[&I] = SROAArg;
436 return isInstructionFree(&I, TD);
439 bool CallAnalyzer::visitCastInst(CastInst &I) {
440 // Propagate constants through ptrtoint.
441 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
442 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
443 SimplifiedValues[&I] = C;
447 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
448 disableSROA(I.getOperand(0));
450 return isInstructionFree(&I, TD);
453 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
454 Value *Operand = I.getOperand(0);
455 Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
456 if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
457 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
459 SimplifiedValues[&I] = C;
463 // Disable any SROA on the argument to arbitrary unary operators.
464 disableSROA(Operand);
469 bool CallAnalyzer::visitICmp(ICmpInst &I) {
470 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
471 // First try to handle simplified comparisons.
472 if (!isa<Constant>(LHS))
473 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
475 if (!isa<Constant>(RHS))
476 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
478 if (Constant *CLHS = dyn_cast<Constant>(LHS))
479 if (Constant *CRHS = dyn_cast<Constant>(RHS))
480 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
481 SimplifiedValues[&I] = C;
485 // Otherwise look for a comparison between constant offset pointers with
487 Value *LHSBase, *RHSBase;
488 APInt LHSOffset, RHSOffset;
489 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
491 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
492 if (RHSBase && LHSBase == RHSBase) {
493 // We have common bases, fold the icmp to a constant based on the
495 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
496 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
497 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
498 SimplifiedValues[&I] = C;
499 ++NumConstantPtrCmps;
505 // If the comparison is an equality comparison with null, we can simplify it
506 // for any alloca-derived argument.
507 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
508 if (isAllocaDerivedArg(I.getOperand(0))) {
509 // We can actually predict the result of comparisons between an
510 // alloca-derived value and null. Note that this fires regardless of
512 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
513 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
514 : ConstantInt::getFalse(I.getType());
518 // Finally check for SROA candidates in comparisons.
520 DenseMap<Value *, int>::iterator CostIt;
521 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
522 if (isa<ConstantPointerNull>(I.getOperand(1))) {
523 accumulateSROACost(CostIt, InlineConstants::InstrCost);
533 bool CallAnalyzer::visitSub(BinaryOperator &I) {
534 // Try to handle a special case: we can fold computing the difference of two
535 // constant-related pointers.
536 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
537 Value *LHSBase, *RHSBase;
538 APInt LHSOffset, RHSOffset;
539 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
541 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
542 if (RHSBase && LHSBase == RHSBase) {
543 // We have common bases, fold the subtract to a constant based on the
545 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
546 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
547 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
548 SimplifiedValues[&I] = C;
549 ++NumConstantPtrDiffs;
555 // Otherwise, fall back to the generic logic for simplifying and handling
557 return Base::visitSub(I);
560 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
561 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
562 if (!isa<Constant>(LHS))
563 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
565 if (!isa<Constant>(RHS))
566 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
568 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
569 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
570 SimplifiedValues[&I] = C;
574 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
581 bool CallAnalyzer::visitLoad(LoadInst &I) {
583 DenseMap<Value *, int>::iterator CostIt;
584 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
586 accumulateSROACost(CostIt, InlineConstants::InstrCost);
596 bool CallAnalyzer::visitStore(StoreInst &I) {
598 DenseMap<Value *, int>::iterator CostIt;
599 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
601 accumulateSROACost(CostIt, InlineConstants::InstrCost);
611 bool CallAnalyzer::visitCallSite(CallSite CS) {
612 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
613 !F.getFnAttributes().hasAttribute(Attributes::ReturnsTwice)) {
614 // This aborts the entire analysis.
615 ExposesReturnsTwice = true;
619 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
620 switch (II->getIntrinsicID()) {
622 return Base::visitCallSite(CS);
624 case Intrinsic::memset:
625 case Intrinsic::memcpy:
626 case Intrinsic::memmove:
627 // SROA can usually chew through these intrinsics, but they aren't free.
632 if (Function *F = CS.getCalledFunction()) {
633 if (F == CS.getInstruction()->getParent()->getParent()) {
634 // This flag will fully abort the analysis, so don't bother with anything
636 IsRecursiveCall = true;
640 if (!callIsSmall(CS)) {
641 // We account for the average 1 instruction per call argument setup
643 Cost += CS.arg_size() * InlineConstants::InstrCost;
645 // Everything other than inline ASM will also have a significant cost
646 // merely from making the call.
647 if (!isa<InlineAsm>(CS.getCalledValue()))
648 Cost += InlineConstants::CallPenalty;
651 return Base::visitCallSite(CS);
654 // Otherwise we're in a very special case -- an indirect function call. See
655 // if we can be particularly clever about this.
656 Value *Callee = CS.getCalledValue();
658 // First, pay the price of the argument setup. We account for the average
659 // 1 instruction per call argument setup here.
660 Cost += CS.arg_size() * InlineConstants::InstrCost;
662 // Next, check if this happens to be an indirect function call to a known
663 // function in this inline context. If not, we've done all we can.
664 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
666 return Base::visitCallSite(CS);
668 // If we have a constant that we are calling as a function, we can peer
669 // through it and see the function target. This happens not infrequently
670 // during devirtualization and so we want to give it a hefty bonus for
671 // inlining, but cap that bonus in the event that inlining wouldn't pan
672 // out. Pretend to inline the function, with a custom threshold.
673 CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
674 if (CA.analyzeCall(CS)) {
675 // We were able to inline the indirect call! Subtract the cost from the
676 // bonus we want to apply, but don't go below zero.
677 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
680 return Base::visitCallSite(CS);
683 bool CallAnalyzer::visitInstruction(Instruction &I) {
684 // Some instructions are free. All of the free intrinsics can also be
685 // handled by SROA, etc.
686 if (isInstructionFree(&I, TD))
689 // We found something we don't understand or can't handle. Mark any SROA-able
690 // values in the operand list as no longer viable.
691 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
698 /// \brief Analyze a basic block for its contribution to the inline cost.
700 /// This method walks the analyzer over every instruction in the given basic
701 /// block and accounts for their cost during inlining at this callsite. It
702 /// aborts early if the threshold has been exceeded or an impossible to inline
703 /// construct has been detected. It returns false if inlining is no longer
704 /// viable, and true if inlining remains viable.
705 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
706 for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
709 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
710 ++NumVectorInstructions;
712 // If the instruction simplified to a constant, there is no cost to this
713 // instruction. Visit the instructions using our InstVisitor to account for
714 // all of the per-instruction logic. The visit tree returns true if we
715 // consumed the instruction in any way, and false if the instruction's base
716 // cost should count against inlining.
718 ++NumInstructionsSimplified;
720 Cost += InlineConstants::InstrCost;
722 // If the visit this instruction detected an uninlinable pattern, abort.
723 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
726 // If the caller is a recursive function then we don't want to inline
727 // functions which allocate a lot of stack space because it would increase
728 // the caller stack usage dramatically.
729 if (IsCallerRecursive &&
730 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
733 if (NumVectorInstructions > NumInstructions/2)
734 VectorBonus = FiftyPercentVectorBonus;
735 else if (NumVectorInstructions > NumInstructions/10)
736 VectorBonus = TenPercentVectorBonus;
740 // Check if we've past the threshold so we don't spin in huge basic
741 // blocks that will never inline.
742 if (Cost > (Threshold + VectorBonus))
749 /// \brief Compute the base pointer and cumulative constant offsets for V.
751 /// This strips all constant offsets off of V, leaving it the base pointer, and
752 /// accumulates the total constant offset applied in the returned constant. It
753 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
754 /// no constant offsets applied.
755 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
756 if (!TD || !V->getType()->isPointerTy())
759 unsigned IntPtrWidth = TD->getPointerSizeInBits();
760 APInt Offset = APInt::getNullValue(IntPtrWidth);
762 // Even though we don't look through PHI nodes, we could be called on an
763 // instruction in an unreachable block, which may be on a cycle.
764 SmallPtrSet<Value *, 4> Visited;
767 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
768 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
770 V = GEP->getPointerOperand();
771 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
772 V = cast<Operator>(V)->getOperand(0);
773 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
774 if (GA->mayBeOverridden())
776 V = GA->getAliasee();
780 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
781 } while (Visited.insert(V));
783 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
784 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
787 /// \brief Analyze a call site for potential inlining.
789 /// Returns true if inlining this call is viable, and false if it is not
790 /// viable. It computes the cost and adjusts the threshold based on numerous
791 /// factors and heuristics. If this method returns false but the computed cost
792 /// is below the computed threshold, then inlining was forcibly disabled by
793 /// some artifact of the routine.
794 bool CallAnalyzer::analyzeCall(CallSite CS) {
797 // Track whether the post-inlining function would have more than one basic
798 // block. A single basic block is often intended for inlining. Balloon the
799 // threshold by 50% until we pass the single-BB phase.
800 bool SingleBB = true;
801 int SingleBBBonus = Threshold / 2;
802 Threshold += SingleBBBonus;
804 // Perform some tweaks to the cost and threshold based on the direct
805 // callsite information.
807 // We want to more aggressively inline vector-dense kernels, so up the
808 // threshold, and we'll lower it if the % of vector instructions gets too
810 assert(NumInstructions == 0);
811 assert(NumVectorInstructions == 0);
812 FiftyPercentVectorBonus = Threshold;
813 TenPercentVectorBonus = Threshold / 2;
815 // Give out bonuses per argument, as the instructions setting them up will
816 // be gone after inlining.
817 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
818 if (TD && CS.isByValArgument(I)) {
819 // We approximate the number of loads and stores needed by dividing the
820 // size of the byval type by the target's pointer size.
821 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
822 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
823 unsigned PointerSize = TD->getPointerSizeInBits();
825 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
827 // If it generates more than 8 stores it is likely to be expanded as an
828 // inline memcpy so we take that as an upper bound. Otherwise we assume
829 // one load and one store per word copied.
830 // FIXME: The maxStoresPerMemcpy setting from the target should be used
831 // here instead of a magic number of 8, but it's not available via
833 NumStores = std::min(NumStores, 8U);
835 Cost -= 2 * NumStores * InlineConstants::InstrCost;
837 // For non-byval arguments subtract off one instruction per call
839 Cost -= InlineConstants::InstrCost;
843 // If there is only one call of the function, and it has internal linkage,
844 // the cost of inlining it drops dramatically.
845 if (F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction())
846 Cost += InlineConstants::LastCallToStaticBonus;
848 // If the instruction after the call, or if the normal destination of the
849 // invoke is an unreachable instruction, the function is noreturn. As such,
850 // there is little point in inlining this unless there is literally zero
852 Instruction *Instr = CS.getInstruction();
853 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
854 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
856 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
859 // If this function uses the coldcc calling convention, prefer not to inline
861 if (F.getCallingConv() == CallingConv::Cold)
862 Cost += InlineConstants::ColdccPenalty;
864 // Check if we're done. This can happen due to bonuses and penalties.
865 if (Cost > Threshold)
871 Function *Caller = CS.getInstruction()->getParent()->getParent();
872 // Check if the caller function is recursive itself.
873 for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
875 CallSite Site(cast<Value>(*U));
878 Instruction *I = Site.getInstruction();
879 if (I->getParent()->getParent() == Caller) {
880 IsCallerRecursive = true;
885 // Track whether we've seen a return instruction. The first return
886 // instruction is free, as at least one will usually disappear in inlining.
887 bool HasReturn = false;
889 // Populate our simplified values by mapping from function arguments to call
890 // arguments with known important simplifications.
891 CallSite::arg_iterator CAI = CS.arg_begin();
892 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
893 FAI != FAE; ++FAI, ++CAI) {
894 assert(CAI != CS.arg_end());
895 if (Constant *C = dyn_cast<Constant>(CAI))
896 SimplifiedValues[FAI] = C;
898 Value *PtrArg = *CAI;
899 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
900 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
902 // We can SROA any pointer arguments derived from alloca instructions.
903 if (isa<AllocaInst>(PtrArg)) {
904 SROAArgValues[FAI] = PtrArg;
905 SROAArgCosts[PtrArg] = 0;
909 NumConstantArgs = SimplifiedValues.size();
910 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
911 NumAllocaArgs = SROAArgValues.size();
913 // The worklist of live basic blocks in the callee *after* inlining. We avoid
914 // adding basic blocks of the callee which can be proven to be dead for this
915 // particular call site in order to get more accurate cost estimates. This
916 // requires a somewhat heavyweight iteration pattern: we need to walk the
917 // basic blocks in a breadth-first order as we insert live successors. To
918 // accomplish this, prioritizing for small iterations because we exit after
919 // crossing our threshold, we use a small-size optimized SetVector.
920 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
921 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
922 BBSetVector BBWorklist;
923 BBWorklist.insert(&F.getEntryBlock());
924 // Note that we *must not* cache the size, this loop grows the worklist.
925 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
926 // Bail out the moment we cross the threshold. This means we'll under-count
927 // the cost, but only when undercounting doesn't matter.
928 if (Cost > (Threshold + VectorBonus))
931 BasicBlock *BB = BBWorklist[Idx];
935 // Handle the terminator cost here where we can track returns and other
936 // function-wide constructs.
937 TerminatorInst *TI = BB->getTerminator();
939 // We never want to inline functions that contain an indirectbr. This is
940 // incorrect because all the blockaddress's (in static global initializers
941 // for example) would be referring to the original function, and this
942 // indirect jump would jump from the inlined copy of the function into the
943 // original function which is extremely undefined behavior.
944 // FIXME: This logic isn't really right; we can safely inline functions
945 // with indirectbr's as long as no other function or global references the
946 // blockaddress of a block within the current function. And as a QOI issue,
947 // if someone is using a blockaddress without an indirectbr, and that
948 // reference somehow ends up in another function or global, we probably
949 // don't want to inline this function.
950 if (isa<IndirectBrInst>(TI))
953 if (!HasReturn && isa<ReturnInst>(TI))
956 Cost += InlineConstants::InstrCost;
958 // Analyze the cost of this block. If we blow through the threshold, this
959 // returns false, and we can bail on out.
960 if (!analyzeBlock(BB)) {
961 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
964 // If the caller is a recursive function then we don't want to inline
965 // functions which allocate a lot of stack space because it would increase
966 // the caller stack usage dramatically.
967 if (IsCallerRecursive &&
968 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
974 // Add in the live successors by first checking whether we have terminator
975 // that may be simplified based on the values simplified by this call.
976 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
977 if (BI->isConditional()) {
978 Value *Cond = BI->getCondition();
979 if (ConstantInt *SimpleCond
980 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
981 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
985 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
986 Value *Cond = SI->getCondition();
987 if (ConstantInt *SimpleCond
988 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
989 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
994 // If we're unable to select a particular successor, just count all of
996 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
998 BBWorklist.insert(TI->getSuccessor(TIdx));
1000 // If we had any successors at this point, than post-inlining is likely to
1001 // have them as well. Note that we assume any basic blocks which existed
1002 // due to branches or switches which folded above will also fold after
1004 if (SingleBB && TI->getNumSuccessors() > 1) {
1005 // Take off the bonus we applied to the threshold.
1006 Threshold -= SingleBBBonus;
1011 Threshold += VectorBonus;
1013 return Cost < Threshold;
1016 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1017 /// \brief Dump stats about this call's analysis.
1018 void CallAnalyzer::dump() {
1019 #define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
1020 DEBUG_PRINT_STAT(NumConstantArgs);
1021 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1022 DEBUG_PRINT_STAT(NumAllocaArgs);
1023 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1024 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1025 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1026 DEBUG_PRINT_STAT(SROACostSavings);
1027 DEBUG_PRINT_STAT(SROACostSavingsLost);
1028 #undef DEBUG_PRINT_STAT
1032 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
1033 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1036 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
1038 // Cannot inline indirect calls.
1040 return llvm::InlineCost::getNever();
1042 // Calls to functions with always-inline attributes should be inlined
1043 // whenever possible.
1044 if (Callee->getFnAttributes().hasAttribute(Attributes::AlwaysInline)) {
1045 if (isInlineViable(*Callee))
1046 return llvm::InlineCost::getAlways();
1047 return llvm::InlineCost::getNever();
1050 // Don't inline functions which can be redefined at link-time to mean
1051 // something else. Don't inline functions marked noinline or call sites
1053 if (Callee->mayBeOverridden() ||
1054 Callee->getFnAttributes().hasAttribute(Attributes::NoInline) ||
1056 return llvm::InlineCost::getNever();
1058 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1061 CallAnalyzer CA(TD, *Callee, Threshold);
1062 bool ShouldInline = CA.analyzeCall(CS);
1066 // Check if there was a reason to force inlining or no inlining.
1067 if (!ShouldInline && CA.getCost() < CA.getThreshold())
1068 return InlineCost::getNever();
1069 if (ShouldInline && CA.getCost() >= CA.getThreshold())
1070 return InlineCost::getAlways();
1072 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1075 bool InlineCostAnalyzer::isInlineViable(Function &F) {
1076 bool ReturnsTwice =F.getFnAttributes().hasAttribute(Attributes::ReturnsTwice);
1077 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1078 // Disallow inlining of functions which contain an indirect branch.
1079 if (isa<IndirectBrInst>(BI->getTerminator()))
1082 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1088 // Disallow recursive calls.
1089 if (&F == CS.getCalledFunction())
1092 // Disallow calls which expose returns-twice to a function not previously
1093 // attributed as such.
1094 if (!ReturnsTwice && CS.isCall() &&
1095 cast<CallInst>(CS.getInstruction())->canReturnTwice())