blob: c8700a8798ceff9f80da168662270cf3a6e785dc [file] [log] [blame]
Dan Gohmane4aeec02009-10-13 18:30:07 +00001//===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements inline cost analysis.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthf2286b02012-03-31 12:42:41 +000014#define DEBUG_TYPE "inline-cost"
Dan Gohmane4aeec02009-10-13 18:30:07 +000015#include "llvm/Analysis/InlineCost.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000016#include "llvm/Analysis/ConstantFolding.h"
17#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohmane4aeec02009-10-13 18:30:07 +000018#include "llvm/Support/CallSite.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000019#include "llvm/Support/Debug.h"
20#include "llvm/Support/InstVisitor.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/raw_ostream.h"
Dan Gohmane4aeec02009-10-13 18:30:07 +000023#include "llvm/CallingConv.h"
24#include "llvm/IntrinsicInst.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000025#include "llvm/Operator.h"
26#include "llvm/GlobalAlias.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000027#include "llvm/DataLayout.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
Dan Gohmane4aeec02009-10-13 18:30:07 +000031#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd6fc2622012-04-11 10:15:10 +000032#include "llvm/ADT/Statistic.h"
Eric Christopher4e8af6d2011-02-05 00:49:15 +000033
Dan Gohmane4aeec02009-10-13 18:30:07 +000034using namespace llvm;
35
Chandler Carruthd6fc2622012-04-11 10:15:10 +000036STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
37
Chandler Carruthf2286b02012-03-31 12:42:41 +000038namespace {
Chandler Carruth3d1d8952012-03-14 07:32:53 +000039
Chandler Carruthf2286b02012-03-31 12:42:41 +000040class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
41 typedef InstVisitor<CallAnalyzer, bool> Base;
42 friend class InstVisitor<CallAnalyzer, bool>;
Owen Anderson082bf2a2010-09-09 16:56:42 +000043
Micah Villmow3574eca2012-10-08 16:38:25 +000044 // DataLayout if available, or null.
45 const DataLayout *const TD;
Owen Anderson082bf2a2010-09-09 16:56:42 +000046
Chandler Carruthf2286b02012-03-31 12:42:41 +000047 // The called function.
48 Function &F;
Owen Anderson082bf2a2010-09-09 16:56:42 +000049
Chandler Carruthf2286b02012-03-31 12:42:41 +000050 int Threshold;
51 int Cost;
52 const bool AlwaysInline;
Owen Anderson082bf2a2010-09-09 16:56:42 +000053
Nadav Rotem92df0262012-09-19 08:08:04 +000054 bool IsCallerRecursive;
55 bool IsRecursiveCall;
Chandler Carruthf2286b02012-03-31 12:42:41 +000056 bool ExposesReturnsTwice;
57 bool HasDynamicAlloca;
Nadav Rotem92df0262012-09-19 08:08:04 +000058 /// Number of bytes allocated statically by the callee.
59 uint64_t AllocatedSize;
Chandler Carruthf2286b02012-03-31 12:42:41 +000060 unsigned NumInstructions, NumVectorInstructions;
61 int FiftyPercentVectorBonus, TenPercentVectorBonus;
62 int VectorBonus;
63
64 // While we walk the potentially-inlined instructions, we build up and
65 // maintain a mapping of simplified values specific to this callsite. The
66 // idea is to propagate any special information we have about arguments to
67 // this call through the inlinable section of the function, and account for
68 // likely simplifications post-inlining. The most important aspect we track
69 // is CFG altering simplifications -- when we prove a basic block dead, that
70 // can cause dramatic shifts in the cost of inlining a function.
71 DenseMap<Value *, Constant *> SimplifiedValues;
72
73 // Keep track of the values which map back (through function arguments) to
74 // allocas on the caller stack which could be simplified through SROA.
75 DenseMap<Value *, Value *> SROAArgValues;
76
77 // The mapping of caller Alloca values to their accumulated cost savings. If
78 // we have to disable SROA for one of the allocas, this tells us how much
79 // cost must be added.
80 DenseMap<Value *, int> SROAArgCosts;
81
82 // Keep track of values which map to a pointer base and constant offset.
83 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
84
85 // Custom simplification helper routines.
86 bool isAllocaDerivedArg(Value *V);
87 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
88 DenseMap<Value *, int>::iterator &CostIt);
89 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
90 void disableSROA(Value *V);
91 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
92 int InstructionCost);
93 bool handleSROACandidate(bool IsSROAValid,
94 DenseMap<Value *, int>::iterator CostIt,
95 int InstructionCost);
96 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
97 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
98 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
99
100 // Custom analysis routines.
101 bool analyzeBlock(BasicBlock *BB);
102
103 // Disable several entry points to the visitor so we don't accidentally use
104 // them by declaring but not defining them here.
105 void visit(Module *); void visit(Module &);
106 void visit(Function *); void visit(Function &);
107 void visit(BasicBlock *); void visit(BasicBlock &);
108
109 // Provide base case for our instruction visit.
110 bool visitInstruction(Instruction &I);
111
112 // Our visit overrides.
113 bool visitAlloca(AllocaInst &I);
114 bool visitPHI(PHINode &I);
115 bool visitGetElementPtr(GetElementPtrInst &I);
116 bool visitBitCast(BitCastInst &I);
117 bool visitPtrToInt(PtrToIntInst &I);
118 bool visitIntToPtr(IntToPtrInst &I);
119 bool visitCastInst(CastInst &I);
120 bool visitUnaryInstruction(UnaryInstruction &I);
121 bool visitICmp(ICmpInst &I);
122 bool visitSub(BinaryOperator &I);
123 bool visitBinaryOperator(BinaryOperator &I);
124 bool visitLoad(LoadInst &I);
125 bool visitStore(StoreInst &I);
126 bool visitCallSite(CallSite CS);
127
128public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000129 CallAnalyzer(const DataLayout *TD, Function &Callee, int Threshold)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000130 : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
Bill Wendling2c189062012-09-26 21:48:26 +0000131 AlwaysInline(F.getFnAttributes().hasAlwaysInlineAttr()),
Nadav Rotem92df0262012-09-19 08:08:04 +0000132 IsCallerRecursive(false), IsRecursiveCall(false),
133 ExposesReturnsTwice(false), HasDynamicAlloca(false), AllocatedSize(0),
Chandler Carruthf2286b02012-03-31 12:42:41 +0000134 NumInstructions(0), NumVectorInstructions(0),
135 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
136 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
137 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
138 NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLost(0) {
139 }
140
141 bool analyzeCall(CallSite CS);
142
143 int getThreshold() { return Threshold; }
144 int getCost() { return Cost; }
Bob Wilsonc38b6362012-10-07 01:11:19 +0000145 bool isAlwaysInline() { return AlwaysInline; }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000146
147 // Keep a bunch of stats about the cost savings found so we can print them
148 // out when debugging.
149 unsigned NumConstantArgs;
150 unsigned NumConstantOffsetPtrArgs;
151 unsigned NumAllocaArgs;
152 unsigned NumConstantPtrCmps;
153 unsigned NumConstantPtrDiffs;
154 unsigned NumInstructionsSimplified;
155 unsigned SROACostSavings;
156 unsigned SROACostSavingsLost;
157
158 void dump();
159};
160
161} // namespace
162
163/// \brief Test whether the given value is an Alloca-derived function argument.
164bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
165 return SROAArgValues.count(V);
Owen Anderson082bf2a2010-09-09 16:56:42 +0000166}
167
Chandler Carruthf2286b02012-03-31 12:42:41 +0000168/// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
169/// Returns false if V does not map to a SROA-candidate.
170bool CallAnalyzer::lookupSROAArgAndCost(
171 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
172 if (SROAArgValues.empty() || SROAArgCosts.empty())
173 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000174
Chandler Carruthf2286b02012-03-31 12:42:41 +0000175 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
176 if (ArgIt == SROAArgValues.end())
177 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000178
Chandler Carruthf2286b02012-03-31 12:42:41 +0000179 Arg = ArgIt->second;
180 CostIt = SROAArgCosts.find(Arg);
181 return CostIt != SROAArgCosts.end();
Chandler Carruthe8187e02012-03-09 02:49:36 +0000182}
183
Chandler Carruthf2286b02012-03-31 12:42:41 +0000184/// \brief Disable SROA for the candidate marked by this cost iterator.
Chandler Carruthe8187e02012-03-09 02:49:36 +0000185///
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000186/// This marks the candidate as no longer viable for SROA, and adds the cost
Chandler Carruthf2286b02012-03-31 12:42:41 +0000187/// savings associated with it back into the inline cost measurement.
188void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
189 // If we're no longer able to perform SROA we need to undo its cost savings
190 // and prevent subsequent analysis.
191 Cost += CostIt->second;
192 SROACostSavings -= CostIt->second;
193 SROACostSavingsLost += CostIt->second;
194 SROAArgCosts.erase(CostIt);
195}
196
197/// \brief If 'V' maps to a SROA candidate, disable SROA for it.
198void CallAnalyzer::disableSROA(Value *V) {
199 Value *SROAArg;
200 DenseMap<Value *, int>::iterator CostIt;
201 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
202 disableSROA(CostIt);
203}
204
205/// \brief Accumulate the given cost for a particular SROA candidate.
206void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
207 int InstructionCost) {
208 CostIt->second += InstructionCost;
209 SROACostSavings += InstructionCost;
210}
211
212/// \brief Helper for the common pattern of handling a SROA candidate.
213/// Either accumulates the cost savings if the SROA remains valid, or disables
214/// SROA for the candidate.
215bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
216 DenseMap<Value *, int>::iterator CostIt,
217 int InstructionCost) {
218 if (IsSROAValid) {
219 accumulateSROACost(CostIt, InstructionCost);
220 return true;
221 }
222
223 disableSROA(CostIt);
224 return false;
225}
226
227/// \brief Check whether a GEP's indices are all constant.
228///
229/// Respects any simplified values known during the analysis of this callsite.
230bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
231 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
232 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
Chandler Carruthe8187e02012-03-09 02:49:36 +0000233 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000234
Chandler Carruthf2286b02012-03-31 12:42:41 +0000235 return true;
236}
237
238/// \brief Accumulate a constant GEP offset into an APInt if possible.
239///
240/// Returns false if unable to compute the offset for any reason. Respects any
241/// simplified values known during the analysis of this callsite.
242bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
243 if (!TD)
244 return false;
245
246 unsigned IntPtrWidth = TD->getPointerSizeInBits();
247 assert(IntPtrWidth == Offset.getBitWidth());
248
249 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
250 GTI != GTE; ++GTI) {
251 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
252 if (!OpC)
253 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
254 OpC = dyn_cast<ConstantInt>(SimpleOp);
255 if (!OpC)
Chandler Carruthe8187e02012-03-09 02:49:36 +0000256 return false;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000257 if (OpC->isZero()) continue;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000258
Chandler Carruthf2286b02012-03-31 12:42:41 +0000259 // Handle a struct index, which adds its field offset to the pointer.
260 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
261 unsigned ElementIdx = OpC->getZExtValue();
262 const StructLayout *SL = TD->getStructLayout(STy);
263 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
264 continue;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000265 }
Chandler Carruthe8187e02012-03-09 02:49:36 +0000266
Chandler Carruthf2286b02012-03-31 12:42:41 +0000267 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
268 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
269 }
270 return true;
271}
272
273bool CallAnalyzer::visitAlloca(AllocaInst &I) {
274 // FIXME: Check whether inlining will turn a dynamic alloca into a static
275 // alloca, and handle that case.
276
Nadav Rotem92df0262012-09-19 08:08:04 +0000277 // Accumulate the allocated size.
278 if (I.isStaticAlloca()) {
279 Type *Ty = I.getAllocatedType();
280 AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
281 Ty->getPrimitiveSizeInBits());
282 }
283
Chandler Carruthf5f256c2012-03-31 13:18:09 +0000284 // We will happily inline static alloca instructions or dynamic alloca
Chandler Carruthf2286b02012-03-31 12:42:41 +0000285 // instructions in always-inline situations.
286 if (AlwaysInline || I.isStaticAlloca())
287 return Base::visitAlloca(I);
288
289 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
290 // a variety of reasons, and so we would like to not inline them into
291 // functions which don't currently have a dynamic alloca. This simply
292 // disables inlining altogether in the presence of a dynamic alloca.
293 HasDynamicAlloca = true;
294 return false;
295}
296
297bool CallAnalyzer::visitPHI(PHINode &I) {
298 // FIXME: We should potentially be tracking values through phi nodes,
299 // especially when they collapse to a single value due to deleted CFG edges
300 // during inlining.
301
302 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
303 // though we don't want to propagate it's bonuses. The idea is to disable
304 // SROA if it *might* be used in an inappropriate manner.
305
306 // Phi nodes are always zero-cost.
307 return true;
308}
309
310bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
311 Value *SROAArg;
312 DenseMap<Value *, int>::iterator CostIt;
313 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
314 SROAArg, CostIt);
315
316 // Try to fold GEPs of constant-offset call site argument pointers. This
317 // requires target data and inbounds GEPs.
318 if (TD && I.isInBounds()) {
319 // Check if we have a base + offset for the pointer.
320 Value *Ptr = I.getPointerOperand();
321 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
322 if (BaseAndOffset.first) {
323 // Check if the offset of this GEP is constant, and if so accumulate it
324 // into Offset.
325 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
326 // Non-constant GEPs aren't folded, and disable SROA.
327 if (SROACandidate)
328 disableSROA(CostIt);
329 return false;
330 }
331
332 // Add the result as a new mapping to Base + Offset.
333 ConstantOffsetPtrs[&I] = BaseAndOffset;
334
335 // Also handle SROA candidates here, we already know that the GEP is
336 // all-constant indexed.
337 if (SROACandidate)
338 SROAArgValues[&I] = SROAArg;
339
Chandler Carruthe8187e02012-03-09 02:49:36 +0000340 return true;
341 }
342 }
343
Chandler Carruthf2286b02012-03-31 12:42:41 +0000344 if (isGEPOffsetConstant(I)) {
345 if (SROACandidate)
346 SROAArgValues[&I] = SROAArg;
347
348 // Constant GEPs are modeled as free.
349 return true;
350 }
351
352 // Variable GEPs will require math and will disable SROA.
353 if (SROACandidate)
354 disableSROA(CostIt);
Chandler Carruthe8187e02012-03-09 02:49:36 +0000355 return false;
356}
357
Chandler Carruthf2286b02012-03-31 12:42:41 +0000358bool CallAnalyzer::visitBitCast(BitCastInst &I) {
359 // Propagate constants through bitcasts.
360 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
361 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
362 SimplifiedValues[&I] = C;
363 return true;
Owen Anderson082bf2a2010-09-09 16:56:42 +0000364 }
Owen Anderson082bf2a2010-09-09 16:56:42 +0000365
Chandler Carruthf2286b02012-03-31 12:42:41 +0000366 // Track base/offsets through casts
367 std::pair<Value *, APInt> BaseAndOffset
368 = ConstantOffsetPtrs.lookup(I.getOperand(0));
369 // Casts don't change the offset, just wrap it up.
370 if (BaseAndOffset.first)
371 ConstantOffsetPtrs[&I] = BaseAndOffset;
372
373 // Also look for SROA candidates here.
374 Value *SROAArg;
375 DenseMap<Value *, int>::iterator CostIt;
376 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
377 SROAArgValues[&I] = SROAArg;
378
379 // Bitcasts are always zero cost.
380 return true;
Owen Anderson082bf2a2010-09-09 16:56:42 +0000381}
382
Chandler Carruthf2286b02012-03-31 12:42:41 +0000383bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
384 // Propagate constants through ptrtoint.
385 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
386 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
387 SimplifiedValues[&I] = C;
388 return true;
Chandler Carruth274d3772012-03-14 23:19:53 +0000389 }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000390
391 // Track base/offset pairs when converted to a plain integer provided the
392 // integer is large enough to represent the pointer.
393 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
394 if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
395 std::pair<Value *, APInt> BaseAndOffset
396 = ConstantOffsetPtrs.lookup(I.getOperand(0));
397 if (BaseAndOffset.first)
398 ConstantOffsetPtrs[&I] = BaseAndOffset;
399 }
400
401 // This is really weird. Technically, ptrtoint will disable SROA. However,
402 // unless that ptrtoint is *used* somewhere in the live basic blocks after
403 // inlining, it will be nuked, and SROA should proceed. All of the uses which
404 // would block SROA would also block SROA if applied directly to a pointer,
405 // and so we can just add the integer in here. The only places where SROA is
406 // preserved either cannot fire on an integer, or won't in-and-of themselves
407 // disable SROA (ext) w/o some later use that we would see and disable.
408 Value *SROAArg;
409 DenseMap<Value *, int>::iterator CostIt;
410 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
411 SROAArgValues[&I] = SROAArg;
412
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000413 return isInstructionFree(&I, TD);
Chandler Carruth274d3772012-03-14 23:19:53 +0000414}
415
Chandler Carruthf2286b02012-03-31 12:42:41 +0000416bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
417 // Propagate constants through ptrtoint.
418 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
419 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
420 SimplifiedValues[&I] = C;
421 return true;
422 }
Dan Gohmane4aeec02009-10-13 18:30:07 +0000423
Chandler Carruthf2286b02012-03-31 12:42:41 +0000424 // Track base/offset pairs when round-tripped through a pointer without
425 // modifications provided the integer is not too large.
426 Value *Op = I.getOperand(0);
427 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
428 if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
429 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
430 if (BaseAndOffset.first)
431 ConstantOffsetPtrs[&I] = BaseAndOffset;
432 }
Dan Gohmane4aeec02009-10-13 18:30:07 +0000433
Chandler Carruthf2286b02012-03-31 12:42:41 +0000434 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
435 Value *SROAArg;
436 DenseMap<Value *, int>::iterator CostIt;
437 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
438 SROAArgValues[&I] = SROAArg;
Chandler Carruth274d3772012-03-14 23:19:53 +0000439
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000440 return isInstructionFree(&I, TD);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000441}
442
443bool CallAnalyzer::visitCastInst(CastInst &I) {
444 // Propagate constants through ptrtoint.
445 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
446 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
447 SimplifiedValues[&I] = C;
448 return true;
449 }
450
451 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
452 disableSROA(I.getOperand(0));
453
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000454 return isInstructionFree(&I, TD);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000455}
456
457bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
458 Value *Operand = I.getOperand(0);
459 Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
460 if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
461 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
462 Ops, TD)) {
463 SimplifiedValues[&I] = C;
464 return true;
465 }
466
467 // Disable any SROA on the argument to arbitrary unary operators.
468 disableSROA(Operand);
469
470 return false;
471}
472
473bool CallAnalyzer::visitICmp(ICmpInst &I) {
474 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
475 // First try to handle simplified comparisons.
476 if (!isa<Constant>(LHS))
477 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
478 LHS = SimpleLHS;
479 if (!isa<Constant>(RHS))
480 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
481 RHS = SimpleRHS;
482 if (Constant *CLHS = dyn_cast<Constant>(LHS))
483 if (Constant *CRHS = dyn_cast<Constant>(RHS))
484 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
485 SimplifiedValues[&I] = C;
486 return true;
487 }
488
489 // Otherwise look for a comparison between constant offset pointers with
490 // a common base.
491 Value *LHSBase, *RHSBase;
492 APInt LHSOffset, RHSOffset;
493 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
494 if (LHSBase) {
495 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
496 if (RHSBase && LHSBase == RHSBase) {
497 // We have common bases, fold the icmp to a constant based on the
498 // offsets.
499 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
500 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
501 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
502 SimplifiedValues[&I] = C;
503 ++NumConstantPtrCmps;
504 return true;
505 }
506 }
507 }
508
509 // If the comparison is an equality comparison with null, we can simplify it
510 // for any alloca-derived argument.
511 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
512 if (isAllocaDerivedArg(I.getOperand(0))) {
513 // We can actually predict the result of comparisons between an
514 // alloca-derived value and null. Note that this fires regardless of
515 // SROA firing.
516 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
517 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
518 : ConstantInt::getFalse(I.getType());
519 return true;
520 }
521
522 // Finally check for SROA candidates in comparisons.
523 Value *SROAArg;
524 DenseMap<Value *, int>::iterator CostIt;
525 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
526 if (isa<ConstantPointerNull>(I.getOperand(1))) {
527 accumulateSROACost(CostIt, InlineConstants::InstrCost);
528 return true;
529 }
530
531 disableSROA(CostIt);
532 }
533
534 return false;
535}
536
537bool CallAnalyzer::visitSub(BinaryOperator &I) {
538 // Try to handle a special case: we can fold computing the difference of two
539 // constant-related pointers.
540 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
541 Value *LHSBase, *RHSBase;
542 APInt LHSOffset, RHSOffset;
543 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
544 if (LHSBase) {
545 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
546 if (RHSBase && LHSBase == RHSBase) {
547 // We have common bases, fold the subtract to a constant based on the
548 // offsets.
549 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
550 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
551 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
552 SimplifiedValues[&I] = C;
553 ++NumConstantPtrDiffs;
554 return true;
555 }
556 }
557 }
558
559 // Otherwise, fall back to the generic logic for simplifying and handling
560 // instructions.
561 return Base::visitSub(I);
562}
563
564bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
565 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
566 if (!isa<Constant>(LHS))
567 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
568 LHS = SimpleLHS;
569 if (!isa<Constant>(RHS))
570 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
571 RHS = SimpleRHS;
572 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
573 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
574 SimplifiedValues[&I] = C;
575 return true;
576 }
577
578 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
579 disableSROA(LHS);
580 disableSROA(RHS);
581
582 return false;
583}
584
585bool CallAnalyzer::visitLoad(LoadInst &I) {
586 Value *SROAArg;
587 DenseMap<Value *, int>::iterator CostIt;
588 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
589 if (I.isSimple()) {
590 accumulateSROACost(CostIt, InlineConstants::InstrCost);
591 return true;
592 }
593
594 disableSROA(CostIt);
595 }
596
597 return false;
598}
599
600bool CallAnalyzer::visitStore(StoreInst &I) {
601 Value *SROAArg;
602 DenseMap<Value *, int>::iterator CostIt;
603 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
604 if (I.isSimple()) {
605 accumulateSROACost(CostIt, InlineConstants::InstrCost);
606 return true;
607 }
608
609 disableSROA(CostIt);
610 }
611
612 return false;
613}
614
615bool CallAnalyzer::visitCallSite(CallSite CS) {
616 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
Bill Wendling2c189062012-09-26 21:48:26 +0000617 !F.getFnAttributes().hasReturnsTwiceAttr()) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000618 // This aborts the entire analysis.
619 ExposesReturnsTwice = true;
620 return false;
621 }
622
623 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
624 switch (II->getIntrinsicID()) {
625 default:
626 return Base::visitCallSite(CS);
627
Chandler Carruthf2286b02012-03-31 12:42:41 +0000628 case Intrinsic::memset:
629 case Intrinsic::memcpy:
630 case Intrinsic::memmove:
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000631 // SROA can usually chew through these intrinsics, but they aren't free.
632 return false;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000633 }
634 }
635
636 if (Function *F = CS.getCalledFunction()) {
637 if (F == CS.getInstruction()->getParent()->getParent()) {
638 // This flag will fully abort the analysis, so don't bother with anything
639 // else.
Nadav Rotem92df0262012-09-19 08:08:04 +0000640 IsRecursiveCall = true;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000641 return false;
642 }
643
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000644 if (!callIsSmall(CS)) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000645 // We account for the average 1 instruction per call argument setup
646 // here.
647 Cost += CS.arg_size() * InlineConstants::InstrCost;
648
649 // Everything other than inline ASM will also have a significant cost
650 // merely from making the call.
651 if (!isa<InlineAsm>(CS.getCalledValue()))
652 Cost += InlineConstants::CallPenalty;
653 }
654
655 return Base::visitCallSite(CS);
656 }
657
658 // Otherwise we're in a very special case -- an indirect function call. See
659 // if we can be particularly clever about this.
660 Value *Callee = CS.getCalledValue();
661
662 // First, pay the price of the argument setup. We account for the average
663 // 1 instruction per call argument setup here.
664 Cost += CS.arg_size() * InlineConstants::InstrCost;
665
666 // Next, check if this happens to be an indirect function call to a known
667 // function in this inline context. If not, we've done all we can.
668 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
669 if (!F)
670 return Base::visitCallSite(CS);
671
672 // If we have a constant that we are calling as a function, we can peer
673 // through it and see the function target. This happens not infrequently
674 // during devirtualization and so we want to give it a hefty bonus for
675 // inlining, but cap that bonus in the event that inlining wouldn't pan
676 // out. Pretend to inline the function, with a custom threshold.
677 CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
678 if (CA.analyzeCall(CS)) {
679 // We were able to inline the indirect call! Subtract the cost from the
680 // bonus we want to apply, but don't go below zero.
681 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
682 }
683
684 return Base::visitCallSite(CS);
685}
686
687bool CallAnalyzer::visitInstruction(Instruction &I) {
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000688 // Some instructions are free. All of the free intrinsics can also be
689 // handled by SROA, etc.
690 if (isInstructionFree(&I, TD))
691 return true;
692
Chandler Carruthf2286b02012-03-31 12:42:41 +0000693 // We found something we don't understand or can't handle. Mark any SROA-able
694 // values in the operand list as no longer viable.
695 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
696 disableSROA(*OI);
697
698 return false;
699}
700
701
702/// \brief Analyze a basic block for its contribution to the inline cost.
703///
704/// This method walks the analyzer over every instruction in the given basic
705/// block and accounts for their cost during inlining at this callsite. It
706/// aborts early if the threshold has been exceeded or an impossible to inline
707/// construct has been detected. It returns false if inlining is no longer
708/// viable, and true if inlining remains viable.
709bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
710 for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
711 I != E; ++I) {
712 ++NumInstructions;
713 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
714 ++NumVectorInstructions;
715
716 // If the instruction simplified to a constant, there is no cost to this
717 // instruction. Visit the instructions using our InstVisitor to account for
718 // all of the per-instruction logic. The visit tree returns true if we
719 // consumed the instruction in any way, and false if the instruction's base
720 // cost should count against inlining.
721 if (Base::visit(I))
722 ++NumInstructionsSimplified;
723 else
724 Cost += InlineConstants::InstrCost;
725
726 // If the visit this instruction detected an uninlinable pattern, abort.
Nadav Rotem92df0262012-09-19 08:08:04 +0000727 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
728 return false;
729
730 // If the caller is a recursive function then we don't want to inline
731 // functions which allocate a lot of stack space because it would increase
732 // the caller stack usage dramatically.
733 if (IsCallerRecursive &&
734 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000735 return false;
736
737 if (NumVectorInstructions > NumInstructions/2)
738 VectorBonus = FiftyPercentVectorBonus;
739 else if (NumVectorInstructions > NumInstructions/10)
740 VectorBonus = TenPercentVectorBonus;
741 else
742 VectorBonus = 0;
743
744 // Check if we've past the threshold so we don't spin in huge basic
745 // blocks that will never inline.
746 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
747 return false;
748 }
749
750 return true;
751}
752
753/// \brief Compute the base pointer and cumulative constant offsets for V.
754///
755/// This strips all constant offsets off of V, leaving it the base pointer, and
756/// accumulates the total constant offset applied in the returned constant. It
757/// returns 0 if V is not a pointer, and returns the constant '0' if there are
758/// no constant offsets applied.
759ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
760 if (!TD || !V->getType()->isPointerTy())
761 return 0;
762
763 unsigned IntPtrWidth = TD->getPointerSizeInBits();
764 APInt Offset = APInt::getNullValue(IntPtrWidth);
765
766 // Even though we don't look through PHI nodes, we could be called on an
767 // instruction in an unreachable block, which may be on a cycle.
768 SmallPtrSet<Value *, 4> Visited;
769 Visited.insert(V);
770 do {
771 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
772 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
773 return 0;
774 V = GEP->getPointerOperand();
775 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
776 V = cast<Operator>(V)->getOperand(0);
777 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
778 if (GA->mayBeOverridden())
779 break;
780 V = GA->getAliasee();
781 } else {
782 break;
783 }
784 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
785 } while (Visited.insert(V));
786
787 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
788 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
789}
790
791/// \brief Analyze a call site for potential inlining.
792///
793/// Returns true if inlining this call is viable, and false if it is not
794/// viable. It computes the cost and adjusts the threshold based on numerous
795/// factors and heuristics. If this method returns false but the computed cost
796/// is below the computed threshold, then inlining was forcibly disabled by
797/// some artifact of the rountine.
798bool CallAnalyzer::analyzeCall(CallSite CS) {
Chandler Carruthd6fc2622012-04-11 10:15:10 +0000799 ++NumCallsAnalyzed;
800
Chandler Carruthf2286b02012-03-31 12:42:41 +0000801 // Track whether the post-inlining function would have more than one basic
802 // block. A single basic block is often intended for inlining. Balloon the
803 // threshold by 50% until we pass the single-BB phase.
804 bool SingleBB = true;
805 int SingleBBBonus = Threshold / 2;
806 Threshold += SingleBBBonus;
807
808 // Unless we are always-inlining, perform some tweaks to the cost and
809 // threshold based on the direct callsite information.
810 if (!AlwaysInline) {
811 // We want to more aggressively inline vector-dense kernels, so up the
812 // threshold, and we'll lower it if the % of vector instructions gets too
813 // low.
814 assert(NumInstructions == 0);
815 assert(NumVectorInstructions == 0);
816 FiftyPercentVectorBonus = Threshold;
817 TenPercentVectorBonus = Threshold / 2;
818
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000819 // Give out bonuses per argument, as the instructions setting them up will
820 // be gone after inlining.
821 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
822 if (TD && CS.isByValArgument(I)) {
823 // We approximate the number of loads and stores needed by dividing the
824 // size of the byval type by the target's pointer size.
825 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
826 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
827 unsigned PointerSize = TD->getPointerSizeInBits();
828 // Ceiling division.
829 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
830
831 // If it generates more than 8 stores it is likely to be expanded as an
832 // inline memcpy so we take that as an upper bound. Otherwise we assume
833 // one load and one store per word copied.
834 // FIXME: The maxStoresPerMemcpy setting from the target should be used
835 // here instead of a magic number of 8, but it's not available via
Micah Villmow3574eca2012-10-08 16:38:25 +0000836 // DataLayout.
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000837 NumStores = std::min(NumStores, 8U);
838
839 Cost -= 2 * NumStores * InlineConstants::InstrCost;
840 } else {
841 // For non-byval arguments subtract off one instruction per call
842 // argument.
843 Cost -= InlineConstants::InstrCost;
844 }
845 }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000846
847 // If there is only one call of the function, and it has internal linkage,
848 // the cost of inlining it drops dramatically.
849 if (F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction())
850 Cost += InlineConstants::LastCallToStaticBonus;
851
852 // If the instruction after the call, or if the normal destination of the
Nadav Rotem92df0262012-09-19 08:08:04 +0000853 // invoke is an unreachable instruction, the function is noreturn. As such,
854 // there is little point in inlining this unless there is literally zero
855 // cost.
856 Instruction *Instr = CS.getInstruction();
857 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000858 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
859 Threshold = 1;
Nadav Rotem92df0262012-09-19 08:08:04 +0000860 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
Chandler Carruthf2286b02012-03-31 12:42:41 +0000861 Threshold = 1;
862
863 // If this function uses the coldcc calling convention, prefer not to inline
864 // it.
865 if (F.getCallingConv() == CallingConv::Cold)
866 Cost += InlineConstants::ColdccPenalty;
867
868 // Check if we're done. This can happen due to bonuses and penalties.
869 if (Cost > Threshold)
870 return false;
871 }
872
873 if (F.empty())
874 return true;
875
Nadav Rotem92df0262012-09-19 08:08:04 +0000876 Function *Caller = CS.getInstruction()->getParent()->getParent();
877 // Check if the caller function is recursive itself.
878 for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
879 U != E; ++U) {
880 CallSite Site(cast<Value>(*U));
881 if (!Site)
882 continue;
883 Instruction *I = Site.getInstruction();
884 if (I->getParent()->getParent() == Caller) {
885 IsCallerRecursive = true;
886 break;
887 }
888 }
889
Chandler Carruthf2286b02012-03-31 12:42:41 +0000890 // Track whether we've seen a return instruction. The first return
891 // instruction is free, as at least one will usually disappear in inlining.
892 bool HasReturn = false;
893
894 // Populate our simplified values by mapping from function arguments to call
895 // arguments with known important simplifications.
896 CallSite::arg_iterator CAI = CS.arg_begin();
897 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
898 FAI != FAE; ++FAI, ++CAI) {
899 assert(CAI != CS.arg_end());
900 if (Constant *C = dyn_cast<Constant>(CAI))
901 SimplifiedValues[FAI] = C;
902
903 Value *PtrArg = *CAI;
904 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
905 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
906
907 // We can SROA any pointer arguments derived from alloca instructions.
908 if (isa<AllocaInst>(PtrArg)) {
909 SROAArgValues[FAI] = PtrArg;
910 SROAArgCosts[PtrArg] = 0;
911 }
912 }
913 }
914 NumConstantArgs = SimplifiedValues.size();
915 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
916 NumAllocaArgs = SROAArgValues.size();
917
918 // The worklist of live basic blocks in the callee *after* inlining. We avoid
919 // adding basic blocks of the callee which can be proven to be dead for this
920 // particular call site in order to get more accurate cost estimates. This
921 // requires a somewhat heavyweight iteration pattern: we need to walk the
922 // basic blocks in a breadth-first order as we insert live successors. To
923 // accomplish this, prioritizing for small iterations because we exit after
924 // crossing our threshold, we use a small-size optimized SetVector.
925 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
926 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
927 BBSetVector BBWorklist;
928 BBWorklist.insert(&F.getEntryBlock());
929 // Note that we *must not* cache the size, this loop grows the worklist.
930 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
931 // Bail out the moment we cross the threshold. This means we'll under-count
932 // the cost, but only when undercounting doesn't matter.
933 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
934 break;
935
936 BasicBlock *BB = BBWorklist[Idx];
937 if (BB->empty())
Chandler Carruth274d3772012-03-14 23:19:53 +0000938 continue;
Dan Gohmane4aeec02009-10-13 18:30:07 +0000939
Chandler Carruthf2286b02012-03-31 12:42:41 +0000940 // Handle the terminator cost here where we can track returns and other
941 // function-wide constructs.
942 TerminatorInst *TI = BB->getTerminator();
Kenneth Uildriks74fa7322010-10-09 22:06:36 +0000943
Chandler Carruthf2286b02012-03-31 12:42:41 +0000944 // We never want to inline functions that contain an indirectbr. This is
945 // incorrect because all the blockaddress's (in static global initializers
Nadav Rotem92df0262012-09-19 08:08:04 +0000946 // for example) would be referring to the original function, and this
947 // indirect jump would jump from the inlined copy of the function into the
948 // original function which is extremely undefined behavior.
Chandler Carruthf2286b02012-03-31 12:42:41 +0000949 // FIXME: This logic isn't really right; we can safely inline functions
950 // with indirectbr's as long as no other function or global references the
951 // blockaddress of a block within the current function. And as a QOI issue,
952 // if someone is using a blockaddress without an indirectbr, and that
953 // reference somehow ends up in another function or global, we probably
954 // don't want to inline this function.
955 if (isa<IndirectBrInst>(TI))
956 return false;
Andrew Trick5c655412011-10-01 01:27:56 +0000957
Chandler Carruthf2286b02012-03-31 12:42:41 +0000958 if (!HasReturn && isa<ReturnInst>(TI))
959 HasReturn = true;
960 else
961 Cost += InlineConstants::InstrCost;
Andrew Trick5c655412011-10-01 01:27:56 +0000962
Chandler Carruthf2286b02012-03-31 12:42:41 +0000963 // Analyze the cost of this block. If we blow through the threshold, this
964 // returns false, and we can bail on out.
965 if (!analyzeBlock(BB)) {
Nadav Rotem92df0262012-09-19 08:08:04 +0000966 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000967 return false;
Nadav Rotem92df0262012-09-19 08:08:04 +0000968
969 // If the caller is a recursive function then we don't want to inline
970 // functions which allocate a lot of stack space because it would increase
971 // the caller stack usage dramatically.
972 if (IsCallerRecursive &&
973 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
974 return false;
975
Chandler Carruthf2286b02012-03-31 12:42:41 +0000976 break;
Eric Christopher8e2da0c2011-02-01 01:16:32 +0000977 }
Eric Christopher8e2da0c2011-02-01 01:16:32 +0000978
Chandler Carruthf2286b02012-03-31 12:42:41 +0000979 // Add in the live successors by first checking whether we have terminator
980 // that may be simplified based on the values simplified by this call.
981 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
982 if (BI->isConditional()) {
983 Value *Cond = BI->getCondition();
984 if (ConstantInt *SimpleCond
985 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
986 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
987 continue;
Eric Christopher8e2da0c2011-02-01 01:16:32 +0000988 }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000989 }
990 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
991 Value *Cond = SI->getCondition();
992 if (ConstantInt *SimpleCond
993 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
994 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
995 continue;
996 }
997 }
Eric Christopher8e2da0c2011-02-01 01:16:32 +0000998
Chandler Carruthf2286b02012-03-31 12:42:41 +0000999 // If we're unable to select a particular successor, just count all of
1000 // them.
Nadav Rotem92df0262012-09-19 08:08:04 +00001001 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1002 ++TIdx)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001003 BBWorklist.insert(TI->getSuccessor(TIdx));
1004
1005 // If we had any successors at this point, than post-inlining is likely to
1006 // have them as well. Note that we assume any basic blocks which existed
1007 // due to branches or switches which folded above will also fold after
1008 // inlining.
1009 if (SingleBB && TI->getNumSuccessors() > 1) {
1010 // Take off the bonus we applied to the threshold.
1011 Threshold -= SingleBBBonus;
1012 SingleBB = false;
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001013 }
1014 }
Andrew Trick5c655412011-10-01 01:27:56 +00001015
Chandler Carruthf2286b02012-03-31 12:42:41 +00001016 Threshold += VectorBonus;
1017
1018 return AlwaysInline || Cost < Threshold;
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001019}
1020
Manman Ren286c4dc2012-09-12 05:06:18 +00001021#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001022/// \brief Dump stats about this call's analysis.
1023void CallAnalyzer::dump() {
1024#define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
1025 DEBUG_PRINT_STAT(NumConstantArgs);
1026 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1027 DEBUG_PRINT_STAT(NumAllocaArgs);
1028 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1029 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1030 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1031 DEBUG_PRINT_STAT(SROACostSavings);
1032 DEBUG_PRINT_STAT(SROACostSavingsLost);
1033#undef DEBUG_PRINT_STAT
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001034}
Manman Rencc77eec2012-09-06 19:55:56 +00001035#endif
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001036
Chandler Carruthf2286b02012-03-31 12:42:41 +00001037InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
David Chisnallb3815782012-04-06 17:27:41 +00001038 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1039}
Dan Gohmane4aeec02009-10-13 18:30:07 +00001040
David Chisnallb3815782012-04-06 17:27:41 +00001041InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
1042 int Threshold) {
Dan Gohmane4aeec02009-10-13 18:30:07 +00001043 // Don't inline functions which can be redefined at link-time to mean
Eric Christopherf27e6082010-03-25 04:49:10 +00001044 // something else. Don't inline functions marked noinline or call sites
1045 // marked noinline.
Chandler Carruthf2286b02012-03-31 12:42:41 +00001046 if (!Callee || Callee->mayBeOverridden() ||
Bill Wendling2c189062012-09-26 21:48:26 +00001047 Callee->getFnAttributes().hasNoInlineAttr() || CS.isNoInline())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001048 return llvm::InlineCost::getNever();
1049
Nadav Rotem92df0262012-09-19 08:08:04 +00001050 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1051 << "...\n");
Andrew Trick5c655412011-10-01 01:27:56 +00001052
Chandler Carruthf2286b02012-03-31 12:42:41 +00001053 CallAnalyzer CA(TD, *Callee, Threshold);
1054 bool ShouldInline = CA.analyzeCall(CS);
Dan Gohmane4aeec02009-10-13 18:30:07 +00001055
Chandler Carruthf2286b02012-03-31 12:42:41 +00001056 DEBUG(CA.dump());
1057
1058 // Check if there was a reason to force inlining or no inlining.
1059 if (!ShouldInline && CA.getCost() < CA.getThreshold())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001060 return InlineCost::getNever();
Bob Wilsonc38b6362012-10-07 01:11:19 +00001061 if (ShouldInline && (CA.isAlwaysInline() ||
1062 CA.getCost() >= CA.getThreshold()))
Dan Gohmane4aeec02009-10-13 18:30:07 +00001063 return InlineCost::getAlways();
Andrew Trick5c655412011-10-01 01:27:56 +00001064
Chandler Carruthf2286b02012-03-31 12:42:41 +00001065 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
Dan Gohmane4aeec02009-10-13 18:30:07 +00001066}