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/Analysis/TargetTransformInfo.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/InstVisitor.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/raw_ostream.h"
37 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
41 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
42 typedef InstVisitor<CallAnalyzer, bool> Base;
43 friend class InstVisitor<CallAnalyzer, bool>;
45 // DataLayout if available, or null.
46 const DataLayout *const TD;
48 /// The TargetTransformInfo available for this compilation.
49 const TargetTransformInfo &TTI;
51 // The called function.
57 bool IsCallerRecursive;
59 bool ExposesReturnsTwice;
60 bool HasDynamicAlloca;
61 bool ContainsNoDuplicateCall;
65 /// Number of bytes allocated statically by the callee.
66 uint64_t AllocatedSize;
67 unsigned NumInstructions, NumVectorInstructions;
68 int FiftyPercentVectorBonus, TenPercentVectorBonus;
71 // While we walk the potentially-inlined instructions, we build up and
72 // maintain a mapping of simplified values specific to this callsite. The
73 // idea is to propagate any special information we have about arguments to
74 // this call through the inlinable section of the function, and account for
75 // likely simplifications post-inlining. The most important aspect we track
76 // is CFG altering simplifications -- when we prove a basic block dead, that
77 // can cause dramatic shifts in the cost of inlining a function.
78 DenseMap<Value *, Constant *> SimplifiedValues;
80 // Keep track of the values which map back (through function arguments) to
81 // allocas on the caller stack which could be simplified through SROA.
82 DenseMap<Value *, Value *> SROAArgValues;
84 // The mapping of caller Alloca values to their accumulated cost savings. If
85 // we have to disable SROA for one of the allocas, this tells us how much
86 // cost must be added.
87 DenseMap<Value *, int> SROAArgCosts;
89 // Keep track of values which map to a pointer base and constant offset.
90 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
92 // Custom simplification helper routines.
93 bool isAllocaDerivedArg(Value *V);
94 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
95 DenseMap<Value *, int>::iterator &CostIt);
96 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
97 void disableSROA(Value *V);
98 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
100 bool handleSROACandidate(bool IsSROAValid,
101 DenseMap<Value *, int>::iterator CostIt,
102 int InstructionCost);
103 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
104 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
105 bool simplifyCallSite(Function *F, CallSite CS);
106 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
108 // Custom analysis routines.
109 bool analyzeBlock(BasicBlock *BB);
111 // Disable several entry points to the visitor so we don't accidentally use
112 // them by declaring but not defining them here.
113 void visit(Module *); void visit(Module &);
114 void visit(Function *); void visit(Function &);
115 void visit(BasicBlock *); void visit(BasicBlock &);
117 // Provide base case for our instruction visit.
118 bool visitInstruction(Instruction &I);
120 // Our visit overrides.
121 bool visitAlloca(AllocaInst &I);
122 bool visitPHI(PHINode &I);
123 bool visitGetElementPtr(GetElementPtrInst &I);
124 bool visitBitCast(BitCastInst &I);
125 bool visitPtrToInt(PtrToIntInst &I);
126 bool visitIntToPtr(IntToPtrInst &I);
127 bool visitCastInst(CastInst &I);
128 bool visitUnaryInstruction(UnaryInstruction &I);
129 bool visitCmpInst(CmpInst &I);
130 bool visitSub(BinaryOperator &I);
131 bool visitBinaryOperator(BinaryOperator &I);
132 bool visitLoad(LoadInst &I);
133 bool visitStore(StoreInst &I);
134 bool visitExtractValue(ExtractValueInst &I);
135 bool visitInsertValue(InsertValueInst &I);
136 bool visitCallSite(CallSite CS);
137 bool visitReturnInst(ReturnInst &RI);
138 bool visitBranchInst(BranchInst &BI);
139 bool visitSwitchInst(SwitchInst &SI);
140 bool visitIndirectBrInst(IndirectBrInst &IBI);
141 bool visitResumeInst(ResumeInst &RI);
142 bool visitUnreachableInst(UnreachableInst &I);
145 CallAnalyzer(const DataLayout *TD, const TargetTransformInfo &TTI,
146 Function &Callee, int Threshold)
147 : TD(TD), TTI(TTI), F(Callee), Threshold(Threshold), Cost(0),
148 IsCallerRecursive(false), IsRecursiveCall(false),
149 ExposesReturnsTwice(false), HasDynamicAlloca(false),
150 ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
151 AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
152 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
153 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
154 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
155 NumInstructionsSimplified(0), SROACostSavings(0),
156 SROACostSavingsLost(0) {}
158 bool analyzeCall(CallSite CS);
160 int getThreshold() { return Threshold; }
161 int getCost() { return Cost; }
163 // Keep a bunch of stats about the cost savings found so we can print them
164 // out when debugging.
165 unsigned NumConstantArgs;
166 unsigned NumConstantOffsetPtrArgs;
167 unsigned NumAllocaArgs;
168 unsigned NumConstantPtrCmps;
169 unsigned NumConstantPtrDiffs;
170 unsigned NumInstructionsSimplified;
171 unsigned SROACostSavings;
172 unsigned SROACostSavingsLost;
179 /// \brief Test whether the given value is an Alloca-derived function argument.
180 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
181 return SROAArgValues.count(V);
184 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
185 /// Returns false if V does not map to a SROA-candidate.
186 bool CallAnalyzer::lookupSROAArgAndCost(
187 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
188 if (SROAArgValues.empty() || SROAArgCosts.empty())
191 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
192 if (ArgIt == SROAArgValues.end())
196 CostIt = SROAArgCosts.find(Arg);
197 return CostIt != SROAArgCosts.end();
200 /// \brief Disable SROA for the candidate marked by this cost iterator.
202 /// This marks the candidate as no longer viable for SROA, and adds the cost
203 /// savings associated with it back into the inline cost measurement.
204 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
205 // If we're no longer able to perform SROA we need to undo its cost savings
206 // and prevent subsequent analysis.
207 Cost += CostIt->second;
208 SROACostSavings -= CostIt->second;
209 SROACostSavingsLost += CostIt->second;
210 SROAArgCosts.erase(CostIt);
213 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
214 void CallAnalyzer::disableSROA(Value *V) {
216 DenseMap<Value *, int>::iterator CostIt;
217 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
221 /// \brief Accumulate the given cost for a particular SROA candidate.
222 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
223 int InstructionCost) {
224 CostIt->second += InstructionCost;
225 SROACostSavings += InstructionCost;
228 /// \brief Helper for the common pattern of handling a SROA candidate.
229 /// Either accumulates the cost savings if the SROA remains valid, or disables
230 /// SROA for the candidate.
231 bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
232 DenseMap<Value *, int>::iterator CostIt,
233 int InstructionCost) {
235 accumulateSROACost(CostIt, InstructionCost);
243 /// \brief Check whether a GEP's indices are all constant.
245 /// Respects any simplified values known during the analysis of this callsite.
246 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
247 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
248 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
254 /// \brief Accumulate a constant GEP offset into an APInt if possible.
256 /// Returns false if unable to compute the offset for any reason. Respects any
257 /// simplified values known during the analysis of this callsite.
258 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
262 unsigned IntPtrWidth = TD->getPointerSizeInBits();
263 assert(IntPtrWidth == Offset.getBitWidth());
265 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
267 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
269 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
270 OpC = dyn_cast<ConstantInt>(SimpleOp);
273 if (OpC->isZero()) continue;
275 // Handle a struct index, which adds its field offset to the pointer.
276 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
277 unsigned ElementIdx = OpC->getZExtValue();
278 const StructLayout *SL = TD->getStructLayout(STy);
279 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
283 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
284 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
289 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
290 // FIXME: Check whether inlining will turn a dynamic alloca into a static
291 // alloca, and handle that case.
293 // Accumulate the allocated size.
294 if (I.isStaticAlloca()) {
295 Type *Ty = I.getAllocatedType();
296 AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
297 Ty->getPrimitiveSizeInBits());
300 // We will happily inline static alloca instructions.
301 if (I.isStaticAlloca())
302 return Base::visitAlloca(I);
304 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
305 // a variety of reasons, and so we would like to not inline them into
306 // functions which don't currently have a dynamic alloca. This simply
307 // disables inlining altogether in the presence of a dynamic alloca.
308 HasDynamicAlloca = true;
312 bool CallAnalyzer::visitPHI(PHINode &I) {
313 // FIXME: We should potentially be tracking values through phi nodes,
314 // especially when they collapse to a single value due to deleted CFG edges
317 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
318 // though we don't want to propagate it's bonuses. The idea is to disable
319 // SROA if it *might* be used in an inappropriate manner.
321 // Phi nodes are always zero-cost.
325 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
327 DenseMap<Value *, int>::iterator CostIt;
328 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
331 // Try to fold GEPs of constant-offset call site argument pointers. This
332 // requires target data and inbounds GEPs.
333 if (TD && I.isInBounds()) {
334 // Check if we have a base + offset for the pointer.
335 Value *Ptr = I.getPointerOperand();
336 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
337 if (BaseAndOffset.first) {
338 // Check if the offset of this GEP is constant, and if so accumulate it
340 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
341 // Non-constant GEPs aren't folded, and disable SROA.
347 // Add the result as a new mapping to Base + Offset.
348 ConstantOffsetPtrs[&I] = BaseAndOffset;
350 // Also handle SROA candidates here, we already know that the GEP is
351 // all-constant indexed.
353 SROAArgValues[&I] = SROAArg;
359 if (isGEPOffsetConstant(I)) {
361 SROAArgValues[&I] = SROAArg;
363 // Constant GEPs are modeled as free.
367 // Variable GEPs will require math and will disable SROA.
373 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
374 // Propagate constants through bitcasts.
375 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
377 COp = SimplifiedValues.lookup(I.getOperand(0));
379 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
380 SimplifiedValues[&I] = C;
384 // Track base/offsets through casts
385 std::pair<Value *, APInt> BaseAndOffset
386 = ConstantOffsetPtrs.lookup(I.getOperand(0));
387 // Casts don't change the offset, just wrap it up.
388 if (BaseAndOffset.first)
389 ConstantOffsetPtrs[&I] = BaseAndOffset;
391 // Also look for SROA candidates here.
393 DenseMap<Value *, int>::iterator CostIt;
394 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
395 SROAArgValues[&I] = SROAArg;
397 // Bitcasts are always zero cost.
401 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
402 // Propagate constants through ptrtoint.
403 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
405 COp = SimplifiedValues.lookup(I.getOperand(0));
407 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
408 SimplifiedValues[&I] = C;
412 // Track base/offset pairs when converted to a plain integer provided the
413 // integer is large enough to represent the pointer.
414 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
415 if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
416 std::pair<Value *, APInt> BaseAndOffset
417 = ConstantOffsetPtrs.lookup(I.getOperand(0));
418 if (BaseAndOffset.first)
419 ConstantOffsetPtrs[&I] = BaseAndOffset;
422 // This is really weird. Technically, ptrtoint will disable SROA. However,
423 // unless that ptrtoint is *used* somewhere in the live basic blocks after
424 // inlining, it will be nuked, and SROA should proceed. All of the uses which
425 // would block SROA would also block SROA if applied directly to a pointer,
426 // and so we can just add the integer in here. The only places where SROA is
427 // preserved either cannot fire on an integer, or won't in-and-of themselves
428 // disable SROA (ext) w/o some later use that we would see and disable.
430 DenseMap<Value *, int>::iterator CostIt;
431 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
432 SROAArgValues[&I] = SROAArg;
434 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
437 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
438 // Propagate constants through ptrtoint.
439 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
441 COp = SimplifiedValues.lookup(I.getOperand(0));
443 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
444 SimplifiedValues[&I] = C;
448 // Track base/offset pairs when round-tripped through a pointer without
449 // modifications provided the integer is not too large.
450 Value *Op = I.getOperand(0);
451 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
452 if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
453 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
454 if (BaseAndOffset.first)
455 ConstantOffsetPtrs[&I] = BaseAndOffset;
458 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
460 DenseMap<Value *, int>::iterator CostIt;
461 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
462 SROAArgValues[&I] = SROAArg;
464 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
467 bool CallAnalyzer::visitCastInst(CastInst &I) {
468 // Propagate constants through ptrtoint.
469 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
471 COp = SimplifiedValues.lookup(I.getOperand(0));
473 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
474 SimplifiedValues[&I] = C;
478 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
479 disableSROA(I.getOperand(0));
481 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
484 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
485 Value *Operand = I.getOperand(0);
486 Constant *COp = dyn_cast<Constant>(Operand);
488 COp = SimplifiedValues.lookup(Operand);
490 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
492 SimplifiedValues[&I] = C;
496 // Disable any SROA on the argument to arbitrary unary operators.
497 disableSROA(Operand);
502 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
503 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
504 // First try to handle simplified comparisons.
505 if (!isa<Constant>(LHS))
506 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
508 if (!isa<Constant>(RHS))
509 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
511 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
512 if (Constant *CRHS = dyn_cast<Constant>(RHS))
513 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
514 SimplifiedValues[&I] = C;
519 if (I.getOpcode() == Instruction::FCmp)
522 // Otherwise look for a comparison between constant offset pointers with
524 Value *LHSBase, *RHSBase;
525 APInt LHSOffset, RHSOffset;
526 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
528 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
529 if (RHSBase && LHSBase == RHSBase) {
530 // We have common bases, fold the icmp to a constant based on the
532 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
533 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
534 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
535 SimplifiedValues[&I] = C;
536 ++NumConstantPtrCmps;
542 // If the comparison is an equality comparison with null, we can simplify it
543 // for any alloca-derived argument.
544 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
545 if (isAllocaDerivedArg(I.getOperand(0))) {
546 // We can actually predict the result of comparisons between an
547 // alloca-derived value and null. Note that this fires regardless of
549 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
550 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
551 : ConstantInt::getFalse(I.getType());
555 // Finally check for SROA candidates in comparisons.
557 DenseMap<Value *, int>::iterator CostIt;
558 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
559 if (isa<ConstantPointerNull>(I.getOperand(1))) {
560 accumulateSROACost(CostIt, InlineConstants::InstrCost);
570 bool CallAnalyzer::visitSub(BinaryOperator &I) {
571 // Try to handle a special case: we can fold computing the difference of two
572 // constant-related pointers.
573 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
574 Value *LHSBase, *RHSBase;
575 APInt LHSOffset, RHSOffset;
576 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
578 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
579 if (RHSBase && LHSBase == RHSBase) {
580 // We have common bases, fold the subtract to a constant based on the
582 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
583 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
584 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
585 SimplifiedValues[&I] = C;
586 ++NumConstantPtrDiffs;
592 // Otherwise, fall back to the generic logic for simplifying and handling
594 return Base::visitSub(I);
597 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
598 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
599 if (!isa<Constant>(LHS))
600 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
602 if (!isa<Constant>(RHS))
603 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
605 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
606 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
607 SimplifiedValues[&I] = C;
611 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
618 bool CallAnalyzer::visitLoad(LoadInst &I) {
620 DenseMap<Value *, int>::iterator CostIt;
621 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
623 accumulateSROACost(CostIt, InlineConstants::InstrCost);
633 bool CallAnalyzer::visitStore(StoreInst &I) {
635 DenseMap<Value *, int>::iterator CostIt;
636 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
638 accumulateSROACost(CostIt, InlineConstants::InstrCost);
648 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
649 // Constant folding for extract value is trivial.
650 Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
652 C = SimplifiedValues.lookup(I.getAggregateOperand());
654 SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
658 // SROA can look through these but give them a cost.
662 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
663 // Constant folding for insert value is trivial.
664 Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
666 AggC = SimplifiedValues.lookup(I.getAggregateOperand());
667 Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
669 InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
670 if (AggC && InsertedC) {
671 SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
676 // SROA can look through these but give them a cost.
680 /// \brief Try to simplify a call site.
682 /// Takes a concrete function and callsite and tries to actually simplify it by
683 /// analyzing the arguments and call itself with instsimplify. Returns true if
684 /// it has simplified the callsite to some other entity (a constant), making it
686 bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
687 // FIXME: Using the instsimplify logic directly for this is inefficient
688 // because we have to continually rebuild the argument list even when no
689 // simplifications can be performed. Until that is fixed with remapping
690 // inside of instsimplify, directly constant fold calls here.
691 if (!canConstantFoldCallTo(F))
694 // Try to re-map the arguments to constants.
695 SmallVector<Constant *, 4> ConstantArgs;
696 ConstantArgs.reserve(CS.arg_size());
697 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
699 Constant *C = dyn_cast<Constant>(*I);
701 C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
703 return false; // This argument doesn't map to a constant.
705 ConstantArgs.push_back(C);
707 if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
708 SimplifiedValues[CS.getInstruction()] = C;
715 bool CallAnalyzer::visitCallSite(CallSite CS) {
716 if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
717 !F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
718 Attribute::ReturnsTwice)) {
719 // This aborts the entire analysis.
720 ExposesReturnsTwice = true;
724 cast<CallInst>(CS.getInstruction())->hasFnAttr(Attribute::NoDuplicate))
725 ContainsNoDuplicateCall = true;
727 if (Function *F = CS.getCalledFunction()) {
728 // When we have a concrete function, first try to simplify it directly.
729 if (simplifyCallSite(F, CS))
732 // Next check if it is an intrinsic we know about.
733 // FIXME: Lift this into part of the InstVisitor.
734 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
735 switch (II->getIntrinsicID()) {
737 return Base::visitCallSite(CS);
739 case Intrinsic::memset:
740 case Intrinsic::memcpy:
741 case Intrinsic::memmove:
742 // SROA can usually chew through these intrinsics, but they aren't free.
747 if (F == CS.getInstruction()->getParent()->getParent()) {
748 // This flag will fully abort the analysis, so don't bother with anything
750 IsRecursiveCall = true;
754 if (TTI.isLoweredToCall(F)) {
755 // We account for the average 1 instruction per call argument setup
757 Cost += CS.arg_size() * InlineConstants::InstrCost;
759 // Everything other than inline ASM will also have a significant cost
760 // merely from making the call.
761 if (!isa<InlineAsm>(CS.getCalledValue()))
762 Cost += InlineConstants::CallPenalty;
765 return Base::visitCallSite(CS);
768 // Otherwise we're in a very special case -- an indirect function call. See
769 // if we can be particularly clever about this.
770 Value *Callee = CS.getCalledValue();
772 // First, pay the price of the argument setup. We account for the average
773 // 1 instruction per call argument setup here.
774 Cost += CS.arg_size() * InlineConstants::InstrCost;
776 // Next, check if this happens to be an indirect function call to a known
777 // function in this inline context. If not, we've done all we can.
778 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
780 return Base::visitCallSite(CS);
782 // If we have a constant that we are calling as a function, we can peer
783 // through it and see the function target. This happens not infrequently
784 // during devirtualization and so we want to give it a hefty bonus for
785 // inlining, but cap that bonus in the event that inlining wouldn't pan
786 // out. Pretend to inline the function, with a custom threshold.
787 CallAnalyzer CA(TD, TTI, *F, InlineConstants::IndirectCallThreshold);
788 if (CA.analyzeCall(CS)) {
789 // We were able to inline the indirect call! Subtract the cost from the
790 // bonus we want to apply, but don't go below zero.
791 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
794 return Base::visitCallSite(CS);
797 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
798 // At least one return instruction will be free after inlining.
799 bool Free = !HasReturn;
804 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
805 // We model unconditional branches as essentially free -- they really
806 // shouldn't exist at all, but handling them makes the behavior of the
807 // inliner more regular and predictable. Interestingly, conditional branches
808 // which will fold away are also free.
809 return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
810 dyn_cast_or_null<ConstantInt>(
811 SimplifiedValues.lookup(BI.getCondition()));
814 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
815 // We model unconditional switches as free, see the comments on handling
817 return isa<ConstantInt>(SI.getCondition()) ||
818 dyn_cast_or_null<ConstantInt>(
819 SimplifiedValues.lookup(SI.getCondition()));
822 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
823 // We never want to inline functions that contain an indirectbr. This is
824 // incorrect because all the blockaddress's (in static global initializers
825 // for example) would be referring to the original function, and this
826 // indirect jump would jump from the inlined copy of the function into the
827 // original function which is extremely undefined behavior.
828 // FIXME: This logic isn't really right; we can safely inline functions with
829 // indirectbr's as long as no other function or global references the
830 // blockaddress of a block within the current function. And as a QOI issue,
831 // if someone is using a blockaddress without an indirectbr, and that
832 // reference somehow ends up in another function or global, we probably don't
833 // want to inline this function.
834 HasIndirectBr = true;
838 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
839 // FIXME: It's not clear that a single instruction is an accurate model for
840 // the inline cost of a resume instruction.
844 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
845 // FIXME: It might be reasonably to discount the cost of instructions leading
846 // to unreachable as they have the lowest possible impact on both runtime and
848 return true; // No actual code is needed for unreachable.
851 bool CallAnalyzer::visitInstruction(Instruction &I) {
852 // Some instructions are free. All of the free intrinsics can also be
853 // handled by SROA, etc.
854 if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
857 // We found something we don't understand or can't handle. Mark any SROA-able
858 // values in the operand list as no longer viable.
859 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
866 /// \brief Analyze a basic block for its contribution to the inline cost.
868 /// This method walks the analyzer over every instruction in the given basic
869 /// block and accounts for their cost during inlining at this callsite. It
870 /// aborts early if the threshold has been exceeded or an impossible to inline
871 /// construct has been detected. It returns false if inlining is no longer
872 /// viable, and true if inlining remains viable.
873 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
874 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
876 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
877 ++NumVectorInstructions;
879 // If the instruction simplified to a constant, there is no cost to this
880 // instruction. Visit the instructions using our InstVisitor to account for
881 // all of the per-instruction logic. The visit tree returns true if we
882 // consumed the instruction in any way, and false if the instruction's base
883 // cost should count against inlining.
885 ++NumInstructionsSimplified;
887 Cost += InlineConstants::InstrCost;
889 // If the visit this instruction detected an uninlinable pattern, abort.
890 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
894 // If the caller is a recursive function then we don't want to inline
895 // functions which allocate a lot of stack space because it would increase
896 // the caller stack usage dramatically.
897 if (IsCallerRecursive &&
898 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
901 if (NumVectorInstructions > NumInstructions/2)
902 VectorBonus = FiftyPercentVectorBonus;
903 else if (NumVectorInstructions > NumInstructions/10)
904 VectorBonus = TenPercentVectorBonus;
908 // Check if we've past the threshold so we don't spin in huge basic
909 // blocks that will never inline.
910 if (Cost > (Threshold + VectorBonus))
917 /// \brief Compute the base pointer and cumulative constant offsets for V.
919 /// This strips all constant offsets off of V, leaving it the base pointer, and
920 /// accumulates the total constant offset applied in the returned constant. It
921 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
922 /// no constant offsets applied.
923 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
924 if (!TD || !V->getType()->isPointerTy())
927 unsigned IntPtrWidth = TD->getPointerSizeInBits();
928 APInt Offset = APInt::getNullValue(IntPtrWidth);
930 // Even though we don't look through PHI nodes, we could be called on an
931 // instruction in an unreachable block, which may be on a cycle.
932 SmallPtrSet<Value *, 4> Visited;
935 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
936 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
938 V = GEP->getPointerOperand();
939 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
940 V = cast<Operator>(V)->getOperand(0);
941 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
942 if (GA->mayBeOverridden())
944 V = GA->getAliasee();
948 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
949 } while (Visited.insert(V));
951 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
952 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
955 /// \brief Analyze a call site for potential inlining.
957 /// Returns true if inlining this call is viable, and false if it is not
958 /// viable. It computes the cost and adjusts the threshold based on numerous
959 /// factors and heuristics. If this method returns false but the computed cost
960 /// is below the computed threshold, then inlining was forcibly disabled by
961 /// some artifact of the routine.
962 bool CallAnalyzer::analyzeCall(CallSite CS) {
965 // Track whether the post-inlining function would have more than one basic
966 // block. A single basic block is often intended for inlining. Balloon the
967 // threshold by 50% until we pass the single-BB phase.
968 bool SingleBB = true;
969 int SingleBBBonus = Threshold / 2;
970 Threshold += SingleBBBonus;
972 // Perform some tweaks to the cost and threshold based on the direct
973 // callsite information.
975 // We want to more aggressively inline vector-dense kernels, so up the
976 // threshold, and we'll lower it if the % of vector instructions gets too
978 assert(NumInstructions == 0);
979 assert(NumVectorInstructions == 0);
980 FiftyPercentVectorBonus = Threshold;
981 TenPercentVectorBonus = Threshold / 2;
983 // Give out bonuses per argument, as the instructions setting them up will
984 // be gone after inlining.
985 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
986 if (TD && CS.isByValArgument(I)) {
987 // We approximate the number of loads and stores needed by dividing the
988 // size of the byval type by the target's pointer size.
989 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
990 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
991 unsigned PointerSize = TD->getPointerSizeInBits();
993 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
995 // If it generates more than 8 stores it is likely to be expanded as an
996 // inline memcpy so we take that as an upper bound. Otherwise we assume
997 // one load and one store per word copied.
998 // FIXME: The maxStoresPerMemcpy setting from the target should be used
999 // here instead of a magic number of 8, but it's not available via
1001 NumStores = std::min(NumStores, 8U);
1003 Cost -= 2 * NumStores * InlineConstants::InstrCost;
1005 // For non-byval arguments subtract off one instruction per call
1007 Cost -= InlineConstants::InstrCost;
1011 // If there is only one call of the function, and it has internal linkage,
1012 // the cost of inlining it drops dramatically.
1013 bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
1014 &F == CS.getCalledFunction();
1015 if (OnlyOneCallAndLocalLinkage)
1016 Cost += InlineConstants::LastCallToStaticBonus;
1018 // If the instruction after the call, or if the normal destination of the
1019 // invoke is an unreachable instruction, the function is noreturn. As such,
1020 // there is little point in inlining this unless there is literally zero
1022 Instruction *Instr = CS.getInstruction();
1023 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
1024 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
1026 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
1029 // If this function uses the coldcc calling convention, prefer not to inline
1031 if (F.getCallingConv() == CallingConv::Cold)
1032 Cost += InlineConstants::ColdccPenalty;
1034 // Check if we're done. This can happen due to bonuses and penalties.
1035 if (Cost > Threshold)
1041 Function *Caller = CS.getInstruction()->getParent()->getParent();
1042 // Check if the caller function is recursive itself.
1043 for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
1045 CallSite Site(cast<Value>(*U));
1048 Instruction *I = Site.getInstruction();
1049 if (I->getParent()->getParent() == Caller) {
1050 IsCallerRecursive = true;
1055 // Populate our simplified values by mapping from function arguments to call
1056 // arguments with known important simplifications.
1057 CallSite::arg_iterator CAI = CS.arg_begin();
1058 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1059 FAI != FAE; ++FAI, ++CAI) {
1060 assert(CAI != CS.arg_end());
1061 if (Constant *C = dyn_cast<Constant>(CAI))
1062 SimplifiedValues[FAI] = C;
1064 Value *PtrArg = *CAI;
1065 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1066 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
1068 // We can SROA any pointer arguments derived from alloca instructions.
1069 if (isa<AllocaInst>(PtrArg)) {
1070 SROAArgValues[FAI] = PtrArg;
1071 SROAArgCosts[PtrArg] = 0;
1075 NumConstantArgs = SimplifiedValues.size();
1076 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1077 NumAllocaArgs = SROAArgValues.size();
1079 // The worklist of live basic blocks in the callee *after* inlining. We avoid
1080 // adding basic blocks of the callee which can be proven to be dead for this
1081 // particular call site in order to get more accurate cost estimates. This
1082 // requires a somewhat heavyweight iteration pattern: we need to walk the
1083 // basic blocks in a breadth-first order as we insert live successors. To
1084 // accomplish this, prioritizing for small iterations because we exit after
1085 // crossing our threshold, we use a small-size optimized SetVector.
1086 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1087 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
1088 BBSetVector BBWorklist;
1089 BBWorklist.insert(&F.getEntryBlock());
1090 // Note that we *must not* cache the size, this loop grows the worklist.
1091 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1092 // Bail out the moment we cross the threshold. This means we'll under-count
1093 // the cost, but only when undercounting doesn't matter.
1094 if (Cost > (Threshold + VectorBonus))
1097 BasicBlock *BB = BBWorklist[Idx];
1101 // Analyze the cost of this block. If we blow through the threshold, this
1102 // returns false, and we can bail on out.
1103 if (!analyzeBlock(BB)) {
1104 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1108 // If the caller is a recursive function then we don't want to inline
1109 // functions which allocate a lot of stack space because it would increase
1110 // the caller stack usage dramatically.
1111 if (IsCallerRecursive &&
1112 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1118 TerminatorInst *TI = BB->getTerminator();
1120 // Add in the live successors by first checking whether we have terminator
1121 // that may be simplified based on the values simplified by this call.
1122 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1123 if (BI->isConditional()) {
1124 Value *Cond = BI->getCondition();
1125 if (ConstantInt *SimpleCond
1126 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1127 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1131 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1132 Value *Cond = SI->getCondition();
1133 if (ConstantInt *SimpleCond
1134 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1135 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1140 // If we're unable to select a particular successor, just count all of
1142 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1144 BBWorklist.insert(TI->getSuccessor(TIdx));
1146 // If we had any successors at this point, than post-inlining is likely to
1147 // have them as well. Note that we assume any basic blocks which existed
1148 // due to branches or switches which folded above will also fold after
1150 if (SingleBB && TI->getNumSuccessors() > 1) {
1151 // Take off the bonus we applied to the threshold.
1152 Threshold -= SingleBBBonus;
1157 // If this is a noduplicate call, we can still inline as long as
1158 // inlining this would cause the removal of the caller (so the instruction
1159 // is not actually duplicated, just moved).
1160 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1163 Threshold += VectorBonus;
1165 return Cost < Threshold;
1168 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1169 /// \brief Dump stats about this call's analysis.
1170 void CallAnalyzer::dump() {
1171 #define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
1172 DEBUG_PRINT_STAT(NumConstantArgs);
1173 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1174 DEBUG_PRINT_STAT(NumAllocaArgs);
1175 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1176 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1177 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1178 DEBUG_PRINT_STAT(SROACostSavings);
1179 DEBUG_PRINT_STAT(SROACostSavingsLost);
1180 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
1181 #undef DEBUG_PRINT_STAT
1185 INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1187 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1188 INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1191 char InlineCostAnalysis::ID = 0;
1193 InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID), TD(0) {}
1195 InlineCostAnalysis::~InlineCostAnalysis() {}
1197 void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1198 AU.setPreservesAll();
1199 AU.addRequired<TargetTransformInfo>();
1200 CallGraphSCCPass::getAnalysisUsage(AU);
1203 bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
1204 TD = getAnalysisIfAvailable<DataLayout>();
1205 TTI = &getAnalysis<TargetTransformInfo>();
1209 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
1210 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1213 /// \brief Test that two functions either have or have not the given attribute
1214 /// at the same time.
1215 static bool attributeMatches(Function *F1, Function *F2,
1216 Attribute::AttrKind Attr) {
1217 return F1->hasFnAttribute(Attr) == F2->hasFnAttribute(Attr);
1220 /// \brief Test that there are no attribute conflicts between Caller and Callee
1221 /// that prevent inlining.
1222 static bool functionsHaveCompatibleAttributes(Function *Caller,
1224 return attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
1225 attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
1226 attributeMatches(Caller, Callee, Attribute::SanitizeThread);
1229 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
1231 // Cannot inline indirect calls.
1233 return llvm::InlineCost::getNever();
1235 // Calls to functions with always-inline attributes should be inlined
1236 // whenever possible.
1237 if (Callee->hasFnAttribute(Attribute::AlwaysInline)) {
1238 if (isInlineViable(*Callee))
1239 return llvm::InlineCost::getAlways();
1240 return llvm::InlineCost::getNever();
1243 // Never inline functions with conflicting attributes (unless callee has
1244 // always-inline attribute).
1245 if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee))
1246 return llvm::InlineCost::getNever();
1248 // Don't inline this call if the caller has the optnone attribute.
1249 if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
1250 return llvm::InlineCost::getNever();
1252 // Don't inline functions which can be redefined at link-time to mean
1253 // something else. Don't inline functions marked noinline or call sites
1255 if (Callee->mayBeOverridden() ||
1256 Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
1257 return llvm::InlineCost::getNever();
1259 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1262 CallAnalyzer CA(TD, *TTI, *Callee, Threshold);
1263 bool ShouldInline = CA.analyzeCall(CS);
1267 // Check if there was a reason to force inlining or no inlining.
1268 if (!ShouldInline && CA.getCost() < CA.getThreshold())
1269 return InlineCost::getNever();
1270 if (ShouldInline && CA.getCost() >= CA.getThreshold())
1271 return InlineCost::getAlways();
1273 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1276 bool InlineCostAnalysis::isInlineViable(Function &F) {
1278 F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1279 Attribute::ReturnsTwice);
1280 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1281 // Disallow inlining of functions which contain an indirect branch.
1282 if (isa<IndirectBrInst>(BI->getTerminator()))
1285 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1291 // Disallow recursive calls.
1292 if (&F == CS.getCalledFunction())
1295 // Disallow calls which expose returns-twice to a function not previously
1296 // attributed as such.
1297 if (!ReturnsTwice && CS.isCall() &&
1298 cast<CallInst>(CS.getInstruction())->canReturnTwice())