1*7adc3a2bSChandler Carruth //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2*7adc3a2bSChandler Carruth //
3*7adc3a2bSChandler Carruth //                     The LLVM Compiler Infrastructure
4*7adc3a2bSChandler Carruth //
5*7adc3a2bSChandler Carruth // This file is distributed under the University of Illinois Open Source
6*7adc3a2bSChandler Carruth // License. See LICENSE.TXT for details.
7*7adc3a2bSChandler Carruth //
8*7adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
9*7adc3a2bSChandler Carruth //
10*7adc3a2bSChandler Carruth // This file implements inline cost analysis.
11*7adc3a2bSChandler Carruth //
12*7adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
13*7adc3a2bSChandler Carruth 
14*7adc3a2bSChandler Carruth #include "llvm/Analysis/InlineCost.h"
15*7adc3a2bSChandler Carruth #include "llvm/ADT/STLExtras.h"
16*7adc3a2bSChandler Carruth #include "llvm/ADT/SetVector.h"
17*7adc3a2bSChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
18*7adc3a2bSChandler Carruth #include "llvm/ADT/SmallVector.h"
19*7adc3a2bSChandler Carruth #include "llvm/ADT/Statistic.h"
20*7adc3a2bSChandler Carruth #include "llvm/Analysis/AssumptionCache.h"
21*7adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
22*7adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h"
23*7adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
24*7adc3a2bSChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
25*7adc3a2bSChandler Carruth #include "llvm/IR/CallSite.h"
26*7adc3a2bSChandler Carruth #include "llvm/IR/CallingConv.h"
27*7adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h"
28*7adc3a2bSChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
29*7adc3a2bSChandler Carruth #include "llvm/IR/GlobalAlias.h"
30*7adc3a2bSChandler Carruth #include "llvm/IR/InstVisitor.h"
31*7adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
32*7adc3a2bSChandler Carruth #include "llvm/IR/Operator.h"
33*7adc3a2bSChandler Carruth #include "llvm/Support/Debug.h"
34*7adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h"
35*7adc3a2bSChandler Carruth 
36*7adc3a2bSChandler Carruth using namespace llvm;
37*7adc3a2bSChandler Carruth 
38*7adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost"
39*7adc3a2bSChandler Carruth 
40*7adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
41*7adc3a2bSChandler Carruth 
42*7adc3a2bSChandler Carruth namespace {
43*7adc3a2bSChandler Carruth 
44*7adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
45*7adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
46*7adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
47*7adc3a2bSChandler Carruth 
48*7adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
49*7adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
50*7adc3a2bSChandler Carruth 
51*7adc3a2bSChandler Carruth   /// The cache of @llvm.assume intrinsics.
52*7adc3a2bSChandler Carruth   AssumptionCacheTracker *ACT;
53*7adc3a2bSChandler Carruth 
54*7adc3a2bSChandler Carruth   // The called function.
55*7adc3a2bSChandler Carruth   Function &F;
56*7adc3a2bSChandler Carruth 
57*7adc3a2bSChandler Carruth   // The candidate callsite being analyzed. Please do not use this to do
58*7adc3a2bSChandler Carruth   // analysis in the caller function; we want the inline cost query to be
59*7adc3a2bSChandler Carruth   // easily cacheable. Instead, use the cover function paramHasAttr.
60*7adc3a2bSChandler Carruth   CallSite CandidateCS;
61*7adc3a2bSChandler Carruth 
62*7adc3a2bSChandler Carruth   int Threshold;
63*7adc3a2bSChandler Carruth   int Cost;
64*7adc3a2bSChandler Carruth 
65*7adc3a2bSChandler Carruth   bool IsCallerRecursive;
66*7adc3a2bSChandler Carruth   bool IsRecursiveCall;
67*7adc3a2bSChandler Carruth   bool ExposesReturnsTwice;
68*7adc3a2bSChandler Carruth   bool HasDynamicAlloca;
69*7adc3a2bSChandler Carruth   bool ContainsNoDuplicateCall;
70*7adc3a2bSChandler Carruth   bool HasReturn;
71*7adc3a2bSChandler Carruth   bool HasIndirectBr;
72*7adc3a2bSChandler Carruth   bool HasFrameEscape;
73*7adc3a2bSChandler Carruth 
74*7adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
75*7adc3a2bSChandler Carruth   uint64_t AllocatedSize;
76*7adc3a2bSChandler Carruth   unsigned NumInstructions, NumVectorInstructions;
77*7adc3a2bSChandler Carruth   int FiftyPercentVectorBonus, TenPercentVectorBonus;
78*7adc3a2bSChandler Carruth   int VectorBonus;
79*7adc3a2bSChandler Carruth 
80*7adc3a2bSChandler Carruth   // While we walk the potentially-inlined instructions, we build up and
81*7adc3a2bSChandler Carruth   // maintain a mapping of simplified values specific to this callsite. The
82*7adc3a2bSChandler Carruth   // idea is to propagate any special information we have about arguments to
83*7adc3a2bSChandler Carruth   // this call through the inlinable section of the function, and account for
84*7adc3a2bSChandler Carruth   // likely simplifications post-inlining. The most important aspect we track
85*7adc3a2bSChandler Carruth   // is CFG altering simplifications -- when we prove a basic block dead, that
86*7adc3a2bSChandler Carruth   // can cause dramatic shifts in the cost of inlining a function.
87*7adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
88*7adc3a2bSChandler Carruth 
89*7adc3a2bSChandler Carruth   // Keep track of the values which map back (through function arguments) to
90*7adc3a2bSChandler Carruth   // allocas on the caller stack which could be simplified through SROA.
91*7adc3a2bSChandler Carruth   DenseMap<Value *, Value *> SROAArgValues;
92*7adc3a2bSChandler Carruth 
93*7adc3a2bSChandler Carruth   // The mapping of caller Alloca values to their accumulated cost savings. If
94*7adc3a2bSChandler Carruth   // we have to disable SROA for one of the allocas, this tells us how much
95*7adc3a2bSChandler Carruth   // cost must be added.
96*7adc3a2bSChandler Carruth   DenseMap<Value *, int> SROAArgCosts;
97*7adc3a2bSChandler Carruth 
98*7adc3a2bSChandler Carruth   // Keep track of values which map to a pointer base and constant offset.
99*7adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
100*7adc3a2bSChandler Carruth 
101*7adc3a2bSChandler Carruth   // Custom simplification helper routines.
102*7adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
103*7adc3a2bSChandler Carruth   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
104*7adc3a2bSChandler Carruth                             DenseMap<Value *, int>::iterator &CostIt);
105*7adc3a2bSChandler Carruth   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
106*7adc3a2bSChandler Carruth   void disableSROA(Value *V);
107*7adc3a2bSChandler Carruth   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
108*7adc3a2bSChandler Carruth                           int InstructionCost);
109*7adc3a2bSChandler Carruth   bool isGEPOffsetConstant(GetElementPtrInst &GEP);
110*7adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
111*7adc3a2bSChandler Carruth   bool simplifyCallSite(Function *F, CallSite CS);
112*7adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
113*7adc3a2bSChandler Carruth 
114*7adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
115*7adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
116*7adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
117*7adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
118*7adc3a2bSChandler Carruth   /// itself.
119*7adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
120*7adc3a2bSChandler Carruth 
121*7adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
122*7adc3a2bSChandler Carruth   /// inlined through this particular callsite.
123*7adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
124*7adc3a2bSChandler Carruth 
125*7adc3a2bSChandler Carruth   // Custom analysis routines.
126*7adc3a2bSChandler Carruth   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
127*7adc3a2bSChandler Carruth 
128*7adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
129*7adc3a2bSChandler Carruth   // them by declaring but not defining them here.
130*7adc3a2bSChandler Carruth   void visit(Module *);     void visit(Module &);
131*7adc3a2bSChandler Carruth   void visit(Function *);   void visit(Function &);
132*7adc3a2bSChandler Carruth   void visit(BasicBlock *); void visit(BasicBlock &);
133*7adc3a2bSChandler Carruth 
134*7adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
135*7adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
136*7adc3a2bSChandler Carruth 
137*7adc3a2bSChandler Carruth   // Our visit overrides.
138*7adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
139*7adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
140*7adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
141*7adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
142*7adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
143*7adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
144*7adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
145*7adc3a2bSChandler Carruth   bool visitUnaryInstruction(UnaryInstruction &I);
146*7adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
147*7adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
148*7adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
149*7adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
150*7adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
151*7adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
152*7adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
153*7adc3a2bSChandler Carruth   bool visitCallSite(CallSite CS);
154*7adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
155*7adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
156*7adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
157*7adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
158*7adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
159*7adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
160*7adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
161*7adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
162*7adc3a2bSChandler Carruth 
163*7adc3a2bSChandler Carruth public:
164*7adc3a2bSChandler Carruth   CallAnalyzer(const TargetTransformInfo &TTI, AssumptionCacheTracker *ACT,
165*7adc3a2bSChandler Carruth                Function &Callee, int Threshold, CallSite CSArg)
166*7adc3a2bSChandler Carruth     : TTI(TTI), ACT(ACT), F(Callee), CandidateCS(CSArg), Threshold(Threshold),
167*7adc3a2bSChandler Carruth         Cost(0), IsCallerRecursive(false), IsRecursiveCall(false),
168*7adc3a2bSChandler Carruth         ExposesReturnsTwice(false), HasDynamicAlloca(false),
169*7adc3a2bSChandler Carruth         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
170*7adc3a2bSChandler Carruth         HasFrameEscape(false), AllocatedSize(0), NumInstructions(0),
171*7adc3a2bSChandler Carruth         NumVectorInstructions(0), FiftyPercentVectorBonus(0),
172*7adc3a2bSChandler Carruth         TenPercentVectorBonus(0), VectorBonus(0), NumConstantArgs(0),
173*7adc3a2bSChandler Carruth         NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), NumConstantPtrCmps(0),
174*7adc3a2bSChandler Carruth         NumConstantPtrDiffs(0), NumInstructionsSimplified(0),
175*7adc3a2bSChandler Carruth         SROACostSavings(0), SROACostSavingsLost(0) {}
176*7adc3a2bSChandler Carruth 
177*7adc3a2bSChandler Carruth   bool analyzeCall(CallSite CS);
178*7adc3a2bSChandler Carruth 
179*7adc3a2bSChandler Carruth   int getThreshold() { return Threshold; }
180*7adc3a2bSChandler Carruth   int getCost() { return Cost; }
181*7adc3a2bSChandler Carruth 
182*7adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
183*7adc3a2bSChandler Carruth   // out when debugging.
184*7adc3a2bSChandler Carruth   unsigned NumConstantArgs;
185*7adc3a2bSChandler Carruth   unsigned NumConstantOffsetPtrArgs;
186*7adc3a2bSChandler Carruth   unsigned NumAllocaArgs;
187*7adc3a2bSChandler Carruth   unsigned NumConstantPtrCmps;
188*7adc3a2bSChandler Carruth   unsigned NumConstantPtrDiffs;
189*7adc3a2bSChandler Carruth   unsigned NumInstructionsSimplified;
190*7adc3a2bSChandler Carruth   unsigned SROACostSavings;
191*7adc3a2bSChandler Carruth   unsigned SROACostSavingsLost;
192*7adc3a2bSChandler Carruth 
193*7adc3a2bSChandler Carruth   void dump();
194*7adc3a2bSChandler Carruth };
195*7adc3a2bSChandler Carruth 
196*7adc3a2bSChandler Carruth } // namespace
197*7adc3a2bSChandler Carruth 
198*7adc3a2bSChandler Carruth /// \brief Test whether the given value is an Alloca-derived function argument.
199*7adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
200*7adc3a2bSChandler Carruth   return SROAArgValues.count(V);
201*7adc3a2bSChandler Carruth }
202*7adc3a2bSChandler Carruth 
203*7adc3a2bSChandler Carruth /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
204*7adc3a2bSChandler Carruth /// Returns false if V does not map to a SROA-candidate.
205*7adc3a2bSChandler Carruth bool CallAnalyzer::lookupSROAArgAndCost(
206*7adc3a2bSChandler Carruth     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
207*7adc3a2bSChandler Carruth   if (SROAArgValues.empty() || SROAArgCosts.empty())
208*7adc3a2bSChandler Carruth     return false;
209*7adc3a2bSChandler Carruth 
210*7adc3a2bSChandler Carruth   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
211*7adc3a2bSChandler Carruth   if (ArgIt == SROAArgValues.end())
212*7adc3a2bSChandler Carruth     return false;
213*7adc3a2bSChandler Carruth 
214*7adc3a2bSChandler Carruth   Arg = ArgIt->second;
215*7adc3a2bSChandler Carruth   CostIt = SROAArgCosts.find(Arg);
216*7adc3a2bSChandler Carruth   return CostIt != SROAArgCosts.end();
217*7adc3a2bSChandler Carruth }
218*7adc3a2bSChandler Carruth 
219*7adc3a2bSChandler Carruth /// \brief Disable SROA for the candidate marked by this cost iterator.
220*7adc3a2bSChandler Carruth ///
221*7adc3a2bSChandler Carruth /// This marks the candidate as no longer viable for SROA, and adds the cost
222*7adc3a2bSChandler Carruth /// savings associated with it back into the inline cost measurement.
223*7adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
224*7adc3a2bSChandler Carruth   // If we're no longer able to perform SROA we need to undo its cost savings
225*7adc3a2bSChandler Carruth   // and prevent subsequent analysis.
226*7adc3a2bSChandler Carruth   Cost += CostIt->second;
227*7adc3a2bSChandler Carruth   SROACostSavings -= CostIt->second;
228*7adc3a2bSChandler Carruth   SROACostSavingsLost += CostIt->second;
229*7adc3a2bSChandler Carruth   SROAArgCosts.erase(CostIt);
230*7adc3a2bSChandler Carruth }
231*7adc3a2bSChandler Carruth 
232*7adc3a2bSChandler Carruth /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
233*7adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
234*7adc3a2bSChandler Carruth   Value *SROAArg;
235*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
236*7adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
237*7adc3a2bSChandler Carruth     disableSROA(CostIt);
238*7adc3a2bSChandler Carruth }
239*7adc3a2bSChandler Carruth 
240*7adc3a2bSChandler Carruth /// \brief Accumulate the given cost for a particular SROA candidate.
241*7adc3a2bSChandler Carruth void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
242*7adc3a2bSChandler Carruth                                       int InstructionCost) {
243*7adc3a2bSChandler Carruth   CostIt->second += InstructionCost;
244*7adc3a2bSChandler Carruth   SROACostSavings += InstructionCost;
245*7adc3a2bSChandler Carruth }
246*7adc3a2bSChandler Carruth 
247*7adc3a2bSChandler Carruth /// \brief Check whether a GEP's indices are all constant.
248*7adc3a2bSChandler Carruth ///
249*7adc3a2bSChandler Carruth /// Respects any simplified values known during the analysis of this callsite.
250*7adc3a2bSChandler Carruth bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
251*7adc3a2bSChandler Carruth   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
252*7adc3a2bSChandler Carruth     if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
253*7adc3a2bSChandler Carruth       return false;
254*7adc3a2bSChandler Carruth 
255*7adc3a2bSChandler Carruth   return true;
256*7adc3a2bSChandler Carruth }
257*7adc3a2bSChandler Carruth 
258*7adc3a2bSChandler Carruth /// \brief Accumulate a constant GEP offset into an APInt if possible.
259*7adc3a2bSChandler Carruth ///
260*7adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
261*7adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
262*7adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
263*7adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
264*7adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
265*7adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
266*7adc3a2bSChandler Carruth 
267*7adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
268*7adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
269*7adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
270*7adc3a2bSChandler Carruth     if (!OpC)
271*7adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
272*7adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
273*7adc3a2bSChandler Carruth     if (!OpC)
274*7adc3a2bSChandler Carruth       return false;
275*7adc3a2bSChandler Carruth     if (OpC->isZero()) continue;
276*7adc3a2bSChandler Carruth 
277*7adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
278*7adc3a2bSChandler Carruth     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
279*7adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
280*7adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
281*7adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
282*7adc3a2bSChandler Carruth       continue;
283*7adc3a2bSChandler Carruth     }
284*7adc3a2bSChandler Carruth 
285*7adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
286*7adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
287*7adc3a2bSChandler Carruth   }
288*7adc3a2bSChandler Carruth   return true;
289*7adc3a2bSChandler Carruth }
290*7adc3a2bSChandler Carruth 
291*7adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
292*7adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
293*7adc3a2bSChandler Carruth   // alloca, and handle that case.
294*7adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
295*7adc3a2bSChandler Carruth     if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
296*7adc3a2bSChandler Carruth       ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
297*7adc3a2bSChandler Carruth       assert(AllocSize && "Allocation size not a constant int?");
298*7adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
299*7adc3a2bSChandler Carruth       AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
300*7adc3a2bSChandler Carruth       return Base::visitAlloca(I);
301*7adc3a2bSChandler Carruth     }
302*7adc3a2bSChandler Carruth   }
303*7adc3a2bSChandler Carruth 
304*7adc3a2bSChandler Carruth   // Accumulate the allocated size.
305*7adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
306*7adc3a2bSChandler Carruth     const DataLayout &DL = F.getParent()->getDataLayout();
307*7adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
308*7adc3a2bSChandler Carruth     AllocatedSize += DL.getTypeAllocSize(Ty);
309*7adc3a2bSChandler Carruth   }
310*7adc3a2bSChandler Carruth 
311*7adc3a2bSChandler Carruth   // We will happily inline static alloca instructions.
312*7adc3a2bSChandler Carruth   if (I.isStaticAlloca())
313*7adc3a2bSChandler Carruth     return Base::visitAlloca(I);
314*7adc3a2bSChandler Carruth 
315*7adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
316*7adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
317*7adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
318*7adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
319*7adc3a2bSChandler Carruth   HasDynamicAlloca = true;
320*7adc3a2bSChandler Carruth   return false;
321*7adc3a2bSChandler Carruth }
322*7adc3a2bSChandler Carruth 
323*7adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
324*7adc3a2bSChandler Carruth   // FIXME: We should potentially be tracking values through phi nodes,
325*7adc3a2bSChandler Carruth   // especially when they collapse to a single value due to deleted CFG edges
326*7adc3a2bSChandler Carruth   // during inlining.
327*7adc3a2bSChandler Carruth 
328*7adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
329*7adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
330*7adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
331*7adc3a2bSChandler Carruth 
332*7adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
333*7adc3a2bSChandler Carruth   return true;
334*7adc3a2bSChandler Carruth }
335*7adc3a2bSChandler Carruth 
336*7adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
337*7adc3a2bSChandler Carruth   Value *SROAArg;
338*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
339*7adc3a2bSChandler Carruth   bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
340*7adc3a2bSChandler Carruth                                             SROAArg, CostIt);
341*7adc3a2bSChandler Carruth 
342*7adc3a2bSChandler Carruth   // Try to fold GEPs of constant-offset call site argument pointers. This
343*7adc3a2bSChandler Carruth   // requires target data and inbounds GEPs.
344*7adc3a2bSChandler Carruth   if (I.isInBounds()) {
345*7adc3a2bSChandler Carruth     // Check if we have a base + offset for the pointer.
346*7adc3a2bSChandler Carruth     Value *Ptr = I.getPointerOperand();
347*7adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
348*7adc3a2bSChandler Carruth     if (BaseAndOffset.first) {
349*7adc3a2bSChandler Carruth       // Check if the offset of this GEP is constant, and if so accumulate it
350*7adc3a2bSChandler Carruth       // into Offset.
351*7adc3a2bSChandler Carruth       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
352*7adc3a2bSChandler Carruth         // Non-constant GEPs aren't folded, and disable SROA.
353*7adc3a2bSChandler Carruth         if (SROACandidate)
354*7adc3a2bSChandler Carruth           disableSROA(CostIt);
355*7adc3a2bSChandler Carruth         return false;
356*7adc3a2bSChandler Carruth       }
357*7adc3a2bSChandler Carruth 
358*7adc3a2bSChandler Carruth       // Add the result as a new mapping to Base + Offset.
359*7adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
360*7adc3a2bSChandler Carruth 
361*7adc3a2bSChandler Carruth       // Also handle SROA candidates here, we already know that the GEP is
362*7adc3a2bSChandler Carruth       // all-constant indexed.
363*7adc3a2bSChandler Carruth       if (SROACandidate)
364*7adc3a2bSChandler Carruth         SROAArgValues[&I] = SROAArg;
365*7adc3a2bSChandler Carruth 
366*7adc3a2bSChandler Carruth       return true;
367*7adc3a2bSChandler Carruth     }
368*7adc3a2bSChandler Carruth   }
369*7adc3a2bSChandler Carruth 
370*7adc3a2bSChandler Carruth   if (isGEPOffsetConstant(I)) {
371*7adc3a2bSChandler Carruth     if (SROACandidate)
372*7adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
373*7adc3a2bSChandler Carruth 
374*7adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
375*7adc3a2bSChandler Carruth     return true;
376*7adc3a2bSChandler Carruth   }
377*7adc3a2bSChandler Carruth 
378*7adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
379*7adc3a2bSChandler Carruth   if (SROACandidate)
380*7adc3a2bSChandler Carruth     disableSROA(CostIt);
381*7adc3a2bSChandler Carruth   return false;
382*7adc3a2bSChandler Carruth }
383*7adc3a2bSChandler Carruth 
384*7adc3a2bSChandler Carruth bool CallAnalyzer::visitBitCast(BitCastInst &I) {
385*7adc3a2bSChandler Carruth   // Propagate constants through bitcasts.
386*7adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
387*7adc3a2bSChandler Carruth   if (!COp)
388*7adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
389*7adc3a2bSChandler Carruth   if (COp)
390*7adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
391*7adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
392*7adc3a2bSChandler Carruth       return true;
393*7adc3a2bSChandler Carruth     }
394*7adc3a2bSChandler Carruth 
395*7adc3a2bSChandler Carruth   // Track base/offsets through casts
396*7adc3a2bSChandler Carruth   std::pair<Value *, APInt> BaseAndOffset
397*7adc3a2bSChandler Carruth     = ConstantOffsetPtrs.lookup(I.getOperand(0));
398*7adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
399*7adc3a2bSChandler Carruth   if (BaseAndOffset.first)
400*7adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
401*7adc3a2bSChandler Carruth 
402*7adc3a2bSChandler Carruth   // Also look for SROA candidates here.
403*7adc3a2bSChandler Carruth   Value *SROAArg;
404*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
405*7adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
406*7adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
407*7adc3a2bSChandler Carruth 
408*7adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
409*7adc3a2bSChandler Carruth   return true;
410*7adc3a2bSChandler Carruth }
411*7adc3a2bSChandler Carruth 
412*7adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
413*7adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
414*7adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
415*7adc3a2bSChandler Carruth   if (!COp)
416*7adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
417*7adc3a2bSChandler Carruth   if (COp)
418*7adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
419*7adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
420*7adc3a2bSChandler Carruth       return true;
421*7adc3a2bSChandler Carruth     }
422*7adc3a2bSChandler Carruth 
423*7adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
424*7adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
425*7adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
426*7adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
427*7adc3a2bSChandler Carruth   if (IntegerSize >= DL.getPointerSizeInBits()) {
428*7adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset
429*7adc3a2bSChandler Carruth       = ConstantOffsetPtrs.lookup(I.getOperand(0));
430*7adc3a2bSChandler Carruth     if (BaseAndOffset.first)
431*7adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
432*7adc3a2bSChandler Carruth   }
433*7adc3a2bSChandler Carruth 
434*7adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
435*7adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
436*7adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
437*7adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
438*7adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
439*7adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
440*7adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
441*7adc3a2bSChandler Carruth   Value *SROAArg;
442*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
443*7adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
444*7adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
445*7adc3a2bSChandler Carruth 
446*7adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
447*7adc3a2bSChandler Carruth }
448*7adc3a2bSChandler Carruth 
449*7adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
450*7adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
451*7adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
452*7adc3a2bSChandler Carruth   if (!COp)
453*7adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
454*7adc3a2bSChandler Carruth   if (COp)
455*7adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
456*7adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
457*7adc3a2bSChandler Carruth       return true;
458*7adc3a2bSChandler Carruth     }
459*7adc3a2bSChandler Carruth 
460*7adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
461*7adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
462*7adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
463*7adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
464*7adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
465*7adc3a2bSChandler Carruth   if (IntegerSize <= DL.getPointerSizeInBits()) {
466*7adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
467*7adc3a2bSChandler Carruth     if (BaseAndOffset.first)
468*7adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
469*7adc3a2bSChandler Carruth   }
470*7adc3a2bSChandler Carruth 
471*7adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
472*7adc3a2bSChandler Carruth   Value *SROAArg;
473*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
474*7adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
475*7adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
476*7adc3a2bSChandler Carruth 
477*7adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
478*7adc3a2bSChandler Carruth }
479*7adc3a2bSChandler Carruth 
480*7adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
481*7adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
482*7adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
483*7adc3a2bSChandler Carruth   if (!COp)
484*7adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(I.getOperand(0));
485*7adc3a2bSChandler Carruth   if (COp)
486*7adc3a2bSChandler Carruth     if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
487*7adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
488*7adc3a2bSChandler Carruth       return true;
489*7adc3a2bSChandler Carruth     }
490*7adc3a2bSChandler Carruth 
491*7adc3a2bSChandler Carruth   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
492*7adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
493*7adc3a2bSChandler Carruth 
494*7adc3a2bSChandler Carruth   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
495*7adc3a2bSChandler Carruth }
496*7adc3a2bSChandler Carruth 
497*7adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
498*7adc3a2bSChandler Carruth   Value *Operand = I.getOperand(0);
499*7adc3a2bSChandler Carruth   Constant *COp = dyn_cast<Constant>(Operand);
500*7adc3a2bSChandler Carruth   if (!COp)
501*7adc3a2bSChandler Carruth     COp = SimplifiedValues.lookup(Operand);
502*7adc3a2bSChandler Carruth   if (COp) {
503*7adc3a2bSChandler Carruth     const DataLayout &DL = F.getParent()->getDataLayout();
504*7adc3a2bSChandler Carruth     if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
505*7adc3a2bSChandler Carruth                                                COp, DL)) {
506*7adc3a2bSChandler Carruth       SimplifiedValues[&I] = C;
507*7adc3a2bSChandler Carruth       return true;
508*7adc3a2bSChandler Carruth     }
509*7adc3a2bSChandler Carruth   }
510*7adc3a2bSChandler Carruth 
511*7adc3a2bSChandler Carruth   // Disable any SROA on the argument to arbitrary unary operators.
512*7adc3a2bSChandler Carruth   disableSROA(Operand);
513*7adc3a2bSChandler Carruth 
514*7adc3a2bSChandler Carruth   return false;
515*7adc3a2bSChandler Carruth }
516*7adc3a2bSChandler Carruth 
517*7adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
518*7adc3a2bSChandler Carruth   unsigned ArgNo = A->getArgNo();
519*7adc3a2bSChandler Carruth   return CandidateCS.paramHasAttr(ArgNo+1, Attr);
520*7adc3a2bSChandler Carruth }
521*7adc3a2bSChandler Carruth 
522*7adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
523*7adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
524*7adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
525*7adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
526*7adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
527*7adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
528*7adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
529*7adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
530*7adc3a2bSChandler Carruth       return true;
531*7adc3a2bSChandler Carruth 
532*7adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
533*7adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
534*7adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
535*7adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
536*7adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
537*7adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
538*7adc3a2bSChandler Carruth     // SROA firing.
539*7adc3a2bSChandler Carruth     return true;
540*7adc3a2bSChandler Carruth 
541*7adc3a2bSChandler Carruth   return false;
542*7adc3a2bSChandler Carruth }
543*7adc3a2bSChandler Carruth 
544*7adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
545*7adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
546*7adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
547*7adc3a2bSChandler Carruth   if (!isa<Constant>(LHS))
548*7adc3a2bSChandler Carruth     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
549*7adc3a2bSChandler Carruth       LHS = SimpleLHS;
550*7adc3a2bSChandler Carruth   if (!isa<Constant>(RHS))
551*7adc3a2bSChandler Carruth     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
552*7adc3a2bSChandler Carruth       RHS = SimpleRHS;
553*7adc3a2bSChandler Carruth   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
554*7adc3a2bSChandler Carruth     if (Constant *CRHS = dyn_cast<Constant>(RHS))
555*7adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
556*7adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
557*7adc3a2bSChandler Carruth         return true;
558*7adc3a2bSChandler Carruth       }
559*7adc3a2bSChandler Carruth   }
560*7adc3a2bSChandler Carruth 
561*7adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
562*7adc3a2bSChandler Carruth     return false;
563*7adc3a2bSChandler Carruth 
564*7adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
565*7adc3a2bSChandler Carruth   // a common base.
566*7adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
567*7adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
568*7adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
569*7adc3a2bSChandler Carruth   if (LHSBase) {
570*7adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
571*7adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
572*7adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
573*7adc3a2bSChandler Carruth       // offsets.
574*7adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
575*7adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
576*7adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
577*7adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
578*7adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
579*7adc3a2bSChandler Carruth         return true;
580*7adc3a2bSChandler Carruth       }
581*7adc3a2bSChandler Carruth     }
582*7adc3a2bSChandler Carruth   }
583*7adc3a2bSChandler Carruth 
584*7adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
585*7adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
586*7adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
587*7adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
588*7adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
589*7adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
590*7adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
591*7adc3a2bSChandler Carruth     return true;
592*7adc3a2bSChandler Carruth   }
593*7adc3a2bSChandler Carruth   // Finally check for SROA candidates in comparisons.
594*7adc3a2bSChandler Carruth   Value *SROAArg;
595*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
596*7adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
597*7adc3a2bSChandler Carruth     if (isa<ConstantPointerNull>(I.getOperand(1))) {
598*7adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
599*7adc3a2bSChandler Carruth       return true;
600*7adc3a2bSChandler Carruth     }
601*7adc3a2bSChandler Carruth 
602*7adc3a2bSChandler Carruth     disableSROA(CostIt);
603*7adc3a2bSChandler Carruth   }
604*7adc3a2bSChandler Carruth 
605*7adc3a2bSChandler Carruth   return false;
606*7adc3a2bSChandler Carruth }
607*7adc3a2bSChandler Carruth 
608*7adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
609*7adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
610*7adc3a2bSChandler Carruth   // constant-related pointers.
611*7adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
612*7adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
613*7adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
614*7adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
615*7adc3a2bSChandler Carruth   if (LHSBase) {
616*7adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
617*7adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
618*7adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
619*7adc3a2bSChandler Carruth       // offsets.
620*7adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
621*7adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
622*7adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
623*7adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
624*7adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
625*7adc3a2bSChandler Carruth         return true;
626*7adc3a2bSChandler Carruth       }
627*7adc3a2bSChandler Carruth     }
628*7adc3a2bSChandler Carruth   }
629*7adc3a2bSChandler Carruth 
630*7adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
631*7adc3a2bSChandler Carruth   // instructions.
632*7adc3a2bSChandler Carruth   return Base::visitSub(I);
633*7adc3a2bSChandler Carruth }
634*7adc3a2bSChandler Carruth 
635*7adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
636*7adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
637*7adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
638*7adc3a2bSChandler Carruth   if (!isa<Constant>(LHS))
639*7adc3a2bSChandler Carruth     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
640*7adc3a2bSChandler Carruth       LHS = SimpleLHS;
641*7adc3a2bSChandler Carruth   if (!isa<Constant>(RHS))
642*7adc3a2bSChandler Carruth     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
643*7adc3a2bSChandler Carruth       RHS = SimpleRHS;
644*7adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
645*7adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
646*7adc3a2bSChandler Carruth     SimpleV =
647*7adc3a2bSChandler Carruth         SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
648*7adc3a2bSChandler Carruth   else
649*7adc3a2bSChandler Carruth     SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
650*7adc3a2bSChandler Carruth 
651*7adc3a2bSChandler Carruth   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
652*7adc3a2bSChandler Carruth     SimplifiedValues[&I] = C;
653*7adc3a2bSChandler Carruth     return true;
654*7adc3a2bSChandler Carruth   }
655*7adc3a2bSChandler Carruth 
656*7adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
657*7adc3a2bSChandler Carruth   disableSROA(LHS);
658*7adc3a2bSChandler Carruth   disableSROA(RHS);
659*7adc3a2bSChandler Carruth 
660*7adc3a2bSChandler Carruth   return false;
661*7adc3a2bSChandler Carruth }
662*7adc3a2bSChandler Carruth 
663*7adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
664*7adc3a2bSChandler Carruth   Value *SROAArg;
665*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
666*7adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
667*7adc3a2bSChandler Carruth     if (I.isSimple()) {
668*7adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
669*7adc3a2bSChandler Carruth       return true;
670*7adc3a2bSChandler Carruth     }
671*7adc3a2bSChandler Carruth 
672*7adc3a2bSChandler Carruth     disableSROA(CostIt);
673*7adc3a2bSChandler Carruth   }
674*7adc3a2bSChandler Carruth 
675*7adc3a2bSChandler Carruth   return false;
676*7adc3a2bSChandler Carruth }
677*7adc3a2bSChandler Carruth 
678*7adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
679*7adc3a2bSChandler Carruth   Value *SROAArg;
680*7adc3a2bSChandler Carruth   DenseMap<Value *, int>::iterator CostIt;
681*7adc3a2bSChandler Carruth   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
682*7adc3a2bSChandler Carruth     if (I.isSimple()) {
683*7adc3a2bSChandler Carruth       accumulateSROACost(CostIt, InlineConstants::InstrCost);
684*7adc3a2bSChandler Carruth       return true;
685*7adc3a2bSChandler Carruth     }
686*7adc3a2bSChandler Carruth 
687*7adc3a2bSChandler Carruth     disableSROA(CostIt);
688*7adc3a2bSChandler Carruth   }
689*7adc3a2bSChandler Carruth 
690*7adc3a2bSChandler Carruth   return false;
691*7adc3a2bSChandler Carruth }
692*7adc3a2bSChandler Carruth 
693*7adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
694*7adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
695*7adc3a2bSChandler Carruth   Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
696*7adc3a2bSChandler Carruth   if (!C)
697*7adc3a2bSChandler Carruth     C = SimplifiedValues.lookup(I.getAggregateOperand());
698*7adc3a2bSChandler Carruth   if (C) {
699*7adc3a2bSChandler Carruth     SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
700*7adc3a2bSChandler Carruth     return true;
701*7adc3a2bSChandler Carruth   }
702*7adc3a2bSChandler Carruth 
703*7adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
704*7adc3a2bSChandler Carruth   return false;
705*7adc3a2bSChandler Carruth }
706*7adc3a2bSChandler Carruth 
707*7adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
708*7adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
709*7adc3a2bSChandler Carruth   Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
710*7adc3a2bSChandler Carruth   if (!AggC)
711*7adc3a2bSChandler Carruth     AggC = SimplifiedValues.lookup(I.getAggregateOperand());
712*7adc3a2bSChandler Carruth   Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
713*7adc3a2bSChandler Carruth   if (!InsertedC)
714*7adc3a2bSChandler Carruth     InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
715*7adc3a2bSChandler Carruth   if (AggC && InsertedC) {
716*7adc3a2bSChandler Carruth     SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
717*7adc3a2bSChandler Carruth                                                         I.getIndices());
718*7adc3a2bSChandler Carruth     return true;
719*7adc3a2bSChandler Carruth   }
720*7adc3a2bSChandler Carruth 
721*7adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
722*7adc3a2bSChandler Carruth   return false;
723*7adc3a2bSChandler Carruth }
724*7adc3a2bSChandler Carruth 
725*7adc3a2bSChandler Carruth /// \brief Try to simplify a call site.
726*7adc3a2bSChandler Carruth ///
727*7adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
728*7adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
729*7adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
730*7adc3a2bSChandler Carruth /// free.
731*7adc3a2bSChandler Carruth bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
732*7adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
733*7adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
734*7adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
735*7adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
736*7adc3a2bSChandler Carruth   if (!canConstantFoldCallTo(F))
737*7adc3a2bSChandler Carruth     return false;
738*7adc3a2bSChandler Carruth 
739*7adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
740*7adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
741*7adc3a2bSChandler Carruth   ConstantArgs.reserve(CS.arg_size());
742*7adc3a2bSChandler Carruth   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
743*7adc3a2bSChandler Carruth        I != E; ++I) {
744*7adc3a2bSChandler Carruth     Constant *C = dyn_cast<Constant>(*I);
745*7adc3a2bSChandler Carruth     if (!C)
746*7adc3a2bSChandler Carruth       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
747*7adc3a2bSChandler Carruth     if (!C)
748*7adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
749*7adc3a2bSChandler Carruth 
750*7adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
751*7adc3a2bSChandler Carruth   }
752*7adc3a2bSChandler Carruth   if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
753*7adc3a2bSChandler Carruth     SimplifiedValues[CS.getInstruction()] = C;
754*7adc3a2bSChandler Carruth     return true;
755*7adc3a2bSChandler Carruth   }
756*7adc3a2bSChandler Carruth 
757*7adc3a2bSChandler Carruth   return false;
758*7adc3a2bSChandler Carruth }
759*7adc3a2bSChandler Carruth 
760*7adc3a2bSChandler Carruth bool CallAnalyzer::visitCallSite(CallSite CS) {
761*7adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
762*7adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
763*7adc3a2bSChandler Carruth     // This aborts the entire analysis.
764*7adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
765*7adc3a2bSChandler Carruth     return false;
766*7adc3a2bSChandler Carruth   }
767*7adc3a2bSChandler Carruth   if (CS.isCall() &&
768*7adc3a2bSChandler Carruth       cast<CallInst>(CS.getInstruction())->cannotDuplicate())
769*7adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
770*7adc3a2bSChandler Carruth 
771*7adc3a2bSChandler Carruth   if (Function *F = CS.getCalledFunction()) {
772*7adc3a2bSChandler Carruth     // When we have a concrete function, first try to simplify it directly.
773*7adc3a2bSChandler Carruth     if (simplifyCallSite(F, CS))
774*7adc3a2bSChandler Carruth       return true;
775*7adc3a2bSChandler Carruth 
776*7adc3a2bSChandler Carruth     // Next check if it is an intrinsic we know about.
777*7adc3a2bSChandler Carruth     // FIXME: Lift this into part of the InstVisitor.
778*7adc3a2bSChandler Carruth     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
779*7adc3a2bSChandler Carruth       switch (II->getIntrinsicID()) {
780*7adc3a2bSChandler Carruth       default:
781*7adc3a2bSChandler Carruth         return Base::visitCallSite(CS);
782*7adc3a2bSChandler Carruth 
783*7adc3a2bSChandler Carruth       case Intrinsic::memset:
784*7adc3a2bSChandler Carruth       case Intrinsic::memcpy:
785*7adc3a2bSChandler Carruth       case Intrinsic::memmove:
786*7adc3a2bSChandler Carruth         // SROA can usually chew through these intrinsics, but they aren't free.
787*7adc3a2bSChandler Carruth         return false;
788*7adc3a2bSChandler Carruth       case Intrinsic::localescape:
789*7adc3a2bSChandler Carruth         HasFrameEscape = true;
790*7adc3a2bSChandler Carruth         return false;
791*7adc3a2bSChandler Carruth       }
792*7adc3a2bSChandler Carruth     }
793*7adc3a2bSChandler Carruth 
794*7adc3a2bSChandler Carruth     if (F == CS.getInstruction()->getParent()->getParent()) {
795*7adc3a2bSChandler Carruth       // This flag will fully abort the analysis, so don't bother with anything
796*7adc3a2bSChandler Carruth       // else.
797*7adc3a2bSChandler Carruth       IsRecursiveCall = true;
798*7adc3a2bSChandler Carruth       return false;
799*7adc3a2bSChandler Carruth     }
800*7adc3a2bSChandler Carruth 
801*7adc3a2bSChandler Carruth     if (TTI.isLoweredToCall(F)) {
802*7adc3a2bSChandler Carruth       // We account for the average 1 instruction per call argument setup
803*7adc3a2bSChandler Carruth       // here.
804*7adc3a2bSChandler Carruth       Cost += CS.arg_size() * InlineConstants::InstrCost;
805*7adc3a2bSChandler Carruth 
806*7adc3a2bSChandler Carruth       // Everything other than inline ASM will also have a significant cost
807*7adc3a2bSChandler Carruth       // merely from making the call.
808*7adc3a2bSChandler Carruth       if (!isa<InlineAsm>(CS.getCalledValue()))
809*7adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
810*7adc3a2bSChandler Carruth     }
811*7adc3a2bSChandler Carruth 
812*7adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
813*7adc3a2bSChandler Carruth   }
814*7adc3a2bSChandler Carruth 
815*7adc3a2bSChandler Carruth   // Otherwise we're in a very special case -- an indirect function call. See
816*7adc3a2bSChandler Carruth   // if we can be particularly clever about this.
817*7adc3a2bSChandler Carruth   Value *Callee = CS.getCalledValue();
818*7adc3a2bSChandler Carruth 
819*7adc3a2bSChandler Carruth   // First, pay the price of the argument setup. We account for the average
820*7adc3a2bSChandler Carruth   // 1 instruction per call argument setup here.
821*7adc3a2bSChandler Carruth   Cost += CS.arg_size() * InlineConstants::InstrCost;
822*7adc3a2bSChandler Carruth 
823*7adc3a2bSChandler Carruth   // Next, check if this happens to be an indirect function call to a known
824*7adc3a2bSChandler Carruth   // function in this inline context. If not, we've done all we can.
825*7adc3a2bSChandler Carruth   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
826*7adc3a2bSChandler Carruth   if (!F)
827*7adc3a2bSChandler Carruth     return Base::visitCallSite(CS);
828*7adc3a2bSChandler Carruth 
829*7adc3a2bSChandler Carruth   // If we have a constant that we are calling as a function, we can peer
830*7adc3a2bSChandler Carruth   // through it and see the function target. This happens not infrequently
831*7adc3a2bSChandler Carruth   // during devirtualization and so we want to give it a hefty bonus for
832*7adc3a2bSChandler Carruth   // inlining, but cap that bonus in the event that inlining wouldn't pan
833*7adc3a2bSChandler Carruth   // out. Pretend to inline the function, with a custom threshold.
834*7adc3a2bSChandler Carruth   CallAnalyzer CA(TTI, ACT, *F, InlineConstants::IndirectCallThreshold, CS);
835*7adc3a2bSChandler Carruth   if (CA.analyzeCall(CS)) {
836*7adc3a2bSChandler Carruth     // We were able to inline the indirect call! Subtract the cost from the
837*7adc3a2bSChandler Carruth     // bonus we want to apply, but don't go below zero.
838*7adc3a2bSChandler Carruth     Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
839*7adc3a2bSChandler Carruth   }
840*7adc3a2bSChandler Carruth 
841*7adc3a2bSChandler Carruth   return Base::visitCallSite(CS);
842*7adc3a2bSChandler Carruth }
843*7adc3a2bSChandler Carruth 
844*7adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
845*7adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
846*7adc3a2bSChandler Carruth   bool Free = !HasReturn;
847*7adc3a2bSChandler Carruth   HasReturn = true;
848*7adc3a2bSChandler Carruth   return Free;
849*7adc3a2bSChandler Carruth }
850*7adc3a2bSChandler Carruth 
851*7adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
852*7adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
853*7adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
854*7adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
855*7adc3a2bSChandler Carruth   // which will fold away are also free.
856*7adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
857*7adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
858*7adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
859*7adc3a2bSChandler Carruth }
860*7adc3a2bSChandler Carruth 
861*7adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
862*7adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
863*7adc3a2bSChandler Carruth   // branches.
864*7adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
865*7adc3a2bSChandler Carruth     return true;
866*7adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
867*7adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
868*7adc3a2bSChandler Carruth       return true;
869*7adc3a2bSChandler Carruth 
870*7adc3a2bSChandler Carruth   // Otherwise, we need to accumulate a cost proportional to the number of
871*7adc3a2bSChandler Carruth   // distinct successor blocks. This fan-out in the CFG cannot be represented
872*7adc3a2bSChandler Carruth   // for free even if we can represent the core switch as a jumptable that
873*7adc3a2bSChandler Carruth   // takes a single instruction.
874*7adc3a2bSChandler Carruth   //
875*7adc3a2bSChandler Carruth   // NB: We convert large switches which are just used to initialize large phi
876*7adc3a2bSChandler Carruth   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
877*7adc3a2bSChandler Carruth   // inlining those. It will prevent inlining in cases where the optimization
878*7adc3a2bSChandler Carruth   // does not (yet) fire.
879*7adc3a2bSChandler Carruth   SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
880*7adc3a2bSChandler Carruth   SuccessorBlocks.insert(SI.getDefaultDest());
881*7adc3a2bSChandler Carruth   for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
882*7adc3a2bSChandler Carruth     SuccessorBlocks.insert(I.getCaseSuccessor());
883*7adc3a2bSChandler Carruth   // Add cost corresponding to the number of distinct destinations. The first
884*7adc3a2bSChandler Carruth   // we model as free because of fallthrough.
885*7adc3a2bSChandler Carruth   Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
886*7adc3a2bSChandler Carruth   return false;
887*7adc3a2bSChandler Carruth }
888*7adc3a2bSChandler Carruth 
889*7adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
890*7adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
891*7adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
892*7adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
893*7adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
894*7adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
895*7adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
896*7adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
897*7adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
898*7adc3a2bSChandler Carruth   HasIndirectBr = true;
899*7adc3a2bSChandler Carruth   return false;
900*7adc3a2bSChandler Carruth }
901*7adc3a2bSChandler Carruth 
902*7adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
903*7adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
904*7adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
905*7adc3a2bSChandler Carruth   return false;
906*7adc3a2bSChandler Carruth }
907*7adc3a2bSChandler Carruth 
908*7adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
909*7adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
910*7adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
911*7adc3a2bSChandler Carruth   return false;
912*7adc3a2bSChandler Carruth }
913*7adc3a2bSChandler Carruth 
914*7adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
915*7adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
916*7adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
917*7adc3a2bSChandler Carruth   return false;
918*7adc3a2bSChandler Carruth }
919*7adc3a2bSChandler Carruth 
920*7adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
921*7adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
922*7adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
923*7adc3a2bSChandler Carruth   // code size.
924*7adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
925*7adc3a2bSChandler Carruth }
926*7adc3a2bSChandler Carruth 
927*7adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
928*7adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
929*7adc3a2bSChandler Carruth   // handled by SROA, etc.
930*7adc3a2bSChandler Carruth   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
931*7adc3a2bSChandler Carruth     return true;
932*7adc3a2bSChandler Carruth 
933*7adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
934*7adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
935*7adc3a2bSChandler Carruth   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
936*7adc3a2bSChandler Carruth     disableSROA(*OI);
937*7adc3a2bSChandler Carruth 
938*7adc3a2bSChandler Carruth   return false;
939*7adc3a2bSChandler Carruth }
940*7adc3a2bSChandler Carruth 
941*7adc3a2bSChandler Carruth 
942*7adc3a2bSChandler Carruth /// \brief Analyze a basic block for its contribution to the inline cost.
943*7adc3a2bSChandler Carruth ///
944*7adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
945*7adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
946*7adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
947*7adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
948*7adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
949*7adc3a2bSChandler Carruth bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
950*7adc3a2bSChandler Carruth                                 SmallPtrSetImpl<const Value *> &EphValues) {
951*7adc3a2bSChandler Carruth   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
952*7adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
953*7adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
954*7adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
955*7adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
956*7adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
957*7adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
958*7adc3a2bSChandler Carruth     // hack around it here.
959*7adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
960*7adc3a2bSChandler Carruth       continue;
961*7adc3a2bSChandler Carruth 
962*7adc3a2bSChandler Carruth     // Skip ephemeral values.
963*7adc3a2bSChandler Carruth     if (EphValues.count(I))
964*7adc3a2bSChandler Carruth       continue;
965*7adc3a2bSChandler Carruth 
966*7adc3a2bSChandler Carruth     ++NumInstructions;
967*7adc3a2bSChandler Carruth     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
968*7adc3a2bSChandler Carruth       ++NumVectorInstructions;
969*7adc3a2bSChandler Carruth 
970*7adc3a2bSChandler Carruth     // If the instruction is floating point, and the target says this operation is
971*7adc3a2bSChandler Carruth     // expensive or the function has the "use-soft-float" attribute, this may
972*7adc3a2bSChandler Carruth     // eventually become a library call.  Treat the cost as such.
973*7adc3a2bSChandler Carruth     if (I->getType()->isFloatingPointTy()) {
974*7adc3a2bSChandler Carruth       bool hasSoftFloatAttr = false;
975*7adc3a2bSChandler Carruth 
976*7adc3a2bSChandler Carruth       // If the function has the "use-soft-float" attribute, mark it as expensive.
977*7adc3a2bSChandler Carruth       if (F.hasFnAttribute("use-soft-float")) {
978*7adc3a2bSChandler Carruth         Attribute Attr = F.getFnAttribute("use-soft-float");
979*7adc3a2bSChandler Carruth         StringRef Val = Attr.getValueAsString();
980*7adc3a2bSChandler Carruth         if (Val == "true")
981*7adc3a2bSChandler Carruth           hasSoftFloatAttr = true;
982*7adc3a2bSChandler Carruth       }
983*7adc3a2bSChandler Carruth 
984*7adc3a2bSChandler Carruth       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
985*7adc3a2bSChandler Carruth           hasSoftFloatAttr)
986*7adc3a2bSChandler Carruth         Cost += InlineConstants::CallPenalty;
987*7adc3a2bSChandler Carruth     }
988*7adc3a2bSChandler Carruth 
989*7adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
990*7adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
991*7adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
992*7adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
993*7adc3a2bSChandler Carruth     // cost should count against inlining.
994*7adc3a2bSChandler Carruth     if (Base::visit(I))
995*7adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
996*7adc3a2bSChandler Carruth     else
997*7adc3a2bSChandler Carruth       Cost += InlineConstants::InstrCost;
998*7adc3a2bSChandler Carruth 
999*7adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
1000*7adc3a2bSChandler Carruth     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1001*7adc3a2bSChandler Carruth         HasIndirectBr || HasFrameEscape)
1002*7adc3a2bSChandler Carruth       return false;
1003*7adc3a2bSChandler Carruth 
1004*7adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
1005*7adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
1006*7adc3a2bSChandler Carruth     // the caller stack usage dramatically.
1007*7adc3a2bSChandler Carruth     if (IsCallerRecursive &&
1008*7adc3a2bSChandler Carruth         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1009*7adc3a2bSChandler Carruth       return false;
1010*7adc3a2bSChandler Carruth 
1011*7adc3a2bSChandler Carruth     // Check if we've past the maximum possible threshold so we don't spin in
1012*7adc3a2bSChandler Carruth     // huge basic blocks that will never inline.
1013*7adc3a2bSChandler Carruth     if (Cost > Threshold)
1014*7adc3a2bSChandler Carruth       return false;
1015*7adc3a2bSChandler Carruth   }
1016*7adc3a2bSChandler Carruth 
1017*7adc3a2bSChandler Carruth   return true;
1018*7adc3a2bSChandler Carruth }
1019*7adc3a2bSChandler Carruth 
1020*7adc3a2bSChandler Carruth /// \brief Compute the base pointer and cumulative constant offsets for V.
1021*7adc3a2bSChandler Carruth ///
1022*7adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
1023*7adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
1024*7adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
1025*7adc3a2bSChandler Carruth /// no constant offsets applied.
1026*7adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
1027*7adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
1028*7adc3a2bSChandler Carruth     return nullptr;
1029*7adc3a2bSChandler Carruth 
1030*7adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
1031*7adc3a2bSChandler Carruth   unsigned IntPtrWidth = DL.getPointerSizeInBits();
1032*7adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
1033*7adc3a2bSChandler Carruth 
1034*7adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
1035*7adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
1036*7adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
1037*7adc3a2bSChandler Carruth   Visited.insert(V);
1038*7adc3a2bSChandler Carruth   do {
1039*7adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1040*7adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
1041*7adc3a2bSChandler Carruth         return nullptr;
1042*7adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
1043*7adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1044*7adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
1045*7adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1046*7adc3a2bSChandler Carruth       if (GA->mayBeOverridden())
1047*7adc3a2bSChandler Carruth         break;
1048*7adc3a2bSChandler Carruth       V = GA->getAliasee();
1049*7adc3a2bSChandler Carruth     } else {
1050*7adc3a2bSChandler Carruth       break;
1051*7adc3a2bSChandler Carruth     }
1052*7adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1053*7adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
1054*7adc3a2bSChandler Carruth 
1055*7adc3a2bSChandler Carruth   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
1056*7adc3a2bSChandler Carruth   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
1057*7adc3a2bSChandler Carruth }
1058*7adc3a2bSChandler Carruth 
1059*7adc3a2bSChandler Carruth /// \brief Analyze a call site for potential inlining.
1060*7adc3a2bSChandler Carruth ///
1061*7adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
1062*7adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
1063*7adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
1064*7adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
1065*7adc3a2bSChandler Carruth /// some artifact of the routine.
1066*7adc3a2bSChandler Carruth bool CallAnalyzer::analyzeCall(CallSite CS) {
1067*7adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
1068*7adc3a2bSChandler Carruth 
1069*7adc3a2bSChandler Carruth   // Perform some tweaks to the cost and threshold based on the direct
1070*7adc3a2bSChandler Carruth   // callsite information.
1071*7adc3a2bSChandler Carruth 
1072*7adc3a2bSChandler Carruth   // We want to more aggressively inline vector-dense kernels, so up the
1073*7adc3a2bSChandler Carruth   // threshold, and we'll lower it if the % of vector instructions gets too
1074*7adc3a2bSChandler Carruth   // low. Note that these bonuses are some what arbitrary and evolved over time
1075*7adc3a2bSChandler Carruth   // by accident as much as because they are principled bonuses.
1076*7adc3a2bSChandler Carruth   //
1077*7adc3a2bSChandler Carruth   // FIXME: It would be nice to remove all such bonuses. At least it would be
1078*7adc3a2bSChandler Carruth   // nice to base the bonus values on something more scientific.
1079*7adc3a2bSChandler Carruth   assert(NumInstructions == 0);
1080*7adc3a2bSChandler Carruth   assert(NumVectorInstructions == 0);
1081*7adc3a2bSChandler Carruth   FiftyPercentVectorBonus = 3 * Threshold / 2;
1082*7adc3a2bSChandler Carruth   TenPercentVectorBonus = 3 * Threshold / 4;
1083*7adc3a2bSChandler Carruth   const DataLayout &DL = F.getParent()->getDataLayout();
1084*7adc3a2bSChandler Carruth 
1085*7adc3a2bSChandler Carruth   // Track whether the post-inlining function would have more than one basic
1086*7adc3a2bSChandler Carruth   // block. A single basic block is often intended for inlining. Balloon the
1087*7adc3a2bSChandler Carruth   // threshold by 50% until we pass the single-BB phase.
1088*7adc3a2bSChandler Carruth   bool SingleBB = true;
1089*7adc3a2bSChandler Carruth   int SingleBBBonus = Threshold / 2;
1090*7adc3a2bSChandler Carruth 
1091*7adc3a2bSChandler Carruth   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
1092*7adc3a2bSChandler Carruth   // this Threshold any time, and cost cannot decrease, we can stop processing
1093*7adc3a2bSChandler Carruth   // the rest of the function body.
1094*7adc3a2bSChandler Carruth   Threshold += (SingleBBBonus + FiftyPercentVectorBonus);
1095*7adc3a2bSChandler Carruth 
1096*7adc3a2bSChandler Carruth   // Give out bonuses per argument, as the instructions setting them up will
1097*7adc3a2bSChandler Carruth   // be gone after inlining.
1098*7adc3a2bSChandler Carruth   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
1099*7adc3a2bSChandler Carruth     if (CS.isByValArgument(I)) {
1100*7adc3a2bSChandler Carruth       // We approximate the number of loads and stores needed by dividing the
1101*7adc3a2bSChandler Carruth       // size of the byval type by the target's pointer size.
1102*7adc3a2bSChandler Carruth       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
1103*7adc3a2bSChandler Carruth       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
1104*7adc3a2bSChandler Carruth       unsigned PointerSize = DL.getPointerSizeInBits();
1105*7adc3a2bSChandler Carruth       // Ceiling division.
1106*7adc3a2bSChandler Carruth       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
1107*7adc3a2bSChandler Carruth 
1108*7adc3a2bSChandler Carruth       // If it generates more than 8 stores it is likely to be expanded as an
1109*7adc3a2bSChandler Carruth       // inline memcpy so we take that as an upper bound. Otherwise we assume
1110*7adc3a2bSChandler Carruth       // one load and one store per word copied.
1111*7adc3a2bSChandler Carruth       // FIXME: The maxStoresPerMemcpy setting from the target should be used
1112*7adc3a2bSChandler Carruth       // here instead of a magic number of 8, but it's not available via
1113*7adc3a2bSChandler Carruth       // DataLayout.
1114*7adc3a2bSChandler Carruth       NumStores = std::min(NumStores, 8U);
1115*7adc3a2bSChandler Carruth 
1116*7adc3a2bSChandler Carruth       Cost -= 2 * NumStores * InlineConstants::InstrCost;
1117*7adc3a2bSChandler Carruth     } else {
1118*7adc3a2bSChandler Carruth       // For non-byval arguments subtract off one instruction per call
1119*7adc3a2bSChandler Carruth       // argument.
1120*7adc3a2bSChandler Carruth       Cost -= InlineConstants::InstrCost;
1121*7adc3a2bSChandler Carruth     }
1122*7adc3a2bSChandler Carruth   }
1123*7adc3a2bSChandler Carruth 
1124*7adc3a2bSChandler Carruth   // If there is only one call of the function, and it has internal linkage,
1125*7adc3a2bSChandler Carruth   // the cost of inlining it drops dramatically.
1126*7adc3a2bSChandler Carruth   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
1127*7adc3a2bSChandler Carruth     &F == CS.getCalledFunction();
1128*7adc3a2bSChandler Carruth   if (OnlyOneCallAndLocalLinkage)
1129*7adc3a2bSChandler Carruth     Cost += InlineConstants::LastCallToStaticBonus;
1130*7adc3a2bSChandler Carruth 
1131*7adc3a2bSChandler Carruth   // If the instruction after the call, or if the normal destination of the
1132*7adc3a2bSChandler Carruth   // invoke is an unreachable instruction, the function is noreturn. As such,
1133*7adc3a2bSChandler Carruth   // there is little point in inlining this unless there is literally zero
1134*7adc3a2bSChandler Carruth   // cost.
1135*7adc3a2bSChandler Carruth   Instruction *Instr = CS.getInstruction();
1136*7adc3a2bSChandler Carruth   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
1137*7adc3a2bSChandler Carruth     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
1138*7adc3a2bSChandler Carruth       Threshold = 0;
1139*7adc3a2bSChandler Carruth   } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
1140*7adc3a2bSChandler Carruth     Threshold = 0;
1141*7adc3a2bSChandler Carruth 
1142*7adc3a2bSChandler Carruth   // If this function uses the coldcc calling convention, prefer not to inline
1143*7adc3a2bSChandler Carruth   // it.
1144*7adc3a2bSChandler Carruth   if (F.getCallingConv() == CallingConv::Cold)
1145*7adc3a2bSChandler Carruth     Cost += InlineConstants::ColdccPenalty;
1146*7adc3a2bSChandler Carruth 
1147*7adc3a2bSChandler Carruth   // Check if we're done. This can happen due to bonuses and penalties.
1148*7adc3a2bSChandler Carruth   if (Cost > Threshold)
1149*7adc3a2bSChandler Carruth     return false;
1150*7adc3a2bSChandler Carruth 
1151*7adc3a2bSChandler Carruth   if (F.empty())
1152*7adc3a2bSChandler Carruth     return true;
1153*7adc3a2bSChandler Carruth 
1154*7adc3a2bSChandler Carruth   Function *Caller = CS.getInstruction()->getParent()->getParent();
1155*7adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
1156*7adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
1157*7adc3a2bSChandler Carruth     CallSite Site(U);
1158*7adc3a2bSChandler Carruth     if (!Site)
1159*7adc3a2bSChandler Carruth       continue;
1160*7adc3a2bSChandler Carruth     Instruction *I = Site.getInstruction();
1161*7adc3a2bSChandler Carruth     if (I->getParent()->getParent() == Caller) {
1162*7adc3a2bSChandler Carruth       IsCallerRecursive = true;
1163*7adc3a2bSChandler Carruth       break;
1164*7adc3a2bSChandler Carruth     }
1165*7adc3a2bSChandler Carruth   }
1166*7adc3a2bSChandler Carruth 
1167*7adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
1168*7adc3a2bSChandler Carruth   // arguments with known important simplifications.
1169*7adc3a2bSChandler Carruth   CallSite::arg_iterator CAI = CS.arg_begin();
1170*7adc3a2bSChandler Carruth   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1171*7adc3a2bSChandler Carruth        FAI != FAE; ++FAI, ++CAI) {
1172*7adc3a2bSChandler Carruth     assert(CAI != CS.arg_end());
1173*7adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
1174*7adc3a2bSChandler Carruth       SimplifiedValues[FAI] = C;
1175*7adc3a2bSChandler Carruth 
1176*7adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
1177*7adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1178*7adc3a2bSChandler Carruth       ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
1179*7adc3a2bSChandler Carruth 
1180*7adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
1181*7adc3a2bSChandler Carruth       if (isa<AllocaInst>(PtrArg)) {
1182*7adc3a2bSChandler Carruth         SROAArgValues[FAI] = PtrArg;
1183*7adc3a2bSChandler Carruth         SROAArgCosts[PtrArg] = 0;
1184*7adc3a2bSChandler Carruth       }
1185*7adc3a2bSChandler Carruth     }
1186*7adc3a2bSChandler Carruth   }
1187*7adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
1188*7adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1189*7adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
1190*7adc3a2bSChandler Carruth 
1191*7adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
1192*7adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
1193*7adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
1194*7adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
1195*7adc3a2bSChandler Carruth   CodeMetrics::collectEphemeralValues(&F, &ACT->getAssumptionCache(F), EphValues);
1196*7adc3a2bSChandler Carruth 
1197*7adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
1198*7adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
1199*7adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
1200*7adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
1201*7adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
1202*7adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
1203*7adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
1204*7adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1205*7adc3a2bSChandler Carruth                                   SmallPtrSet<BasicBlock *, 16> > BBSetVector;
1206*7adc3a2bSChandler Carruth   BBSetVector BBWorklist;
1207*7adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
1208*7adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
1209*7adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1210*7adc3a2bSChandler Carruth     // Bail out the moment we cross the threshold. This means we'll under-count
1211*7adc3a2bSChandler Carruth     // the cost, but only when undercounting doesn't matter.
1212*7adc3a2bSChandler Carruth     if (Cost > Threshold)
1213*7adc3a2bSChandler Carruth       break;
1214*7adc3a2bSChandler Carruth 
1215*7adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
1216*7adc3a2bSChandler Carruth     if (BB->empty())
1217*7adc3a2bSChandler Carruth       continue;
1218*7adc3a2bSChandler Carruth 
1219*7adc3a2bSChandler Carruth     // Disallow inlining a blockaddress. A blockaddress only has defined
1220*7adc3a2bSChandler Carruth     // behavior for an indirect branch in the same function, and we do not
1221*7adc3a2bSChandler Carruth     // currently support inlining indirect branches. But, the inliner may not
1222*7adc3a2bSChandler Carruth     // see an indirect branch that ends up being dead code at a particular call
1223*7adc3a2bSChandler Carruth     // site. If the blockaddress escapes the function, e.g., via a global
1224*7adc3a2bSChandler Carruth     // variable, inlining may lead to an invalid cross-function reference.
1225*7adc3a2bSChandler Carruth     if (BB->hasAddressTaken())
1226*7adc3a2bSChandler Carruth       return false;
1227*7adc3a2bSChandler Carruth 
1228*7adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
1229*7adc3a2bSChandler Carruth     // returns false, and we can bail on out.
1230*7adc3a2bSChandler Carruth     if (!analyzeBlock(BB, EphValues)) {
1231*7adc3a2bSChandler Carruth       if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1232*7adc3a2bSChandler Carruth           HasIndirectBr || HasFrameEscape)
1233*7adc3a2bSChandler Carruth         return false;
1234*7adc3a2bSChandler Carruth 
1235*7adc3a2bSChandler Carruth       // If the caller is a recursive function then we don't want to inline
1236*7adc3a2bSChandler Carruth       // functions which allocate a lot of stack space because it would increase
1237*7adc3a2bSChandler Carruth       // the caller stack usage dramatically.
1238*7adc3a2bSChandler Carruth       if (IsCallerRecursive &&
1239*7adc3a2bSChandler Carruth           AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1240*7adc3a2bSChandler Carruth         return false;
1241*7adc3a2bSChandler Carruth 
1242*7adc3a2bSChandler Carruth       break;
1243*7adc3a2bSChandler Carruth     }
1244*7adc3a2bSChandler Carruth 
1245*7adc3a2bSChandler Carruth     TerminatorInst *TI = BB->getTerminator();
1246*7adc3a2bSChandler Carruth 
1247*7adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
1248*7adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
1249*7adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1250*7adc3a2bSChandler Carruth       if (BI->isConditional()) {
1251*7adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
1252*7adc3a2bSChandler Carruth         if (ConstantInt *SimpleCond
1253*7adc3a2bSChandler Carruth               = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1254*7adc3a2bSChandler Carruth           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1255*7adc3a2bSChandler Carruth           continue;
1256*7adc3a2bSChandler Carruth         }
1257*7adc3a2bSChandler Carruth       }
1258*7adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1259*7adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
1260*7adc3a2bSChandler Carruth       if (ConstantInt *SimpleCond
1261*7adc3a2bSChandler Carruth             = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1262*7adc3a2bSChandler Carruth         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1263*7adc3a2bSChandler Carruth         continue;
1264*7adc3a2bSChandler Carruth       }
1265*7adc3a2bSChandler Carruth     }
1266*7adc3a2bSChandler Carruth 
1267*7adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
1268*7adc3a2bSChandler Carruth     // them.
1269*7adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1270*7adc3a2bSChandler Carruth          ++TIdx)
1271*7adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
1272*7adc3a2bSChandler Carruth 
1273*7adc3a2bSChandler Carruth     // If we had any successors at this point, than post-inlining is likely to
1274*7adc3a2bSChandler Carruth     // have them as well. Note that we assume any basic blocks which existed
1275*7adc3a2bSChandler Carruth     // due to branches or switches which folded above will also fold after
1276*7adc3a2bSChandler Carruth     // inlining.
1277*7adc3a2bSChandler Carruth     if (SingleBB && TI->getNumSuccessors() > 1) {
1278*7adc3a2bSChandler Carruth       // Take off the bonus we applied to the threshold.
1279*7adc3a2bSChandler Carruth       Threshold -= SingleBBBonus;
1280*7adc3a2bSChandler Carruth       SingleBB = false;
1281*7adc3a2bSChandler Carruth     }
1282*7adc3a2bSChandler Carruth   }
1283*7adc3a2bSChandler Carruth 
1284*7adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
1285*7adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
1286*7adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
1287*7adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1288*7adc3a2bSChandler Carruth     return false;
1289*7adc3a2bSChandler Carruth 
1290*7adc3a2bSChandler Carruth   // We applied the maximum possible vector bonus at the beginning. Now,
1291*7adc3a2bSChandler Carruth   // subtract the excess bonus, if any, from the Threshold before
1292*7adc3a2bSChandler Carruth   // comparing against Cost.
1293*7adc3a2bSChandler Carruth   if (NumVectorInstructions <= NumInstructions / 10)
1294*7adc3a2bSChandler Carruth     Threshold -= FiftyPercentVectorBonus;
1295*7adc3a2bSChandler Carruth   else if (NumVectorInstructions <= NumInstructions / 2)
1296*7adc3a2bSChandler Carruth     Threshold -= (FiftyPercentVectorBonus - TenPercentVectorBonus);
1297*7adc3a2bSChandler Carruth 
1298*7adc3a2bSChandler Carruth   return Cost < Threshold;
1299*7adc3a2bSChandler Carruth }
1300*7adc3a2bSChandler Carruth 
1301*7adc3a2bSChandler Carruth #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1302*7adc3a2bSChandler Carruth /// \brief Dump stats about this call's analysis.
1303*7adc3a2bSChandler Carruth void CallAnalyzer::dump() {
1304*7adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
1305*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
1306*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1307*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
1308*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
1309*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1310*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
1311*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
1312*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
1313*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
1314*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
1315*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
1316*7adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
1317*7adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
1318*7adc3a2bSChandler Carruth }
1319*7adc3a2bSChandler Carruth #endif
1320*7adc3a2bSChandler Carruth 
1321*7adc3a2bSChandler Carruth INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1322*7adc3a2bSChandler Carruth                       true, true)
1323*7adc3a2bSChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1324*7adc3a2bSChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1325*7adc3a2bSChandler Carruth INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
1326*7adc3a2bSChandler Carruth                     true, true)
1327*7adc3a2bSChandler Carruth 
1328*7adc3a2bSChandler Carruth char InlineCostAnalysis::ID = 0;
1329*7adc3a2bSChandler Carruth 
1330*7adc3a2bSChandler Carruth InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID) {}
1331*7adc3a2bSChandler Carruth 
1332*7adc3a2bSChandler Carruth InlineCostAnalysis::~InlineCostAnalysis() {}
1333*7adc3a2bSChandler Carruth 
1334*7adc3a2bSChandler Carruth void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1335*7adc3a2bSChandler Carruth   AU.setPreservesAll();
1336*7adc3a2bSChandler Carruth   AU.addRequired<AssumptionCacheTracker>();
1337*7adc3a2bSChandler Carruth   AU.addRequired<TargetTransformInfoWrapperPass>();
1338*7adc3a2bSChandler Carruth   CallGraphSCCPass::getAnalysisUsage(AU);
1339*7adc3a2bSChandler Carruth }
1340*7adc3a2bSChandler Carruth 
1341*7adc3a2bSChandler Carruth bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
1342*7adc3a2bSChandler Carruth   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1343*7adc3a2bSChandler Carruth   ACT = &getAnalysis<AssumptionCacheTracker>();
1344*7adc3a2bSChandler Carruth   return false;
1345*7adc3a2bSChandler Carruth }
1346*7adc3a2bSChandler Carruth 
1347*7adc3a2bSChandler Carruth InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
1348*7adc3a2bSChandler Carruth   return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1349*7adc3a2bSChandler Carruth }
1350*7adc3a2bSChandler Carruth 
1351*7adc3a2bSChandler Carruth /// \brief Test that two functions either have or have not the given attribute
1352*7adc3a2bSChandler Carruth ///        at the same time.
1353*7adc3a2bSChandler Carruth template<typename AttrKind>
1354*7adc3a2bSChandler Carruth static bool attributeMatches(Function *F1, Function *F2, AttrKind Attr) {
1355*7adc3a2bSChandler Carruth   return F1->getFnAttribute(Attr) == F2->getFnAttribute(Attr);
1356*7adc3a2bSChandler Carruth }
1357*7adc3a2bSChandler Carruth 
1358*7adc3a2bSChandler Carruth /// \brief Test that there are no attribute conflicts between Caller and Callee
1359*7adc3a2bSChandler Carruth ///        that prevent inlining.
1360*7adc3a2bSChandler Carruth static bool functionsHaveCompatibleAttributes(Function *Caller,
1361*7adc3a2bSChandler Carruth                                               Function *Callee,
1362*7adc3a2bSChandler Carruth                                               TargetTransformInfo &TTI) {
1363*7adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
1364*7adc3a2bSChandler Carruth          attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
1365*7adc3a2bSChandler Carruth          attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
1366*7adc3a2bSChandler Carruth          attributeMatches(Caller, Callee, Attribute::SanitizeThread);
1367*7adc3a2bSChandler Carruth }
1368*7adc3a2bSChandler Carruth 
1369*7adc3a2bSChandler Carruth InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
1370*7adc3a2bSChandler Carruth                                              int Threshold) {
1371*7adc3a2bSChandler Carruth   // Cannot inline indirect calls.
1372*7adc3a2bSChandler Carruth   if (!Callee)
1373*7adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
1374*7adc3a2bSChandler Carruth 
1375*7adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
1376*7adc3a2bSChandler Carruth   // whenever possible.
1377*7adc3a2bSChandler Carruth   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
1378*7adc3a2bSChandler Carruth     if (isInlineViable(*Callee))
1379*7adc3a2bSChandler Carruth       return llvm::InlineCost::getAlways();
1380*7adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
1381*7adc3a2bSChandler Carruth   }
1382*7adc3a2bSChandler Carruth 
1383*7adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
1384*7adc3a2bSChandler Carruth   // always-inline attribute).
1385*7adc3a2bSChandler Carruth   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee,
1386*7adc3a2bSChandler Carruth                                          TTIWP->getTTI(*Callee)))
1387*7adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
1388*7adc3a2bSChandler Carruth 
1389*7adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
1390*7adc3a2bSChandler Carruth   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
1391*7adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
1392*7adc3a2bSChandler Carruth 
1393*7adc3a2bSChandler Carruth   // Don't inline functions which can be redefined at link-time to mean
1394*7adc3a2bSChandler Carruth   // something else.  Don't inline functions marked noinline or call sites
1395*7adc3a2bSChandler Carruth   // marked noinline.
1396*7adc3a2bSChandler Carruth   if (Callee->mayBeOverridden() ||
1397*7adc3a2bSChandler Carruth       Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
1398*7adc3a2bSChandler Carruth     return llvm::InlineCost::getNever();
1399*7adc3a2bSChandler Carruth 
1400*7adc3a2bSChandler Carruth   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
1401*7adc3a2bSChandler Carruth         << "...\n");
1402*7adc3a2bSChandler Carruth 
1403*7adc3a2bSChandler Carruth   CallAnalyzer CA(TTIWP->getTTI(*Callee), ACT, *Callee, Threshold, CS);
1404*7adc3a2bSChandler Carruth   bool ShouldInline = CA.analyzeCall(CS);
1405*7adc3a2bSChandler Carruth 
1406*7adc3a2bSChandler Carruth   DEBUG(CA.dump());
1407*7adc3a2bSChandler Carruth 
1408*7adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
1409*7adc3a2bSChandler Carruth   if (!ShouldInline && CA.getCost() < CA.getThreshold())
1410*7adc3a2bSChandler Carruth     return InlineCost::getNever();
1411*7adc3a2bSChandler Carruth   if (ShouldInline && CA.getCost() >= CA.getThreshold())
1412*7adc3a2bSChandler Carruth     return InlineCost::getAlways();
1413*7adc3a2bSChandler Carruth 
1414*7adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1415*7adc3a2bSChandler Carruth }
1416*7adc3a2bSChandler Carruth 
1417*7adc3a2bSChandler Carruth bool InlineCostAnalysis::isInlineViable(Function &F) {
1418*7adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
1419*7adc3a2bSChandler Carruth   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1420*7adc3a2bSChandler Carruth     // Disallow inlining of functions which contain indirect branches or
1421*7adc3a2bSChandler Carruth     // blockaddresses.
1422*7adc3a2bSChandler Carruth     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
1423*7adc3a2bSChandler Carruth       return false;
1424*7adc3a2bSChandler Carruth 
1425*7adc3a2bSChandler Carruth     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1426*7adc3a2bSChandler Carruth          ++II) {
1427*7adc3a2bSChandler Carruth       CallSite CS(II);
1428*7adc3a2bSChandler Carruth       if (!CS)
1429*7adc3a2bSChandler Carruth         continue;
1430*7adc3a2bSChandler Carruth 
1431*7adc3a2bSChandler Carruth       // Disallow recursive calls.
1432*7adc3a2bSChandler Carruth       if (&F == CS.getCalledFunction())
1433*7adc3a2bSChandler Carruth         return false;
1434*7adc3a2bSChandler Carruth 
1435*7adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
1436*7adc3a2bSChandler Carruth       // attributed as such.
1437*7adc3a2bSChandler Carruth       if (!ReturnsTwice && CS.isCall() &&
1438*7adc3a2bSChandler Carruth           cast<CallInst>(CS.getInstruction())->canReturnTwice())
1439*7adc3a2bSChandler Carruth         return false;
1440*7adc3a2bSChandler Carruth 
1441*7adc3a2bSChandler Carruth       // Disallow inlining functions that call @llvm.localescape. Doing this
1442*7adc3a2bSChandler Carruth       // correctly would require major changes to the inliner.
1443*7adc3a2bSChandler Carruth       if (CS.getCalledFunction() &&
1444*7adc3a2bSChandler Carruth           CS.getCalledFunction()->getIntrinsicID() ==
1445*7adc3a2bSChandler Carruth               llvm::Intrinsic::localescape)
1446*7adc3a2bSChandler Carruth         return false;
1447*7adc3a2bSChandler Carruth     }
1448*7adc3a2bSChandler Carruth   }
1449*7adc3a2bSChandler Carruth 
1450*7adc3a2bSChandler Carruth   return true;
1451*7adc3a2bSChandler Carruth }
1452