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/CallSite.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/GetElementPtrTypeIterator.h"
28 #include "llvm/IR/GlobalAlias.h"
29 #include "llvm/IR/InstVisitor.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/Support/Debug.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 DL;
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 isGEPOffsetConstant(GetElementPtrInst &GEP);
101 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
102 bool simplifyCallSite(Function *F, CallSite CS);
103 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
105 // Custom analysis routines.
106 bool analyzeBlock(BasicBlock *BB);
108 // Disable several entry points to the visitor so we don't accidentally use
109 // them by declaring but not defining them here.
110 void visit(Module *); void visit(Module &);
111 void visit(Function *); void visit(Function &);
112 void visit(BasicBlock *); void visit(BasicBlock &);
114 // Provide base case for our instruction visit.
115 bool visitInstruction(Instruction &I);
117 // Our visit overrides.
118 bool visitAlloca(AllocaInst &I);
119 bool visitPHI(PHINode &I);
120 bool visitGetElementPtr(GetElementPtrInst &I);
121 bool visitBitCast(BitCastInst &I);
122 bool visitPtrToInt(PtrToIntInst &I);
123 bool visitIntToPtr(IntToPtrInst &I);
124 bool visitCastInst(CastInst &I);
125 bool visitUnaryInstruction(UnaryInstruction &I);
126 bool visitCmpInst(CmpInst &I);
127 bool visitSub(BinaryOperator &I);
128 bool visitBinaryOperator(BinaryOperator &I);
129 bool visitLoad(LoadInst &I);
130 bool visitStore(StoreInst &I);
131 bool visitExtractValue(ExtractValueInst &I);
132 bool visitInsertValue(InsertValueInst &I);
133 bool visitCallSite(CallSite CS);
134 bool visitReturnInst(ReturnInst &RI);
135 bool visitBranchInst(BranchInst &BI);
136 bool visitSwitchInst(SwitchInst &SI);
137 bool visitIndirectBrInst(IndirectBrInst &IBI);
138 bool visitResumeInst(ResumeInst &RI);
139 bool visitUnreachableInst(UnreachableInst &I);
142 CallAnalyzer(const DataLayout *DL, const TargetTransformInfo &TTI,
143 Function &Callee, int Threshold)
144 : DL(DL), TTI(TTI), F(Callee), Threshold(Threshold), Cost(0),
145 IsCallerRecursive(false), IsRecursiveCall(false),
146 ExposesReturnsTwice(false), HasDynamicAlloca(false),
147 ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
148 AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
149 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
150 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
151 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
152 NumInstructionsSimplified(0), SROACostSavings(0),
153 SROACostSavingsLost(0) {}
155 bool analyzeCall(CallSite CS);
157 int getThreshold() { return Threshold; }
158 int getCost() { return Cost; }
160 // Keep a bunch of stats about the cost savings found so we can print them
161 // out when debugging.
162 unsigned NumConstantArgs;
163 unsigned NumConstantOffsetPtrArgs;
164 unsigned NumAllocaArgs;
165 unsigned NumConstantPtrCmps;
166 unsigned NumConstantPtrDiffs;
167 unsigned NumInstructionsSimplified;
168 unsigned SROACostSavings;
169 unsigned SROACostSavingsLost;
176 /// \brief Test whether the given value is an Alloca-derived function argument.
177 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
178 return SROAArgValues.count(V);
181 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
182 /// Returns false if V does not map to a SROA-candidate.
183 bool CallAnalyzer::lookupSROAArgAndCost(
184 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
185 if (SROAArgValues.empty() || SROAArgCosts.empty())
188 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
189 if (ArgIt == SROAArgValues.end())
193 CostIt = SROAArgCosts.find(Arg);
194 return CostIt != SROAArgCosts.end();
197 /// \brief Disable SROA for the candidate marked by this cost iterator.
199 /// This marks the candidate as no longer viable for SROA, and adds the cost
200 /// savings associated with it back into the inline cost measurement.
201 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
202 // If we're no longer able to perform SROA we need to undo its cost savings
203 // and prevent subsequent analysis.
204 Cost += CostIt->second;
205 SROACostSavings -= CostIt->second;
206 SROACostSavingsLost += CostIt->second;
207 SROAArgCosts.erase(CostIt);
210 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
211 void CallAnalyzer::disableSROA(Value *V) {
213 DenseMap<Value *, int>::iterator CostIt;
214 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
218 /// \brief Accumulate the given cost for a particular SROA candidate.
219 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
220 int InstructionCost) {
221 CostIt->second += InstructionCost;
222 SROACostSavings += InstructionCost;
225 /// \brief Check whether a GEP's indices are all constant.
227 /// Respects any simplified values known during the analysis of this callsite.
228 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
229 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
230 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
236 /// \brief Accumulate a constant GEP offset into an APInt if possible.
238 /// Returns false if unable to compute the offset for any reason. Respects any
239 /// simplified values known during the analysis of this callsite.
240 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
244 unsigned IntPtrWidth = DL->getPointerSizeInBits();
245 assert(IntPtrWidth == Offset.getBitWidth());
247 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
249 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
251 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
252 OpC = dyn_cast<ConstantInt>(SimpleOp);
255 if (OpC->isZero()) continue;
257 // Handle a struct index, which adds its field offset to the pointer.
258 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
259 unsigned ElementIdx = OpC->getZExtValue();
260 const StructLayout *SL = DL->getStructLayout(STy);
261 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
265 APInt TypeSize(IntPtrWidth, DL->getTypeAllocSize(GTI.getIndexedType()));
266 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
271 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
272 // Check whether inlining will turn a dynamic alloca into a static
273 // alloca, and handle that case.
274 if (I.isArrayAllocation()) {
275 if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
276 ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
277 assert(AllocSize && "Allocation size not a constant int?");
278 Type *Ty = I.getAllocatedType();
279 AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
280 return Base::visitAlloca(I);
284 // Accumulate the allocated size.
285 if (I.isStaticAlloca()) {
286 Type *Ty = I.getAllocatedType();
287 AllocatedSize += (DL ? DL->getTypeAllocSize(Ty) :
288 Ty->getPrimitiveSizeInBits());
291 // We will happily inline static alloca instructions.
292 if (I.isStaticAlloca())
293 return Base::visitAlloca(I);
295 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
296 // a variety of reasons, and so we would like to not inline them into
297 // functions which don't currently have a dynamic alloca. This simply
298 // disables inlining altogether in the presence of a dynamic alloca.
299 HasDynamicAlloca = true;
303 bool CallAnalyzer::visitPHI(PHINode &I) {
304 // FIXME: We should potentially be tracking values through phi nodes,
305 // especially when they collapse to a single value due to deleted CFG edges
308 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
309 // though we don't want to propagate it's bonuses. The idea is to disable
310 // SROA if it *might* be used in an inappropriate manner.
312 // Phi nodes are always zero-cost.
316 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
318 DenseMap<Value *, int>::iterator CostIt;
319 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
322 // Try to fold GEPs of constant-offset call site argument pointers. This
323 // requires target data and inbounds GEPs.
324 if (DL && I.isInBounds()) {
325 // Check if we have a base + offset for the pointer.
326 Value *Ptr = I.getPointerOperand();
327 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
328 if (BaseAndOffset.first) {
329 // Check if the offset of this GEP is constant, and if so accumulate it
331 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
332 // Non-constant GEPs aren't folded, and disable SROA.
338 // Add the result as a new mapping to Base + Offset.
339 ConstantOffsetPtrs[&I] = BaseAndOffset;
341 // Also handle SROA candidates here, we already know that the GEP is
342 // all-constant indexed.
344 SROAArgValues[&I] = SROAArg;
350 if (isGEPOffsetConstant(I)) {
352 SROAArgValues[&I] = SROAArg;
354 // Constant GEPs are modeled as free.
358 // Variable GEPs will require math and will disable SROA.
364 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
365 // Propagate constants through bitcasts.
366 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
368 COp = SimplifiedValues.lookup(I.getOperand(0));
370 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
371 SimplifiedValues[&I] = C;
375 // Track base/offsets through casts
376 std::pair<Value *, APInt> BaseAndOffset
377 = ConstantOffsetPtrs.lookup(I.getOperand(0));
378 // Casts don't change the offset, just wrap it up.
379 if (BaseAndOffset.first)
380 ConstantOffsetPtrs[&I] = BaseAndOffset;
382 // Also look for SROA candidates here.
384 DenseMap<Value *, int>::iterator CostIt;
385 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
386 SROAArgValues[&I] = SROAArg;
388 // Bitcasts are always zero cost.
392 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
393 const DataLayout *DL = I.getDataLayout();
394 // Propagate constants through ptrtoint.
395 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
397 COp = SimplifiedValues.lookup(I.getOperand(0));
399 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
400 SimplifiedValues[&I] = C;
404 // Track base/offset pairs when converted to a plain integer provided the
405 // integer is large enough to represent the pointer.
406 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
407 if (DL && IntegerSize >= DL->getPointerSizeInBits()) {
408 std::pair<Value *, APInt> BaseAndOffset
409 = ConstantOffsetPtrs.lookup(I.getOperand(0));
410 if (BaseAndOffset.first)
411 ConstantOffsetPtrs[&I] = BaseAndOffset;
414 // This is really weird. Technically, ptrtoint will disable SROA. However,
415 // unless that ptrtoint is *used* somewhere in the live basic blocks after
416 // inlining, it will be nuked, and SROA should proceed. All of the uses which
417 // would block SROA would also block SROA if applied directly to a pointer,
418 // and so we can just add the integer in here. The only places where SROA is
419 // preserved either cannot fire on an integer, or won't in-and-of themselves
420 // disable SROA (ext) w/o some later use that we would see and disable.
422 DenseMap<Value *, int>::iterator CostIt;
423 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
424 SROAArgValues[&I] = SROAArg;
426 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
429 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
430 const DataLayout *DL = I.getDataLayout();
431 // Propagate constants through ptrtoint.
432 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
434 COp = SimplifiedValues.lookup(I.getOperand(0));
436 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
437 SimplifiedValues[&I] = C;
441 // Track base/offset pairs when round-tripped through a pointer without
442 // modifications provided the integer is not too large.
443 Value *Op = I.getOperand(0);
444 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
445 if (DL && IntegerSize <= DL->getPointerSizeInBits()) {
446 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
447 if (BaseAndOffset.first)
448 ConstantOffsetPtrs[&I] = BaseAndOffset;
451 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
453 DenseMap<Value *, int>::iterator CostIt;
454 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
455 SROAArgValues[&I] = SROAArg;
457 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
460 bool CallAnalyzer::visitCastInst(CastInst &I) {
461 // Propagate constants through ptrtoint.
462 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
464 COp = SimplifiedValues.lookup(I.getOperand(0));
466 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
467 SimplifiedValues[&I] = C;
471 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
472 disableSROA(I.getOperand(0));
474 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
477 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
478 Value *Operand = I.getOperand(0);
479 Constant *COp = dyn_cast<Constant>(Operand);
481 COp = SimplifiedValues.lookup(Operand);
483 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
485 SimplifiedValues[&I] = C;
489 // Disable any SROA on the argument to arbitrary unary operators.
490 disableSROA(Operand);
495 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
496 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
497 // First try to handle simplified comparisons.
498 if (!isa<Constant>(LHS))
499 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
501 if (!isa<Constant>(RHS))
502 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
504 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
505 if (Constant *CRHS = dyn_cast<Constant>(RHS))
506 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
507 SimplifiedValues[&I] = C;
512 if (I.getOpcode() == Instruction::FCmp)
515 // Otherwise look for a comparison between constant offset pointers with
517 Value *LHSBase, *RHSBase;
518 APInt LHSOffset, RHSOffset;
519 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
521 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
522 if (RHSBase && LHSBase == RHSBase) {
523 // We have common bases, fold the icmp to a constant based on the
525 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
526 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
527 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
528 SimplifiedValues[&I] = C;
529 ++NumConstantPtrCmps;
535 // If the comparison is an equality comparison with null, we can simplify it
536 // for any alloca-derived argument.
537 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
538 if (isAllocaDerivedArg(I.getOperand(0))) {
539 // We can actually predict the result of comparisons between an
540 // alloca-derived value and null. Note that this fires regardless of
542 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
543 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
544 : ConstantInt::getFalse(I.getType());
548 // Finally check for SROA candidates in comparisons.
550 DenseMap<Value *, int>::iterator CostIt;
551 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
552 if (isa<ConstantPointerNull>(I.getOperand(1))) {
553 accumulateSROACost(CostIt, InlineConstants::InstrCost);
563 bool CallAnalyzer::visitSub(BinaryOperator &I) {
564 // Try to handle a special case: we can fold computing the difference of two
565 // constant-related pointers.
566 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
567 Value *LHSBase, *RHSBase;
568 APInt LHSOffset, RHSOffset;
569 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
571 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
572 if (RHSBase && LHSBase == RHSBase) {
573 // We have common bases, fold the subtract to a constant based on the
575 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
576 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
577 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
578 SimplifiedValues[&I] = C;
579 ++NumConstantPtrDiffs;
585 // Otherwise, fall back to the generic logic for simplifying and handling
587 return Base::visitSub(I);
590 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
591 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
592 if (!isa<Constant>(LHS))
593 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
595 if (!isa<Constant>(RHS))
596 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
598 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
599 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
600 SimplifiedValues[&I] = C;
604 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
611 bool CallAnalyzer::visitLoad(LoadInst &I) {
613 DenseMap<Value *, int>::iterator CostIt;
614 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
616 accumulateSROACost(CostIt, InlineConstants::InstrCost);
626 bool CallAnalyzer::visitStore(StoreInst &I) {
628 DenseMap<Value *, int>::iterator CostIt;
629 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
631 accumulateSROACost(CostIt, InlineConstants::InstrCost);
641 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
642 // Constant folding for extract value is trivial.
643 Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
645 C = SimplifiedValues.lookup(I.getAggregateOperand());
647 SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
651 // SROA can look through these but give them a cost.
655 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
656 // Constant folding for insert value is trivial.
657 Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
659 AggC = SimplifiedValues.lookup(I.getAggregateOperand());
660 Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
662 InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
663 if (AggC && InsertedC) {
664 SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
669 // SROA can look through these but give them a cost.
673 /// \brief Try to simplify a call site.
675 /// Takes a concrete function and callsite and tries to actually simplify it by
676 /// analyzing the arguments and call itself with instsimplify. Returns true if
677 /// it has simplified the callsite to some other entity (a constant), making it
679 bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
680 // FIXME: Using the instsimplify logic directly for this is inefficient
681 // because we have to continually rebuild the argument list even when no
682 // simplifications can be performed. Until that is fixed with remapping
683 // inside of instsimplify, directly constant fold calls here.
684 if (!canConstantFoldCallTo(F))
687 // Try to re-map the arguments to constants.
688 SmallVector<Constant *, 4> ConstantArgs;
689 ConstantArgs.reserve(CS.arg_size());
690 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
692 Constant *C = dyn_cast<Constant>(*I);
694 C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
696 return false; // This argument doesn't map to a constant.
698 ConstantArgs.push_back(C);
700 if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
701 SimplifiedValues[CS.getInstruction()] = C;
708 bool CallAnalyzer::visitCallSite(CallSite CS) {
709 if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
710 !F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
711 Attribute::ReturnsTwice)) {
712 // This aborts the entire analysis.
713 ExposesReturnsTwice = true;
717 cast<CallInst>(CS.getInstruction())->cannotDuplicate())
718 ContainsNoDuplicateCall = true;
720 if (Function *F = CS.getCalledFunction()) {
721 // When we have a concrete function, first try to simplify it directly.
722 if (simplifyCallSite(F, CS))
725 // Next check if it is an intrinsic we know about.
726 // FIXME: Lift this into part of the InstVisitor.
727 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
728 switch (II->getIntrinsicID()) {
730 return Base::visitCallSite(CS);
732 case Intrinsic::memset:
733 case Intrinsic::memcpy:
734 case Intrinsic::memmove:
735 // SROA can usually chew through these intrinsics, but they aren't free.
740 if (F == CS.getInstruction()->getParent()->getParent()) {
741 // This flag will fully abort the analysis, so don't bother with anything
743 IsRecursiveCall = true;
747 if (TTI.isLoweredToCall(F)) {
748 // We account for the average 1 instruction per call argument setup
750 Cost += CS.arg_size() * InlineConstants::InstrCost;
752 // Everything other than inline ASM will also have a significant cost
753 // merely from making the call.
754 if (!isa<InlineAsm>(CS.getCalledValue()))
755 Cost += InlineConstants::CallPenalty;
758 return Base::visitCallSite(CS);
761 // Otherwise we're in a very special case -- an indirect function call. See
762 // if we can be particularly clever about this.
763 Value *Callee = CS.getCalledValue();
765 // First, pay the price of the argument setup. We account for the average
766 // 1 instruction per call argument setup here.
767 Cost += CS.arg_size() * InlineConstants::InstrCost;
769 // Next, check if this happens to be an indirect function call to a known
770 // function in this inline context. If not, we've done all we can.
771 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
773 return Base::visitCallSite(CS);
775 // If we have a constant that we are calling as a function, we can peer
776 // through it and see the function target. This happens not infrequently
777 // during devirtualization and so we want to give it a hefty bonus for
778 // inlining, but cap that bonus in the event that inlining wouldn't pan
779 // out. Pretend to inline the function, with a custom threshold.
780 CallAnalyzer CA(DL, TTI, *F, InlineConstants::IndirectCallThreshold);
781 if (CA.analyzeCall(CS)) {
782 // We were able to inline the indirect call! Subtract the cost from the
783 // bonus we want to apply, but don't go below zero.
784 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
787 return Base::visitCallSite(CS);
790 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
791 // At least one return instruction will be free after inlining.
792 bool Free = !HasReturn;
797 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
798 // We model unconditional branches as essentially free -- they really
799 // shouldn't exist at all, but handling them makes the behavior of the
800 // inliner more regular and predictable. Interestingly, conditional branches
801 // which will fold away are also free.
802 return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
803 dyn_cast_or_null<ConstantInt>(
804 SimplifiedValues.lookup(BI.getCondition()));
807 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
808 // We model unconditional switches as free, see the comments on handling
810 return isa<ConstantInt>(SI.getCondition()) ||
811 dyn_cast_or_null<ConstantInt>(
812 SimplifiedValues.lookup(SI.getCondition()));
815 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
816 // We never want to inline functions that contain an indirectbr. This is
817 // incorrect because all the blockaddress's (in static global initializers
818 // for example) would be referring to the original function, and this
819 // indirect jump would jump from the inlined copy of the function into the
820 // original function which is extremely undefined behavior.
821 // FIXME: This logic isn't really right; we can safely inline functions with
822 // indirectbr's as long as no other function or global references the
823 // blockaddress of a block within the current function. And as a QOI issue,
824 // if someone is using a blockaddress without an indirectbr, and that
825 // reference somehow ends up in another function or global, we probably don't
826 // want to inline this function.
827 HasIndirectBr = true;
831 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
832 // FIXME: It's not clear that a single instruction is an accurate model for
833 // the inline cost of a resume instruction.
837 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
838 // FIXME: It might be reasonably to discount the cost of instructions leading
839 // to unreachable as they have the lowest possible impact on both runtime and
841 return true; // No actual code is needed for unreachable.
844 bool CallAnalyzer::visitInstruction(Instruction &I) {
845 // Some instructions are free. All of the free intrinsics can also be
846 // handled by SROA, etc.
847 if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
850 // We found something we don't understand or can't handle. Mark any SROA-able
851 // values in the operand list as no longer viable.
852 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
859 /// \brief Analyze a basic block for its contribution to the inline cost.
861 /// This method walks the analyzer over every instruction in the given basic
862 /// block and accounts for their cost during inlining at this callsite. It
863 /// aborts early if the threshold has been exceeded or an impossible to inline
864 /// construct has been detected. It returns false if inlining is no longer
865 /// viable, and true if inlining remains viable.
866 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
867 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
868 // FIXME: Currently, the number of instructions in a function regardless of
869 // our ability to simplify them during inline to constants or dead code,
870 // are actually used by the vector bonus heuristic. As long as that's true,
871 // we have to special case debug intrinsics here to prevent differences in
872 // inlining due to debug symbols. Eventually, the number of unsimplified
873 // instructions shouldn't factor into the cost computation, but until then,
874 // hack around it here.
875 if (isa<DbgInfoIntrinsic>(I))
879 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
880 ++NumVectorInstructions;
882 // If the instruction simplified to a constant, there is no cost to this
883 // instruction. Visit the instructions using our InstVisitor to account for
884 // all of the per-instruction logic. The visit tree returns true if we
885 // consumed the instruction in any way, and false if the instruction's base
886 // cost should count against inlining.
888 ++NumInstructionsSimplified;
890 Cost += InlineConstants::InstrCost;
892 // If the visit this instruction detected an uninlinable pattern, abort.
893 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
897 // If the caller is a recursive function then we don't want to inline
898 // functions which allocate a lot of stack space because it would increase
899 // the caller stack usage dramatically.
900 if (IsCallerRecursive &&
901 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
904 if (NumVectorInstructions > NumInstructions/2)
905 VectorBonus = FiftyPercentVectorBonus;
906 else if (NumVectorInstructions > NumInstructions/10)
907 VectorBonus = TenPercentVectorBonus;
911 // Check if we've past the threshold so we don't spin in huge basic
912 // blocks that will never inline.
913 if (Cost > (Threshold + VectorBonus))
920 /// \brief Compute the base pointer and cumulative constant offsets for V.
922 /// This strips all constant offsets off of V, leaving it the base pointer, and
923 /// accumulates the total constant offset applied in the returned constant. It
924 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
925 /// no constant offsets applied.
926 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
927 if (!DL || !V->getType()->isPointerTy())
930 unsigned IntPtrWidth = DL->getPointerSizeInBits();
931 APInt Offset = APInt::getNullValue(IntPtrWidth);
933 // Even though we don't look through PHI nodes, we could be called on an
934 // instruction in an unreachable block, which may be on a cycle.
935 SmallPtrSet<Value *, 4> Visited;
938 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
939 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
941 V = GEP->getPointerOperand();
942 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
943 V = cast<Operator>(V)->getOperand(0);
944 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
945 if (GA->mayBeOverridden())
947 V = GA->getAliasee();
951 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
952 } while (Visited.insert(V));
954 Type *IntPtrTy = DL->getIntPtrType(V->getContext());
955 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
958 /// \brief Analyze a call site for potential inlining.
960 /// Returns true if inlining this call is viable, and false if it is not
961 /// viable. It computes the cost and adjusts the threshold based on numerous
962 /// factors and heuristics. If this method returns false but the computed cost
963 /// is below the computed threshold, then inlining was forcibly disabled by
964 /// some artifact of the routine.
965 bool CallAnalyzer::analyzeCall(CallSite CS) {
968 // Track whether the post-inlining function would have more than one basic
969 // block. A single basic block is often intended for inlining. Balloon the
970 // threshold by 50% until we pass the single-BB phase.
971 bool SingleBB = true;
972 int SingleBBBonus = Threshold / 2;
973 Threshold += SingleBBBonus;
975 // Perform some tweaks to the cost and threshold based on the direct
976 // callsite information.
978 // We want to more aggressively inline vector-dense kernels, so up the
979 // threshold, and we'll lower it if the % of vector instructions gets too
981 assert(NumInstructions == 0);
982 assert(NumVectorInstructions == 0);
983 FiftyPercentVectorBonus = Threshold;
984 TenPercentVectorBonus = Threshold / 2;
986 // Give out bonuses per argument, as the instructions setting them up will
987 // be gone after inlining.
988 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
989 if (DL && CS.isByValArgument(I)) {
990 // We approximate the number of loads and stores needed by dividing the
991 // size of the byval type by the target's pointer size.
992 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
993 unsigned TypeSize = DL->getTypeSizeInBits(PTy->getElementType());
994 unsigned PointerSize = DL->getPointerSizeInBits();
996 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
998 // If it generates more than 8 stores it is likely to be expanded as an
999 // inline memcpy so we take that as an upper bound. Otherwise we assume
1000 // one load and one store per word copied.
1001 // FIXME: The maxStoresPerMemcpy setting from the target should be used
1002 // here instead of a magic number of 8, but it's not available via
1004 NumStores = std::min(NumStores, 8U);
1006 Cost -= 2 * NumStores * InlineConstants::InstrCost;
1008 // For non-byval arguments subtract off one instruction per call
1010 Cost -= InlineConstants::InstrCost;
1014 // If there is only one call of the function, and it has internal linkage,
1015 // the cost of inlining it drops dramatically.
1016 bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
1017 &F == CS.getCalledFunction();
1018 if (OnlyOneCallAndLocalLinkage)
1019 Cost += InlineConstants::LastCallToStaticBonus;
1021 // If the instruction after the call, or if the normal destination of the
1022 // invoke is an unreachable instruction, the function is noreturn. As such,
1023 // there is little point in inlining this unless there is literally zero
1025 Instruction *Instr = CS.getInstruction();
1026 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
1027 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
1029 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
1032 // If this function uses the coldcc calling convention, prefer not to inline
1034 if (F.getCallingConv() == CallingConv::Cold)
1035 Cost += InlineConstants::ColdccPenalty;
1037 // Check if we're done. This can happen due to bonuses and penalties.
1038 if (Cost > Threshold)
1044 Function *Caller = CS.getInstruction()->getParent()->getParent();
1045 // Check if the caller function is recursive itself.
1046 for (User *U : Caller->users()) {
1050 Instruction *I = Site.getInstruction();
1051 if (I->getParent()->getParent() == Caller) {
1052 IsCallerRecursive = true;
1057 // Populate our simplified values by mapping from function arguments to call
1058 // arguments with known important simplifications.
1059 CallSite::arg_iterator CAI = CS.arg_begin();
1060 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1061 FAI != FAE; ++FAI, ++CAI) {
1062 assert(CAI != CS.arg_end());
1063 if (Constant *C = dyn_cast<Constant>(CAI))
1064 SimplifiedValues[FAI] = C;
1066 Value *PtrArg = *CAI;
1067 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1068 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
1070 // We can SROA any pointer arguments derived from alloca instructions.
1071 if (isa<AllocaInst>(PtrArg)) {
1072 SROAArgValues[FAI] = PtrArg;
1073 SROAArgCosts[PtrArg] = 0;
1077 NumConstantArgs = SimplifiedValues.size();
1078 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1079 NumAllocaArgs = SROAArgValues.size();
1081 // The worklist of live basic blocks in the callee *after* inlining. We avoid
1082 // adding basic blocks of the callee which can be proven to be dead for this
1083 // particular call site in order to get more accurate cost estimates. This
1084 // requires a somewhat heavyweight iteration pattern: we need to walk the
1085 // basic blocks in a breadth-first order as we insert live successors. To
1086 // accomplish this, prioritizing for small iterations because we exit after
1087 // crossing our threshold, we use a small-size optimized SetVector.
1088 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1089 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
1090 BBSetVector BBWorklist;
1091 BBWorklist.insert(&F.getEntryBlock());
1092 // Note that we *must not* cache the size, this loop grows the worklist.
1093 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1094 // Bail out the moment we cross the threshold. This means we'll under-count
1095 // the cost, but only when undercounting doesn't matter.
1096 if (Cost > (Threshold + VectorBonus))
1099 BasicBlock *BB = BBWorklist[Idx];
1103 // Analyze the cost of this block. If we blow through the threshold, this
1104 // returns false, and we can bail on out.
1105 if (!analyzeBlock(BB)) {
1106 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1110 // If the caller is a recursive function then we don't want to inline
1111 // functions which allocate a lot of stack space because it would increase
1112 // the caller stack usage dramatically.
1113 if (IsCallerRecursive &&
1114 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1120 TerminatorInst *TI = BB->getTerminator();
1122 // Add in the live successors by first checking whether we have terminator
1123 // that may be simplified based on the values simplified by this call.
1124 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1125 if (BI->isConditional()) {
1126 Value *Cond = BI->getCondition();
1127 if (ConstantInt *SimpleCond
1128 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1129 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1133 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1134 Value *Cond = SI->getCondition();
1135 if (ConstantInt *SimpleCond
1136 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1137 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1142 // If we're unable to select a particular successor, just count all of
1144 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1146 BBWorklist.insert(TI->getSuccessor(TIdx));
1148 // If we had any successors at this point, than post-inlining is likely to
1149 // have them as well. Note that we assume any basic blocks which existed
1150 // due to branches or switches which folded above will also fold after
1152 if (SingleBB && TI->getNumSuccessors() > 1) {
1153 // Take off the bonus we applied to the threshold.
1154 Threshold -= SingleBBBonus;
1159 // If this is a noduplicate call, we can still inline as long as
1160 // inlining this would cause the removal of the caller (so the instruction
1161 // is not actually duplicated, just moved).
1162 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1165 Threshold += VectorBonus;
1167 return Cost < Threshold;
1170 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1171 /// \brief Dump stats about this call's analysis.
1172 void CallAnalyzer::dump() {
1173 #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n"
1174 DEBUG_PRINT_STAT(NumConstantArgs);
1175 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1176 DEBUG_PRINT_STAT(NumAllocaArgs);
1177 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1178 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1179 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1180 DEBUG_PRINT_STAT(SROACostSavings);
1181 DEBUG_PRINT_STAT(SROACostSavingsLost);
1182 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
1183 DEBUG_PRINT_STAT(Cost);
1184 DEBUG_PRINT_STAT(Threshold);
1185 DEBUG_PRINT_STAT(VectorBonus);
1186 #undef DEBUG_PRINT_STAT
1190 INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1192 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
1193 INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1196 char InlineCostAnalysis::ID = 0;
1198 InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID) {}
1200 InlineCostAnalysis::~InlineCostAnalysis() {}
1202 void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1203 AU.setPreservesAll();
1204 AU.addRequired<TargetTransformInfo>();
1205 CallGraphSCCPass::getAnalysisUsage(AU);
1208 bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
1209 TTI = &getAnalysis<TargetTransformInfo>();
1213 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
1214 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1217 /// \brief Test that two functions either have or have not the given attribute
1218 /// at the same time.
1219 static bool attributeMatches(Function *F1, Function *F2,
1220 Attribute::AttrKind Attr) {
1221 return F1->hasFnAttribute(Attr) == F2->hasFnAttribute(Attr);
1224 /// \brief Test that there are no attribute conflicts between Caller and Callee
1225 /// that prevent inlining.
1226 static bool functionsHaveCompatibleAttributes(Function *Caller,
1228 return attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
1229 attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
1230 attributeMatches(Caller, Callee, Attribute::SanitizeThread);
1233 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
1235 // Cannot inline indirect calls.
1237 return llvm::InlineCost::getNever();
1239 // Calls to functions with always-inline attributes should be inlined
1240 // whenever possible.
1241 if (Callee->hasFnAttribute(Attribute::AlwaysInline)) {
1242 if (isInlineViable(*Callee))
1243 return llvm::InlineCost::getAlways();
1244 return llvm::InlineCost::getNever();
1247 // Never inline functions with conflicting attributes (unless callee has
1248 // always-inline attribute).
1249 if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee))
1250 return llvm::InlineCost::getNever();
1252 // Don't inline this call if the caller has the optnone attribute.
1253 if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
1254 return llvm::InlineCost::getNever();
1256 // Don't inline functions which can be redefined at link-time to mean
1257 // something else. Don't inline functions marked noinline or call sites
1259 if (Callee->mayBeOverridden() ||
1260 Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
1261 return llvm::InlineCost::getNever();
1263 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1266 CallAnalyzer CA(Callee->getDataLayout(), *TTI, *Callee, Threshold);
1267 bool ShouldInline = CA.analyzeCall(CS);
1271 // Check if there was a reason to force inlining or no inlining.
1272 if (!ShouldInline && CA.getCost() < CA.getThreshold())
1273 return InlineCost::getNever();
1274 if (ShouldInline && CA.getCost() >= CA.getThreshold())
1275 return InlineCost::getAlways();
1277 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1280 bool InlineCostAnalysis::isInlineViable(Function &F) {
1282 F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1283 Attribute::ReturnsTwice);
1284 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1285 // Disallow inlining of functions which contain an indirect branch.
1286 if (isa<IndirectBrInst>(BI->getTerminator()))
1289 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1295 // Disallow recursive calls.
1296 if (&F == CS.getCalledFunction())
1299 // Disallow calls which expose returns-twice to a function not previously
1300 // attributed as such.
1301 if (!ReturnsTwice && CS.isCall() &&
1302 cast<CallInst>(CS.getInstruction())->canReturnTwice())