blob: 835b8343b284afe433552b6e724536867f018deb [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 Carruthd04a8d42012-12-03 16:50:05 +000016#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"
Chandler Carruthf2286b02012-03-31 12:42:41 +000021#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/CallingConv.h"
24#include "llvm/DataLayout.h"
25#include "llvm/GlobalAlias.h"
26#include "llvm/InstVisitor.h"
27#include "llvm/IntrinsicInst.h"
28#include "llvm/Operator.h"
Dan Gohmane4aeec02009-10-13 18:30:07 +000029#include "llvm/Support/CallSite.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000030#include "llvm/Support/Debug.h"
Chandler Carruthf2286b02012-03-31 12:42:41 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/raw_ostream.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;
Owen Anderson082bf2a2010-09-09 16:56:42 +000052
Nadav Rotem92df0262012-09-19 08:08:04 +000053 bool IsCallerRecursive;
54 bool IsRecursiveCall;
Chandler Carruthf2286b02012-03-31 12:42:41 +000055 bool ExposesReturnsTwice;
56 bool HasDynamicAlloca;
James Molloy67ae1352012-12-20 16:04:27 +000057 bool ContainsNoDuplicateCall;
58
Nadav Rotem92df0262012-09-19 08:08:04 +000059 /// Number of bytes allocated statically by the callee.
60 uint64_t AllocatedSize;
Chandler Carruthf2286b02012-03-31 12:42:41 +000061 unsigned NumInstructions, NumVectorInstructions;
62 int FiftyPercentVectorBonus, TenPercentVectorBonus;
63 int VectorBonus;
64
65 // While we walk the potentially-inlined instructions, we build up and
66 // maintain a mapping of simplified values specific to this callsite. The
67 // idea is to propagate any special information we have about arguments to
68 // this call through the inlinable section of the function, and account for
69 // likely simplifications post-inlining. The most important aspect we track
70 // is CFG altering simplifications -- when we prove a basic block dead, that
71 // can cause dramatic shifts in the cost of inlining a function.
72 DenseMap<Value *, Constant *> SimplifiedValues;
73
74 // Keep track of the values which map back (through function arguments) to
75 // allocas on the caller stack which could be simplified through SROA.
76 DenseMap<Value *, Value *> SROAArgValues;
77
78 // The mapping of caller Alloca values to their accumulated cost savings. If
79 // we have to disable SROA for one of the allocas, this tells us how much
80 // cost must be added.
81 DenseMap<Value *, int> SROAArgCosts;
82
83 // Keep track of values which map to a pointer base and constant offset.
84 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
85
86 // Custom simplification helper routines.
87 bool isAllocaDerivedArg(Value *V);
88 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
89 DenseMap<Value *, int>::iterator &CostIt);
90 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
91 void disableSROA(Value *V);
92 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
93 int InstructionCost);
94 bool handleSROACandidate(bool IsSROAValid,
95 DenseMap<Value *, int>::iterator CostIt,
96 int InstructionCost);
97 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
98 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
Chandler Carruthba942042012-12-28 14:23:32 +000099 bool simplifyCallSite(Function *F, CallSite CS);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000100 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
101
102 // Custom analysis routines.
103 bool analyzeBlock(BasicBlock *BB);
104
105 // Disable several entry points to the visitor so we don't accidentally use
106 // them by declaring but not defining them here.
107 void visit(Module *); void visit(Module &);
108 void visit(Function *); void visit(Function &);
109 void visit(BasicBlock *); void visit(BasicBlock &);
110
111 // Provide base case for our instruction visit.
112 bool visitInstruction(Instruction &I);
113
114 // Our visit overrides.
115 bool visitAlloca(AllocaInst &I);
116 bool visitPHI(PHINode &I);
117 bool visitGetElementPtr(GetElementPtrInst &I);
118 bool visitBitCast(BitCastInst &I);
119 bool visitPtrToInt(PtrToIntInst &I);
120 bool visitIntToPtr(IntToPtrInst &I);
121 bool visitCastInst(CastInst &I);
122 bool visitUnaryInstruction(UnaryInstruction &I);
123 bool visitICmp(ICmpInst &I);
124 bool visitSub(BinaryOperator &I);
125 bool visitBinaryOperator(BinaryOperator &I);
126 bool visitLoad(LoadInst &I);
127 bool visitStore(StoreInst &I);
Chandler Carruthba942042012-12-28 14:23:32 +0000128 bool visitExtractValue(ExtractValueInst &I);
129 bool visitInsertValue(InsertValueInst &I);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000130 bool visitCallSite(CallSite CS);
131
132public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000133 CallAnalyzer(const DataLayout *TD, Function &Callee, int Threshold)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000134 : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
Nadav Rotem92df0262012-09-19 08:08:04 +0000135 IsCallerRecursive(false), IsRecursiveCall(false),
James Molloy67ae1352012-12-20 16:04:27 +0000136 ExposesReturnsTwice(false), HasDynamicAlloca(false), ContainsNoDuplicateCall(false),
137 AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
Chandler Carruthf2286b02012-03-31 12:42:41 +0000138 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
139 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
140 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
141 NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLost(0) {
142 }
143
144 bool analyzeCall(CallSite CS);
145
146 int getThreshold() { return Threshold; }
147 int getCost() { return Cost; }
148
149 // Keep a bunch of stats about the cost savings found so we can print them
150 // out when debugging.
151 unsigned NumConstantArgs;
152 unsigned NumConstantOffsetPtrArgs;
153 unsigned NumAllocaArgs;
154 unsigned NumConstantPtrCmps;
155 unsigned NumConstantPtrDiffs;
156 unsigned NumInstructionsSimplified;
157 unsigned SROACostSavings;
158 unsigned SROACostSavingsLost;
159
160 void dump();
161};
162
163} // namespace
164
165/// \brief Test whether the given value is an Alloca-derived function argument.
166bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
167 return SROAArgValues.count(V);
Owen Anderson082bf2a2010-09-09 16:56:42 +0000168}
169
Chandler Carruthf2286b02012-03-31 12:42:41 +0000170/// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
171/// Returns false if V does not map to a SROA-candidate.
172bool CallAnalyzer::lookupSROAArgAndCost(
173 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
174 if (SROAArgValues.empty() || SROAArgCosts.empty())
175 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000176
Chandler Carruthf2286b02012-03-31 12:42:41 +0000177 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
178 if (ArgIt == SROAArgValues.end())
179 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000180
Chandler Carruthf2286b02012-03-31 12:42:41 +0000181 Arg = ArgIt->second;
182 CostIt = SROAArgCosts.find(Arg);
183 return CostIt != SROAArgCosts.end();
Chandler Carruthe8187e02012-03-09 02:49:36 +0000184}
185
Chandler Carruthf2286b02012-03-31 12:42:41 +0000186/// \brief Disable SROA for the candidate marked by this cost iterator.
Chandler Carruthe8187e02012-03-09 02:49:36 +0000187///
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000188/// This marks the candidate as no longer viable for SROA, and adds the cost
Chandler Carruthf2286b02012-03-31 12:42:41 +0000189/// savings associated with it back into the inline cost measurement.
190void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
191 // If we're no longer able to perform SROA we need to undo its cost savings
192 // and prevent subsequent analysis.
193 Cost += CostIt->second;
194 SROACostSavings -= CostIt->second;
195 SROACostSavingsLost += CostIt->second;
196 SROAArgCosts.erase(CostIt);
197}
198
199/// \brief If 'V' maps to a SROA candidate, disable SROA for it.
200void CallAnalyzer::disableSROA(Value *V) {
201 Value *SROAArg;
202 DenseMap<Value *, int>::iterator CostIt;
203 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
204 disableSROA(CostIt);
205}
206
207/// \brief Accumulate the given cost for a particular SROA candidate.
208void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
209 int InstructionCost) {
210 CostIt->second += InstructionCost;
211 SROACostSavings += InstructionCost;
212}
213
214/// \brief Helper for the common pattern of handling a SROA candidate.
215/// Either accumulates the cost savings if the SROA remains valid, or disables
216/// SROA for the candidate.
217bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
218 DenseMap<Value *, int>::iterator CostIt,
219 int InstructionCost) {
220 if (IsSROAValid) {
221 accumulateSROACost(CostIt, InstructionCost);
222 return true;
223 }
224
225 disableSROA(CostIt);
226 return false;
227}
228
229/// \brief Check whether a GEP's indices are all constant.
230///
231/// Respects any simplified values known during the analysis of this callsite.
232bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
233 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
234 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
Chandler Carruthe8187e02012-03-09 02:49:36 +0000235 return false;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000236
Chandler Carruthf2286b02012-03-31 12:42:41 +0000237 return true;
238}
239
240/// \brief Accumulate a constant GEP offset into an APInt if possible.
241///
242/// Returns false if unable to compute the offset for any reason. Respects any
243/// simplified values known during the analysis of this callsite.
244bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
245 if (!TD)
246 return false;
247
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000248 unsigned IntPtrWidth = TD->getPointerSizeInBits();
Chandler Carruthf2286b02012-03-31 12:42:41 +0000249 assert(IntPtrWidth == Offset.getBitWidth());
250
251 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
252 GTI != GTE; ++GTI) {
253 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
254 if (!OpC)
255 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
256 OpC = dyn_cast<ConstantInt>(SimpleOp);
257 if (!OpC)
Chandler Carruthe8187e02012-03-09 02:49:36 +0000258 return false;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000259 if (OpC->isZero()) continue;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000260
Chandler Carruthf2286b02012-03-31 12:42:41 +0000261 // Handle a struct index, which adds its field offset to the pointer.
262 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
263 unsigned ElementIdx = OpC->getZExtValue();
264 const StructLayout *SL = TD->getStructLayout(STy);
265 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
266 continue;
Chandler Carruthe8187e02012-03-09 02:49:36 +0000267 }
Chandler Carruthe8187e02012-03-09 02:49:36 +0000268
Chandler Carruthf2286b02012-03-31 12:42:41 +0000269 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
270 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
271 }
272 return true;
273}
274
275bool CallAnalyzer::visitAlloca(AllocaInst &I) {
276 // FIXME: Check whether inlining will turn a dynamic alloca into a static
277 // alloca, and handle that case.
278
Nadav Rotem92df0262012-09-19 08:08:04 +0000279 // Accumulate the allocated size.
280 if (I.isStaticAlloca()) {
281 Type *Ty = I.getAllocatedType();
282 AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
283 Ty->getPrimitiveSizeInBits());
284 }
285
Bob Wilson28f872f2012-11-19 07:04:35 +0000286 // We will happily inline static alloca instructions.
287 if (I.isStaticAlloca())
Chandler Carruthf2286b02012-03-31 12:42:41 +0000288 return Base::visitAlloca(I);
289
290 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
291 // a variety of reasons, and so we would like to not inline them into
292 // functions which don't currently have a dynamic alloca. This simply
293 // disables inlining altogether in the presence of a dynamic alloca.
294 HasDynamicAlloca = true;
295 return false;
296}
297
298bool CallAnalyzer::visitPHI(PHINode &I) {
299 // FIXME: We should potentially be tracking values through phi nodes,
300 // especially when they collapse to a single value due to deleted CFG edges
301 // during inlining.
302
303 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
304 // though we don't want to propagate it's bonuses. The idea is to disable
305 // SROA if it *might* be used in an inappropriate manner.
306
307 // Phi nodes are always zero-cost.
308 return true;
309}
310
311bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
312 Value *SROAArg;
313 DenseMap<Value *, int>::iterator CostIt;
314 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
315 SROAArg, CostIt);
316
317 // Try to fold GEPs of constant-offset call site argument pointers. This
318 // requires target data and inbounds GEPs.
319 if (TD && I.isInBounds()) {
320 // Check if we have a base + offset for the pointer.
321 Value *Ptr = I.getPointerOperand();
322 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
323 if (BaseAndOffset.first) {
324 // Check if the offset of this GEP is constant, and if so accumulate it
325 // into Offset.
326 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
327 // Non-constant GEPs aren't folded, and disable SROA.
328 if (SROACandidate)
329 disableSROA(CostIt);
330 return false;
331 }
332
333 // Add the result as a new mapping to Base + Offset.
334 ConstantOffsetPtrs[&I] = BaseAndOffset;
335
336 // Also handle SROA candidates here, we already know that the GEP is
337 // all-constant indexed.
338 if (SROACandidate)
339 SROAArgValues[&I] = SROAArg;
340
Chandler Carruthe8187e02012-03-09 02:49:36 +0000341 return true;
342 }
343 }
344
Chandler Carruthf2286b02012-03-31 12:42:41 +0000345 if (isGEPOffsetConstant(I)) {
346 if (SROACandidate)
347 SROAArgValues[&I] = SROAArg;
348
349 // Constant GEPs are modeled as free.
350 return true;
351 }
352
353 // Variable GEPs will require math and will disable SROA.
354 if (SROACandidate)
355 disableSROA(CostIt);
Chandler Carruthe8187e02012-03-09 02:49:36 +0000356 return false;
357}
358
Chandler Carruthf2286b02012-03-31 12:42:41 +0000359bool CallAnalyzer::visitBitCast(BitCastInst &I) {
360 // Propagate constants through bitcasts.
Chandler Carruth73527d32012-12-28 14:43:42 +0000361 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
362 if (!COp)
363 COp = SimplifiedValues.lookup(I.getOperand(0));
364 if (COp)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000365 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
366 SimplifiedValues[&I] = C;
367 return true;
Owen Anderson082bf2a2010-09-09 16:56:42 +0000368 }
Owen Anderson082bf2a2010-09-09 16:56:42 +0000369
Chandler Carruthf2286b02012-03-31 12:42:41 +0000370 // Track base/offsets through casts
371 std::pair<Value *, APInt> BaseAndOffset
372 = ConstantOffsetPtrs.lookup(I.getOperand(0));
373 // Casts don't change the offset, just wrap it up.
374 if (BaseAndOffset.first)
375 ConstantOffsetPtrs[&I] = BaseAndOffset;
376
377 // Also look for SROA candidates here.
378 Value *SROAArg;
379 DenseMap<Value *, int>::iterator CostIt;
380 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
381 SROAArgValues[&I] = SROAArg;
382
383 // Bitcasts are always zero cost.
384 return true;
Owen Anderson082bf2a2010-09-09 16:56:42 +0000385}
386
Chandler Carruthf2286b02012-03-31 12:42:41 +0000387bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
388 // Propagate constants through ptrtoint.
Chandler Carruth73527d32012-12-28 14:43:42 +0000389 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
390 if (!COp)
391 COp = SimplifiedValues.lookup(I.getOperand(0));
392 if (COp)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000393 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
394 SimplifiedValues[&I] = C;
395 return true;
Chandler Carruth274d3772012-03-14 23:19:53 +0000396 }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000397
398 // Track base/offset pairs when converted to a plain integer provided the
399 // integer is large enough to represent the pointer.
400 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000401 if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000402 std::pair<Value *, APInt> BaseAndOffset
403 = ConstantOffsetPtrs.lookup(I.getOperand(0));
404 if (BaseAndOffset.first)
405 ConstantOffsetPtrs[&I] = BaseAndOffset;
406 }
407
408 // This is really weird. Technically, ptrtoint will disable SROA. However,
409 // unless that ptrtoint is *used* somewhere in the live basic blocks after
410 // inlining, it will be nuked, and SROA should proceed. All of the uses which
411 // would block SROA would also block SROA if applied directly to a pointer,
412 // and so we can just add the integer in here. The only places where SROA is
413 // preserved either cannot fire on an integer, or won't in-and-of themselves
414 // disable SROA (ext) w/o some later use that we would see and disable.
415 Value *SROAArg;
416 DenseMap<Value *, int>::iterator CostIt;
417 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
418 SROAArgValues[&I] = SROAArg;
419
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000420 return isInstructionFree(&I, TD);
Chandler Carruth274d3772012-03-14 23:19:53 +0000421}
422
Chandler Carruthf2286b02012-03-31 12:42:41 +0000423bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
424 // Propagate constants through ptrtoint.
Chandler Carruth73527d32012-12-28 14:43:42 +0000425 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
426 if (!COp)
427 COp = SimplifiedValues.lookup(I.getOperand(0));
428 if (COp)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000429 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
430 SimplifiedValues[&I] = C;
431 return true;
432 }
Dan Gohmane4aeec02009-10-13 18:30:07 +0000433
Chandler Carruthf2286b02012-03-31 12:42:41 +0000434 // Track base/offset pairs when round-tripped through a pointer without
435 // modifications provided the integer is not too large.
436 Value *Op = I.getOperand(0);
437 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000438 if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000439 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
440 if (BaseAndOffset.first)
441 ConstantOffsetPtrs[&I] = BaseAndOffset;
442 }
Dan Gohmane4aeec02009-10-13 18:30:07 +0000443
Chandler Carruthf2286b02012-03-31 12:42:41 +0000444 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
445 Value *SROAArg;
446 DenseMap<Value *, int>::iterator CostIt;
447 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
448 SROAArgValues[&I] = SROAArg;
Chandler Carruth274d3772012-03-14 23:19:53 +0000449
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000450 return isInstructionFree(&I, TD);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000451}
452
453bool CallAnalyzer::visitCastInst(CastInst &I) {
454 // Propagate constants through ptrtoint.
Chandler Carruth73527d32012-12-28 14:43:42 +0000455 Constant *COp = dyn_cast<Constant>(I.getOperand(0));
456 if (!COp)
457 COp = SimplifiedValues.lookup(I.getOperand(0));
458 if (COp)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000459 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
460 SimplifiedValues[&I] = C;
461 return true;
462 }
463
464 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
465 disableSROA(I.getOperand(0));
466
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000467 return isInstructionFree(&I, TD);
Chandler Carruthf2286b02012-03-31 12:42:41 +0000468}
469
470bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
471 Value *Operand = I.getOperand(0);
472 Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
473 if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
474 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
475 Ops, TD)) {
476 SimplifiedValues[&I] = C;
477 return true;
478 }
479
480 // Disable any SROA on the argument to arbitrary unary operators.
481 disableSROA(Operand);
482
483 return false;
484}
485
486bool CallAnalyzer::visitICmp(ICmpInst &I) {
487 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
488 // First try to handle simplified comparisons.
489 if (!isa<Constant>(LHS))
490 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
491 LHS = SimpleLHS;
492 if (!isa<Constant>(RHS))
493 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
494 RHS = SimpleRHS;
495 if (Constant *CLHS = dyn_cast<Constant>(LHS))
496 if (Constant *CRHS = dyn_cast<Constant>(RHS))
497 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
498 SimplifiedValues[&I] = C;
499 return true;
500 }
501
502 // Otherwise look for a comparison between constant offset pointers with
503 // a common base.
504 Value *LHSBase, *RHSBase;
505 APInt LHSOffset, RHSOffset;
506 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
507 if (LHSBase) {
508 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
509 if (RHSBase && LHSBase == RHSBase) {
510 // We have common bases, fold the icmp to a constant based on the
511 // offsets.
512 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
513 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
514 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
515 SimplifiedValues[&I] = C;
516 ++NumConstantPtrCmps;
517 return true;
518 }
519 }
520 }
521
522 // If the comparison is an equality comparison with null, we can simplify it
523 // for any alloca-derived argument.
524 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
525 if (isAllocaDerivedArg(I.getOperand(0))) {
526 // We can actually predict the result of comparisons between an
527 // alloca-derived value and null. Note that this fires regardless of
528 // SROA firing.
529 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
530 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
531 : ConstantInt::getFalse(I.getType());
532 return true;
533 }
534
535 // Finally check for SROA candidates in comparisons.
536 Value *SROAArg;
537 DenseMap<Value *, int>::iterator CostIt;
538 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
539 if (isa<ConstantPointerNull>(I.getOperand(1))) {
540 accumulateSROACost(CostIt, InlineConstants::InstrCost);
541 return true;
542 }
543
544 disableSROA(CostIt);
545 }
546
547 return false;
548}
549
550bool CallAnalyzer::visitSub(BinaryOperator &I) {
551 // Try to handle a special case: we can fold computing the difference of two
552 // constant-related pointers.
553 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
554 Value *LHSBase, *RHSBase;
555 APInt LHSOffset, RHSOffset;
556 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
557 if (LHSBase) {
558 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
559 if (RHSBase && LHSBase == RHSBase) {
560 // We have common bases, fold the subtract to a constant based on the
561 // offsets.
562 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
563 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
564 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
565 SimplifiedValues[&I] = C;
566 ++NumConstantPtrDiffs;
567 return true;
568 }
569 }
570 }
571
572 // Otherwise, fall back to the generic logic for simplifying and handling
573 // instructions.
574 return Base::visitSub(I);
575}
576
577bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
578 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
579 if (!isa<Constant>(LHS))
580 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
581 LHS = SimpleLHS;
582 if (!isa<Constant>(RHS))
583 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
584 RHS = SimpleRHS;
585 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
586 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
587 SimplifiedValues[&I] = C;
588 return true;
589 }
590
591 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
592 disableSROA(LHS);
593 disableSROA(RHS);
594
595 return false;
596}
597
598bool CallAnalyzer::visitLoad(LoadInst &I) {
599 Value *SROAArg;
600 DenseMap<Value *, int>::iterator CostIt;
601 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
602 if (I.isSimple()) {
603 accumulateSROACost(CostIt, InlineConstants::InstrCost);
604 return true;
605 }
606
607 disableSROA(CostIt);
608 }
609
610 return false;
611}
612
613bool CallAnalyzer::visitStore(StoreInst &I) {
614 Value *SROAArg;
615 DenseMap<Value *, int>::iterator CostIt;
616 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
617 if (I.isSimple()) {
618 accumulateSROACost(CostIt, InlineConstants::InstrCost);
619 return true;
620 }
621
622 disableSROA(CostIt);
623 }
624
625 return false;
626}
627
Chandler Carruthba942042012-12-28 14:23:32 +0000628bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
629 // Constant folding for extract value is trivial.
630 Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
631 if (!C)
632 C = SimplifiedValues.lookup(I.getAggregateOperand());
633 if (C) {
634 SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
635 return true;
636 }
637
638 // SROA can look through these but give them a cost.
639 return false;
640}
641
642bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
643 // Constant folding for insert value is trivial.
644 Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
645 if (!AggC)
646 AggC = SimplifiedValues.lookup(I.getAggregateOperand());
647 Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
648 if (!InsertedC)
649 InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
650 if (AggC && InsertedC) {
651 SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
652 I.getIndices());
653 return true;
654 }
655
656 // SROA can look through these but give them a cost.
657 return false;
658}
659
660/// \brief Try to simplify a call site.
661///
662/// Takes a concrete function and callsite and tries to actually simplify it by
663/// analyzing the arguments and call itself with instsimplify. Returns true if
664/// it has simplified the callsite to some other entity (a constant), making it
665/// free.
666bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
667 // FIXME: Using the instsimplify logic directly for this is inefficient
668 // because we have to continually rebuild the argument list even when no
669 // simplifications can be performed. Until that is fixed with remapping
670 // inside of instsimplify, directly constant fold calls here.
671 if (!canConstantFoldCallTo(F))
672 return false;
673
674 // Try to re-map the arguments to constants.
675 SmallVector<Constant *, 4> ConstantArgs;
676 ConstantArgs.reserve(CS.arg_size());
677 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
678 I != E; ++I) {
679 Constant *C = dyn_cast<Constant>(*I);
680 if (!C)
681 C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
682 if (!C)
683 return false; // This argument doesn't map to a constant.
684
685 ConstantArgs.push_back(C);
686 }
687 if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
688 SimplifiedValues[CS.getInstruction()] = C;
689 return true;
690 }
691
692 return false;
693}
694
Chandler Carruthf2286b02012-03-31 12:42:41 +0000695bool CallAnalyzer::visitCallSite(CallSite CS) {
696 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
Bill Wendling034b94b2012-12-19 07:18:57 +0000697 !F.getFnAttributes().hasAttribute(Attribute::ReturnsTwice)) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000698 // This aborts the entire analysis.
699 ExposesReturnsTwice = true;
700 return false;
701 }
James Molloy67ae1352012-12-20 16:04:27 +0000702 if (CS.isCall() &&
703 cast<CallInst>(CS.getInstruction())->hasFnAttr(Attribute::NoDuplicate))
704 ContainsNoDuplicateCall = true;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000705
Chandler Carruthf2286b02012-03-31 12:42:41 +0000706 if (Function *F = CS.getCalledFunction()) {
Chandler Carruthba942042012-12-28 14:23:32 +0000707 // When we have a concrete function, first try to simplify it directly.
708 if (simplifyCallSite(F, CS))
709 return true;
710
711 // Next check if it is an intrinsic we know about.
712 // FIXME: Lift this into part of the InstVisitor.
713 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
714 switch (II->getIntrinsicID()) {
715 default:
716 return Base::visitCallSite(CS);
717
718 case Intrinsic::memset:
719 case Intrinsic::memcpy:
720 case Intrinsic::memmove:
721 // SROA can usually chew through these intrinsics, but they aren't free.
722 return false;
723 }
724 }
725
Chandler Carruthf2286b02012-03-31 12:42:41 +0000726 if (F == CS.getInstruction()->getParent()->getParent()) {
727 // This flag will fully abort the analysis, so don't bother with anything
728 // else.
Nadav Rotem92df0262012-09-19 08:08:04 +0000729 IsRecursiveCall = true;
Chandler Carruthf2286b02012-03-31 12:42:41 +0000730 return false;
731 }
732
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000733 if (!callIsSmall(CS)) {
Chandler Carruthf2286b02012-03-31 12:42:41 +0000734 // We account for the average 1 instruction per call argument setup
735 // here.
736 Cost += CS.arg_size() * InlineConstants::InstrCost;
737
738 // Everything other than inline ASM will also have a significant cost
739 // merely from making the call.
740 if (!isa<InlineAsm>(CS.getCalledValue()))
741 Cost += InlineConstants::CallPenalty;
742 }
743
744 return Base::visitCallSite(CS);
745 }
746
747 // Otherwise we're in a very special case -- an indirect function call. See
748 // if we can be particularly clever about this.
749 Value *Callee = CS.getCalledValue();
750
751 // First, pay the price of the argument setup. We account for the average
752 // 1 instruction per call argument setup here.
753 Cost += CS.arg_size() * InlineConstants::InstrCost;
754
755 // Next, check if this happens to be an indirect function call to a known
756 // function in this inline context. If not, we've done all we can.
757 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
758 if (!F)
759 return Base::visitCallSite(CS);
760
761 // If we have a constant that we are calling as a function, we can peer
762 // through it and see the function target. This happens not infrequently
763 // during devirtualization and so we want to give it a hefty bonus for
764 // inlining, but cap that bonus in the event that inlining wouldn't pan
765 // out. Pretend to inline the function, with a custom threshold.
766 CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
767 if (CA.analyzeCall(CS)) {
768 // We were able to inline the indirect call! Subtract the cost from the
769 // bonus we want to apply, but don't go below zero.
770 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
771 }
772
773 return Base::visitCallSite(CS);
774}
775
776bool CallAnalyzer::visitInstruction(Instruction &I) {
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000777 // Some instructions are free. All of the free intrinsics can also be
778 // handled by SROA, etc.
779 if (isInstructionFree(&I, TD))
780 return true;
781
Chandler Carruthf2286b02012-03-31 12:42:41 +0000782 // We found something we don't understand or can't handle. Mark any SROA-able
783 // values in the operand list as no longer viable.
784 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
785 disableSROA(*OI);
786
787 return false;
788}
789
790
791/// \brief Analyze a basic block for its contribution to the inline cost.
792///
793/// This method walks the analyzer over every instruction in the given basic
794/// block and accounts for their cost during inlining at this callsite. It
795/// aborts early if the threshold has been exceeded or an impossible to inline
796/// construct has been detected. It returns false if inlining is no longer
797/// viable, and true if inlining remains viable.
798bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
799 for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
800 I != E; ++I) {
801 ++NumInstructions;
802 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
803 ++NumVectorInstructions;
804
805 // If the instruction simplified to a constant, there is no cost to this
806 // instruction. Visit the instructions using our InstVisitor to account for
807 // all of the per-instruction logic. The visit tree returns true if we
808 // consumed the instruction in any way, and false if the instruction's base
809 // cost should count against inlining.
810 if (Base::visit(I))
811 ++NumInstructionsSimplified;
812 else
813 Cost += InlineConstants::InstrCost;
814
815 // If the visit this instruction detected an uninlinable pattern, abort.
Nadav Rotem92df0262012-09-19 08:08:04 +0000816 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
817 return false;
818
819 // If the caller is a recursive function then we don't want to inline
820 // functions which allocate a lot of stack space because it would increase
821 // the caller stack usage dramatically.
822 if (IsCallerRecursive &&
823 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
Chandler Carruthf2286b02012-03-31 12:42:41 +0000824 return false;
825
826 if (NumVectorInstructions > NumInstructions/2)
827 VectorBonus = FiftyPercentVectorBonus;
828 else if (NumVectorInstructions > NumInstructions/10)
829 VectorBonus = TenPercentVectorBonus;
830 else
831 VectorBonus = 0;
832
833 // Check if we've past the threshold so we don't spin in huge basic
834 // blocks that will never inline.
Bob Wilson28f872f2012-11-19 07:04:35 +0000835 if (Cost > (Threshold + VectorBonus))
Chandler Carruthf2286b02012-03-31 12:42:41 +0000836 return false;
837 }
838
839 return true;
840}
841
842/// \brief Compute the base pointer and cumulative constant offsets for V.
843///
844/// This strips all constant offsets off of V, leaving it the base pointer, and
845/// accumulates the total constant offset applied in the returned constant. It
846/// returns 0 if V is not a pointer, and returns the constant '0' if there are
847/// no constant offsets applied.
848ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
849 if (!TD || !V->getType()->isPointerTy())
850 return 0;
851
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000852 unsigned IntPtrWidth = TD->getPointerSizeInBits();
Chandler Carruthf2286b02012-03-31 12:42:41 +0000853 APInt Offset = APInt::getNullValue(IntPtrWidth);
854
855 // Even though we don't look through PHI nodes, we could be called on an
856 // instruction in an unreachable block, which may be on a cycle.
857 SmallPtrSet<Value *, 4> Visited;
858 Visited.insert(V);
859 do {
860 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
861 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
862 return 0;
863 V = GEP->getPointerOperand();
864 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
865 V = cast<Operator>(V)->getOperand(0);
866 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
867 if (GA->mayBeOverridden())
868 break;
869 V = GA->getAliasee();
870 } else {
871 break;
872 }
873 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
874 } while (Visited.insert(V));
875
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000876 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
Chandler Carruthf2286b02012-03-31 12:42:41 +0000877 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
878}
879
880/// \brief Analyze a call site for potential inlining.
881///
882/// Returns true if inlining this call is viable, and false if it is not
883/// viable. It computes the cost and adjusts the threshold based on numerous
884/// factors and heuristics. If this method returns false but the computed cost
885/// is below the computed threshold, then inlining was forcibly disabled by
Bob Wilson593423f2012-11-19 07:04:30 +0000886/// some artifact of the routine.
Chandler Carruthf2286b02012-03-31 12:42:41 +0000887bool CallAnalyzer::analyzeCall(CallSite CS) {
Chandler Carruthd6fc2622012-04-11 10:15:10 +0000888 ++NumCallsAnalyzed;
889
Chandler Carruthf2286b02012-03-31 12:42:41 +0000890 // Track whether the post-inlining function would have more than one basic
891 // block. A single basic block is often intended for inlining. Balloon the
892 // threshold by 50% until we pass the single-BB phase.
893 bool SingleBB = true;
894 int SingleBBBonus = Threshold / 2;
895 Threshold += SingleBBBonus;
896
Bob Wilson28f872f2012-11-19 07:04:35 +0000897 // Perform some tweaks to the cost and threshold based on the direct
898 // callsite information.
Chandler Carruthf2286b02012-03-31 12:42:41 +0000899
Bob Wilson28f872f2012-11-19 07:04:35 +0000900 // We want to more aggressively inline vector-dense kernels, so up the
901 // threshold, and we'll lower it if the % of vector instructions gets too
902 // low.
903 assert(NumInstructions == 0);
904 assert(NumVectorInstructions == 0);
905 FiftyPercentVectorBonus = Threshold;
906 TenPercentVectorBonus = Threshold / 2;
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000907
Bob Wilson28f872f2012-11-19 07:04:35 +0000908 // Give out bonuses per argument, as the instructions setting them up will
909 // be gone after inlining.
910 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
911 if (TD && CS.isByValArgument(I)) {
912 // We approximate the number of loads and stores needed by dividing the
913 // size of the byval type by the target's pointer size.
914 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
915 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
916 unsigned PointerSize = TD->getPointerSizeInBits();
917 // Ceiling division.
918 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000919
Bob Wilson28f872f2012-11-19 07:04:35 +0000920 // If it generates more than 8 stores it is likely to be expanded as an
921 // inline memcpy so we take that as an upper bound. Otherwise we assume
922 // one load and one store per word copied.
923 // FIXME: The maxStoresPerMemcpy setting from the target should be used
924 // here instead of a magic number of 8, but it's not available via
925 // DataLayout.
926 NumStores = std::min(NumStores, 8U);
927
928 Cost -= 2 * NumStores * InlineConstants::InstrCost;
929 } else {
930 // For non-byval arguments subtract off one instruction per call
931 // argument.
932 Cost -= InlineConstants::InstrCost;
Benjamin Kramerb6fdd022012-08-07 11:13:19 +0000933 }
Chandler Carruthf2286b02012-03-31 12:42:41 +0000934 }
935
Bob Wilson28f872f2012-11-19 07:04:35 +0000936 // If there is only one call of the function, and it has internal linkage,
937 // the cost of inlining it drops dramatically.
James Molloy67ae1352012-12-20 16:04:27 +0000938 bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
939 &F == CS.getCalledFunction();
940 if (OnlyOneCallAndLocalLinkage)
Bob Wilson28f872f2012-11-19 07:04:35 +0000941 Cost += InlineConstants::LastCallToStaticBonus;
942
943 // If the instruction after the call, or if the normal destination of the
944 // invoke is an unreachable instruction, the function is noreturn. As such,
945 // there is little point in inlining this unless there is literally zero
946 // cost.
947 Instruction *Instr = CS.getInstruction();
948 if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
949 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
950 Threshold = 1;
951 } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
952 Threshold = 1;
953
954 // If this function uses the coldcc calling convention, prefer not to inline
955 // it.
956 if (F.getCallingConv() == CallingConv::Cold)
957 Cost += InlineConstants::ColdccPenalty;
958
959 // Check if we're done. This can happen due to bonuses and penalties.
960 if (Cost > Threshold)
961 return false;
962
Chandler Carruthf2286b02012-03-31 12:42:41 +0000963 if (F.empty())
964 return true;
965
Nadav Rotem92df0262012-09-19 08:08:04 +0000966 Function *Caller = CS.getInstruction()->getParent()->getParent();
967 // Check if the caller function is recursive itself.
968 for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
969 U != E; ++U) {
970 CallSite Site(cast<Value>(*U));
971 if (!Site)
972 continue;
973 Instruction *I = Site.getInstruction();
974 if (I->getParent()->getParent() == Caller) {
975 IsCallerRecursive = true;
976 break;
977 }
978 }
979
Chandler Carruthf2286b02012-03-31 12:42:41 +0000980 // Track whether we've seen a return instruction. The first return
981 // instruction is free, as at least one will usually disappear in inlining.
982 bool HasReturn = false;
983
984 // Populate our simplified values by mapping from function arguments to call
985 // arguments with known important simplifications.
986 CallSite::arg_iterator CAI = CS.arg_begin();
987 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
988 FAI != FAE; ++FAI, ++CAI) {
989 assert(CAI != CS.arg_end());
990 if (Constant *C = dyn_cast<Constant>(CAI))
991 SimplifiedValues[FAI] = C;
992
993 Value *PtrArg = *CAI;
994 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
995 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
996
997 // We can SROA any pointer arguments derived from alloca instructions.
998 if (isa<AllocaInst>(PtrArg)) {
999 SROAArgValues[FAI] = PtrArg;
1000 SROAArgCosts[PtrArg] = 0;
1001 }
1002 }
1003 }
1004 NumConstantArgs = SimplifiedValues.size();
1005 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1006 NumAllocaArgs = SROAArgValues.size();
1007
1008 // The worklist of live basic blocks in the callee *after* inlining. We avoid
1009 // adding basic blocks of the callee which can be proven to be dead for this
1010 // particular call site in order to get more accurate cost estimates. This
1011 // requires a somewhat heavyweight iteration pattern: we need to walk the
1012 // basic blocks in a breadth-first order as we insert live successors. To
1013 // accomplish this, prioritizing for small iterations because we exit after
1014 // crossing our threshold, we use a small-size optimized SetVector.
1015 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1016 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
1017 BBSetVector BBWorklist;
1018 BBWorklist.insert(&F.getEntryBlock());
1019 // Note that we *must not* cache the size, this loop grows the worklist.
1020 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1021 // Bail out the moment we cross the threshold. This means we'll under-count
1022 // the cost, but only when undercounting doesn't matter.
Bob Wilson28f872f2012-11-19 07:04:35 +00001023 if (Cost > (Threshold + VectorBonus))
Chandler Carruthf2286b02012-03-31 12:42:41 +00001024 break;
1025
1026 BasicBlock *BB = BBWorklist[Idx];
1027 if (BB->empty())
Chandler Carruth274d3772012-03-14 23:19:53 +00001028 continue;
Dan Gohmane4aeec02009-10-13 18:30:07 +00001029
Chandler Carruthf2286b02012-03-31 12:42:41 +00001030 // Handle the terminator cost here where we can track returns and other
1031 // function-wide constructs.
1032 TerminatorInst *TI = BB->getTerminator();
Kenneth Uildriks74fa7322010-10-09 22:06:36 +00001033
Chandler Carruthf2286b02012-03-31 12:42:41 +00001034 // We never want to inline functions that contain an indirectbr. This is
1035 // incorrect because all the blockaddress's (in static global initializers
Nadav Rotem92df0262012-09-19 08:08:04 +00001036 // for example) would be referring to the original function, and this
1037 // indirect jump would jump from the inlined copy of the function into the
1038 // original function which is extremely undefined behavior.
Chandler Carruthf2286b02012-03-31 12:42:41 +00001039 // FIXME: This logic isn't really right; we can safely inline functions
1040 // with indirectbr's as long as no other function or global references the
1041 // blockaddress of a block within the current function. And as a QOI issue,
1042 // if someone is using a blockaddress without an indirectbr, and that
1043 // reference somehow ends up in another function or global, we probably
1044 // don't want to inline this function.
1045 if (isa<IndirectBrInst>(TI))
1046 return false;
Andrew Trick5c655412011-10-01 01:27:56 +00001047
Chandler Carruthf2286b02012-03-31 12:42:41 +00001048 if (!HasReturn && isa<ReturnInst>(TI))
1049 HasReturn = true;
1050 else
1051 Cost += InlineConstants::InstrCost;
Andrew Trick5c655412011-10-01 01:27:56 +00001052
Chandler Carruthf2286b02012-03-31 12:42:41 +00001053 // Analyze the cost of this block. If we blow through the threshold, this
1054 // returns false, and we can bail on out.
1055 if (!analyzeBlock(BB)) {
Nadav Rotem92df0262012-09-19 08:08:04 +00001056 if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001057 return false;
Nadav Rotem92df0262012-09-19 08:08:04 +00001058
1059 // If the caller is a recursive function then we don't want to inline
1060 // functions which allocate a lot of stack space because it would increase
1061 // the caller stack usage dramatically.
1062 if (IsCallerRecursive &&
1063 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1064 return false;
1065
Chandler Carruthf2286b02012-03-31 12:42:41 +00001066 break;
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001067 }
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001068
Chandler Carruthf2286b02012-03-31 12:42:41 +00001069 // Add in the live successors by first checking whether we have terminator
1070 // that may be simplified based on the values simplified by this call.
1071 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1072 if (BI->isConditional()) {
1073 Value *Cond = BI->getCondition();
1074 if (ConstantInt *SimpleCond
1075 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1076 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1077 continue;
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001078 }
Chandler Carruthf2286b02012-03-31 12:42:41 +00001079 }
1080 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1081 Value *Cond = SI->getCondition();
1082 if (ConstantInt *SimpleCond
1083 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1084 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1085 continue;
1086 }
1087 }
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001088
Chandler Carruthf2286b02012-03-31 12:42:41 +00001089 // If we're unable to select a particular successor, just count all of
1090 // them.
Nadav Rotem92df0262012-09-19 08:08:04 +00001091 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1092 ++TIdx)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001093 BBWorklist.insert(TI->getSuccessor(TIdx));
1094
1095 // If we had any successors at this point, than post-inlining is likely to
1096 // have them as well. Note that we assume any basic blocks which existed
1097 // due to branches or switches which folded above will also fold after
1098 // inlining.
1099 if (SingleBB && TI->getNumSuccessors() > 1) {
1100 // Take off the bonus we applied to the threshold.
1101 Threshold -= SingleBBBonus;
1102 SingleBB = false;
Eric Christopher8e2da0c2011-02-01 01:16:32 +00001103 }
1104 }
Andrew Trick5c655412011-10-01 01:27:56 +00001105
James Molloy67ae1352012-12-20 16:04:27 +00001106 // If this is a noduplicate call, we can still inline as long as
1107 // inlining this would cause the removal of the caller (so the instruction
1108 // is not actually duplicated, just moved).
1109 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1110 return false;
1111
Chandler Carruthf2286b02012-03-31 12:42:41 +00001112 Threshold += VectorBonus;
1113
Bob Wilson28f872f2012-11-19 07:04:35 +00001114 return Cost < Threshold;
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001115}
1116
Manman Ren286c4dc2012-09-12 05:06:18 +00001117#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthf2286b02012-03-31 12:42:41 +00001118/// \brief Dump stats about this call's analysis.
1119void CallAnalyzer::dump() {
1120#define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
1121 DEBUG_PRINT_STAT(NumConstantArgs);
1122 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1123 DEBUG_PRINT_STAT(NumAllocaArgs);
1124 DEBUG_PRINT_STAT(NumConstantPtrCmps);
1125 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1126 DEBUG_PRINT_STAT(NumInstructionsSimplified);
1127 DEBUG_PRINT_STAT(SROACostSavings);
1128 DEBUG_PRINT_STAT(SROACostSavingsLost);
James Molloy67ae1352012-12-20 16:04:27 +00001129 DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
Chandler Carruthf2286b02012-03-31 12:42:41 +00001130#undef DEBUG_PRINT_STAT
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001131}
Manman Rencc77eec2012-09-06 19:55:56 +00001132#endif
Eric Christopher4e8af6d2011-02-05 00:49:15 +00001133
Chandler Carruthf2286b02012-03-31 12:42:41 +00001134InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
David Chisnallb3815782012-04-06 17:27:41 +00001135 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1136}
Dan Gohmane4aeec02009-10-13 18:30:07 +00001137
David Chisnallb3815782012-04-06 17:27:41 +00001138InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
1139 int Threshold) {
Bob Wilson28f872f2012-11-19 07:04:35 +00001140 // Cannot inline indirect calls.
1141 if (!Callee)
1142 return llvm::InlineCost::getNever();
1143
1144 // Calls to functions with always-inline attributes should be inlined
1145 // whenever possible.
Bill Wendling034b94b2012-12-19 07:18:57 +00001146 if (Callee->getFnAttributes().hasAttribute(Attribute::AlwaysInline)) {
Bob Wilson28f872f2012-11-19 07:04:35 +00001147 if (isInlineViable(*Callee))
1148 return llvm::InlineCost::getAlways();
1149 return llvm::InlineCost::getNever();
1150 }
1151
Dan Gohmane4aeec02009-10-13 18:30:07 +00001152 // Don't inline functions which can be redefined at link-time to mean
Eric Christopherf27e6082010-03-25 04:49:10 +00001153 // something else. Don't inline functions marked noinline or call sites
1154 // marked noinline.
Bob Wilson28f872f2012-11-19 07:04:35 +00001155 if (Callee->mayBeOverridden() ||
Bill Wendling034b94b2012-12-19 07:18:57 +00001156 Callee->getFnAttributes().hasAttribute(Attribute::NoInline) ||
Bill Wendling67658342012-10-09 07:45:08 +00001157 CS.isNoInline())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001158 return llvm::InlineCost::getNever();
1159
Nadav Rotem92df0262012-09-19 08:08:04 +00001160 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
1161 << "...\n");
Andrew Trick5c655412011-10-01 01:27:56 +00001162
Chandler Carruthf2286b02012-03-31 12:42:41 +00001163 CallAnalyzer CA(TD, *Callee, Threshold);
1164 bool ShouldInline = CA.analyzeCall(CS);
Dan Gohmane4aeec02009-10-13 18:30:07 +00001165
Chandler Carruthf2286b02012-03-31 12:42:41 +00001166 DEBUG(CA.dump());
1167
1168 // Check if there was a reason to force inlining or no inlining.
1169 if (!ShouldInline && CA.getCost() < CA.getThreshold())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001170 return InlineCost::getNever();
Bob Wilson28f872f2012-11-19 07:04:35 +00001171 if (ShouldInline && CA.getCost() >= CA.getThreshold())
Dan Gohmane4aeec02009-10-13 18:30:07 +00001172 return InlineCost::getAlways();
Andrew Trick5c655412011-10-01 01:27:56 +00001173
Chandler Carruthf2286b02012-03-31 12:42:41 +00001174 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
Dan Gohmane4aeec02009-10-13 18:30:07 +00001175}
Bob Wilson28f872f2012-11-19 07:04:35 +00001176
1177bool InlineCostAnalyzer::isInlineViable(Function &F) {
Bill Wendling034b94b2012-12-19 07:18:57 +00001178 bool ReturnsTwice =F.getFnAttributes().hasAttribute(Attribute::ReturnsTwice);
Bob Wilson28f872f2012-11-19 07:04:35 +00001179 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1180 // Disallow inlining of functions which contain an indirect branch.
1181 if (isa<IndirectBrInst>(BI->getTerminator()))
1182 return false;
1183
1184 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1185 ++II) {
1186 CallSite CS(II);
1187 if (!CS)
1188 continue;
1189
1190 // Disallow recursive calls.
1191 if (&F == CS.getCalledFunction())
1192 return false;
1193
1194 // Disallow calls which expose returns-twice to a function not previously
1195 // attributed as such.
1196 if (!ReturnsTwice && CS.isCall() &&
1197 cast<CallInst>(CS.getInstruction())->canReturnTwice())
1198 return false;
1199 }
1200 }
1201
1202 return true;
1203}