17adc3a2bSChandler Carruth //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
27adc3a2bSChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67adc3a2bSChandler Carruth //
77adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
87adc3a2bSChandler Carruth //
97adc3a2bSChandler Carruth // This file implements inline cost analysis.
107adc3a2bSChandler Carruth //
117adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
127adc3a2bSChandler Carruth 
137adc3a2bSChandler Carruth #include "llvm/Analysis/InlineCost.h"
147adc3a2bSChandler Carruth #include "llvm/ADT/STLExtras.h"
157adc3a2bSChandler Carruth #include "llvm/ADT/SetVector.h"
167adc3a2bSChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
177adc3a2bSChandler Carruth #include "llvm/ADT/SmallVector.h"
187adc3a2bSChandler Carruth #include "llvm/ADT/Statistic.h"
19aec2fa35SDaniel Jasper #include "llvm/Analysis/AssumptionCache.h"
2012585b01SEaswaran Raman #include "llvm/Analysis/BlockFrequencyInfo.h"
214c1a1d3cSReid Kleckner #include "llvm/Analysis/CFG.h"
227adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
237adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h"
247adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
25ba9f245bSDavid Green #include "llvm/Analysis/LoopInfo.h"
2671069cf6SEaswaran Raman #include "llvm/Analysis/ProfileSummaryInfo.h"
27f9ca75f1STeresa Johnson #include "llvm/Analysis/TargetLibraryInfo.h"
287adc3a2bSChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
29a4461515SHaicheng Wu #include "llvm/Analysis/ValueTracking.h"
30432a3883SNico Weber #include "llvm/Config/llvm-config.h"
31c965fd94SKirill Naumov #include "llvm/IR/AssemblyAnnotationWriter.h"
327adc3a2bSChandler Carruth #include "llvm/IR/CallingConv.h"
337adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h"
34ba9f245bSDavid Green #include "llvm/IR/Dominators.h"
357adc3a2bSChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
367adc3a2bSChandler Carruth #include "llvm/IR/GlobalAlias.h"
377adc3a2bSChandler Carruth #include "llvm/IR/InstVisitor.h"
387adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
397adc3a2bSChandler Carruth #include "llvm/IR/Operator.h"
407cebf0afSCraig Topper #include "llvm/IR/PatternMatch.h"
414c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
427adc3a2bSChandler Carruth #include "llvm/Support/Debug.h"
43c965fd94SKirill Naumov #include "llvm/Support/FormattedStream.h"
447adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h"
457adc3a2bSChandler Carruth 
467adc3a2bSChandler Carruth using namespace llvm;
477adc3a2bSChandler Carruth 
487adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost"
497adc3a2bSChandler Carruth 
507adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
517adc3a2bSChandler Carruth 
527f37a802STeresa Johnson static cl::opt<int>
537f37a802STeresa Johnson     DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225),
547f37a802STeresa Johnson                      cl::ZeroOrMore,
557f37a802STeresa Johnson                      cl::desc("Default amount of inlining to perform"));
567f37a802STeresa Johnson 
571022b5ebSKirill Naumov static cl::opt<bool> PrintInstructionComments(
581022b5ebSKirill Naumov     "print-instruction-comments", cl::Hidden, cl::init(false),
591022b5ebSKirill Naumov     cl::desc("Prints comments for instruction based on inline cost analysis"));
60c965fd94SKirill Naumov 
611c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold(
62f4bb2f0dSEaswaran Raman     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
63f4bb2f0dSEaswaran Raman     cl::desc("Control the amount of inlining to perform (default = 225)"));
64f4bb2f0dSEaswaran Raman 
65f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold(
66fd3e7a93SDavid Callahan     "inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore,
67f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with inline hint"));
68f4bb2f0dSEaswaran Raman 
6912585b01SEaswaran Raman static cl::opt<int>
7012585b01SEaswaran Raman     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
71fd3e7a93SDavid Callahan                           cl::init(45), cl::ZeroOrMore,
7212585b01SEaswaran Raman                           cl::desc("Threshold for inlining cold callsites"));
7312585b01SEaswaran Raman 
74f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based
75f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and
76f4bb2f0dSEaswaran Raman // BFI.
77f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold(
78fd3e7a93SDavid Callahan     "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore,
79f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with cold attribute"));
80f4bb2f0dSEaswaran Raman 
81de39cb93SDehao Chen static cl::opt<int>
82de39cb93SDehao Chen     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
83de39cb93SDehao Chen                          cl::ZeroOrMore,
84de39cb93SDehao Chen                          cl::desc("Threshold for hot callsites "));
85de39cb93SDehao Chen 
86974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold(
87974d4eeaSEaswaran Raman     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore,
88974d4eeaSEaswaran Raman     cl::desc("Threshold for locally hot callsites "));
89974d4eeaSEaswaran Raman 
90c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq(
91c5fa6358SEaswaran Raman     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
9202a2bb2fSHiroshi Inoue     cl::desc("Maximum block frequency, expressed as a percentage of caller's "
93c5fa6358SEaswaran Raman              "entry frequency, for a callsite to be cold in the absence of "
94c5fa6358SEaswaran Raman              "profile information."));
95c5fa6358SEaswaran Raman 
96974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq(
97974d4eeaSEaswaran Raman     "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore,
98ff77cc75SEaswaran Raman     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
99974d4eeaSEaswaran Raman              "entry frequency, for a callsite to be hot in the absence of "
100974d4eeaSEaswaran Raman              "profile information."));
101974d4eeaSEaswaran Raman 
1024924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost(
103fd3e7a93SDavid Callahan     "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore,
1040812c5beSHaicheng Wu     cl::desc("Compute the full inline cost of a call site even when the cost "
1050812c5beSHaicheng Wu              "exceeds the threshold."));
1060812c5beSHaicheng Wu 
107ed03d948SMehdi Amini static cl::opt<bool> InlineCallerSupersetNoBuiltin(
108ed03d948SMehdi Amini     "inline-caller-superset-nobuiltin", cl::Hidden, cl::init(true),
109ed03d948SMehdi Amini     cl::ZeroOrMore,
110ed03d948SMehdi Amini     cl::desc("Allow inlining when caller has a superset of callee's nobuiltin "
111f9ca75f1STeresa Johnson              "attributes."));
112f9ca75f1STeresa Johnson 
113d48c7859SKirill Naumov static cl::opt<bool> DisableGEPConstOperand(
114d48c7859SKirill Naumov     "disable-gep-const-evaluation", cl::Hidden, cl::init(false),
115d48c7859SKirill Naumov     cl::desc("Disables evaluation of GetElementPtr with constant operands"));
116d48c7859SKirill Naumov 
1177adc3a2bSChandler Carruth namespace {
11806408758SMircea Trofin class InlineCostCallAnalyzer;
119c965fd94SKirill Naumov 
120c965fd94SKirill Naumov // This struct is used to store information about inline cost of a
121c965fd94SKirill Naumov // particular instruction
122c965fd94SKirill Naumov struct InstructionCostDetail {
123b4924f01SMircea Trofin   int CostBefore = 0;
124b4924f01SMircea Trofin   int CostAfter = 0;
125b4924f01SMircea Trofin   int ThresholdBefore = 0;
126b4924f01SMircea Trofin   int ThresholdAfter = 0;
127b4924f01SMircea Trofin 
128b4924f01SMircea Trofin   int getThresholdDelta() const { return ThresholdAfter - ThresholdBefore; }
129b4924f01SMircea Trofin 
130b4924f01SMircea Trofin   int getCostDelta() const { return CostAfter - CostBefore; }
131b4924f01SMircea Trofin 
132b4924f01SMircea Trofin   bool hasThresholdChanged() const { return ThresholdAfter != ThresholdBefore; }
133c965fd94SKirill Naumov };
134c965fd94SKirill Naumov 
1351022b5ebSKirill Naumov class InlineCostAnnotationWriter : public AssemblyAnnotationWriter {
1361022b5ebSKirill Naumov private:
1371022b5ebSKirill Naumov   InlineCostCallAnalyzer *const ICCA;
138c965fd94SKirill Naumov 
1391022b5ebSKirill Naumov public:
1401022b5ebSKirill Naumov   InlineCostAnnotationWriter(InlineCostCallAnalyzer *ICCA) : ICCA(ICCA) {}
141c965fd94SKirill Naumov   virtual void emitInstructionAnnot(const Instruction *I,
1421022b5ebSKirill Naumov                                     formatted_raw_ostream &OS) override;
143c965fd94SKirill Naumov };
144c965fd94SKirill Naumov 
14508e2386dSMircea Trofin /// Carry out call site analysis, in order to evaluate inlinability.
14608e2386dSMircea Trofin /// NOTE: the type is currently used as implementation detail of functions such
14708e2386dSMircea Trofin /// as llvm::getInlineCost. Note the function_ref constructor parameters - the
14808e2386dSMircea Trofin /// expectation is that they come from the outer scope, from the wrapper
14908e2386dSMircea Trofin /// functions. If we want to support constructing CallAnalyzer objects where
15008e2386dSMircea Trofin /// lambdas are provided inline at construction, or where the object needs to
15108e2386dSMircea Trofin /// otherwise survive past the scope of the provided functions, we need to
15208e2386dSMircea Trofin /// revisit the argument types.
1537adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
1547adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
1557adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
1567adc3a2bSChandler Carruth 
15706408758SMircea Trofin protected:
15806408758SMircea Trofin   virtual ~CallAnalyzer() {}
1597adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
1607adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
1617adc3a2bSChandler Carruth 
162aec2fa35SDaniel Jasper   /// Getter for the cache of @llvm.assume intrinsics.
16308e2386dSMircea Trofin   function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
164aec2fa35SDaniel Jasper 
16512585b01SEaswaran Raman   /// Getter for BlockFrequencyInfo
16608e2386dSMircea Trofin   function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
16712585b01SEaswaran Raman 
16871069cf6SEaswaran Raman   /// Profile summary information.
16971069cf6SEaswaran Raman   ProfileSummaryInfo *PSI;
17071069cf6SEaswaran Raman 
171f3d122cdSPiotr Padlewski   /// The called function.
1727adc3a2bSChandler Carruth   Function &F;
1737adc3a2bSChandler Carruth 
17485be8ca8SEric Christopher   // Cache the DataLayout since we use it a lot.
17585be8ca8SEric Christopher   const DataLayout &DL;
17685be8ca8SEric Christopher 
1770812c5beSHaicheng Wu   /// The OptimizationRemarkEmitter available for this compilation.
1780812c5beSHaicheng Wu   OptimizationRemarkEmitter *ORE;
1790812c5beSHaicheng Wu 
180f3d122cdSPiotr Padlewski   /// The candidate callsite being analyzed. Please do not use this to do
181f3d122cdSPiotr Padlewski   /// analysis in the caller function; we want the inline cost query to be
182f3d122cdSPiotr Padlewski   /// easily cacheable. Instead, use the cover function paramHasAttr.
183652168a9SFedor Sergeev   CallBase &CandidateCall;
1847adc3a2bSChandler Carruth 
18506408758SMircea Trofin   /// Extension points for handling callsite features.
18606408758SMircea Trofin   /// Called after a basic block was analyzed.
18706408758SMircea Trofin   virtual void onBlockAnalyzed(const BasicBlock *BB) {}
1881c57cc2bSEaswaran Raman 
189c965fd94SKirill Naumov   /// Called before an instruction was analyzed
190c965fd94SKirill Naumov   virtual void onInstructionAnalysisStart(const Instruction *I) {}
191c965fd94SKirill Naumov 
192c965fd94SKirill Naumov   /// Called after an instruction was analyzed
193c965fd94SKirill Naumov   virtual void onInstructionAnalysisFinish(const Instruction *I) {}
194c965fd94SKirill Naumov 
19506408758SMircea Trofin   /// Called at the end of the analysis of the callsite. Return the outcome of
19606408758SMircea Trofin   /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
19706408758SMircea Trofin   /// the reason it can't.
1985466597fSMircea Trofin   virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
19906408758SMircea Trofin   /// Called when we're about to start processing a basic block, and every time
20006408758SMircea Trofin   /// we are done processing an instruction. Return true if there is no point in
20106408758SMircea Trofin   /// continuing the analysis (e.g. we've determined already the call site is
20206408758SMircea Trofin   /// too expensive to inline)
20306408758SMircea Trofin   virtual bool shouldStop() { return false; }
204eeae45dcSFedor Sergeev 
20506408758SMircea Trofin   /// Called before the analysis of the callee body starts (with callsite
20606408758SMircea Trofin   /// contexts propagated).  It checks callsite-specific information. Return a
20706408758SMircea Trofin   /// reason analysis can't continue if that's the case, or 'true' if it may
20806408758SMircea Trofin   /// continue.
2095466597fSMircea Trofin   virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
21006408758SMircea Trofin   /// Called if the analysis engine decides SROA cannot be done for the given
21106408758SMircea Trofin   /// alloca.
21206408758SMircea Trofin   virtual void onDisableSROA(AllocaInst *Arg) {}
21306408758SMircea Trofin 
21406408758SMircea Trofin   /// Called the analysis engine determines load elimination won't happen.
21506408758SMircea Trofin   virtual void onDisableLoadElimination() {}
21606408758SMircea Trofin 
21706408758SMircea Trofin   /// Called to account for a call.
21806408758SMircea Trofin   virtual void onCallPenalty() {}
21906408758SMircea Trofin 
22006408758SMircea Trofin   /// Called to account for the expectation the inlining would result in a load
22106408758SMircea Trofin   /// elimination.
22206408758SMircea Trofin   virtual void onLoadEliminationOpportunity() {}
22306408758SMircea Trofin 
22406408758SMircea Trofin   /// Called to account for the cost of argument setup for the Call in the
22506408758SMircea Trofin   /// callee's body (not the callsite currently under analysis).
22606408758SMircea Trofin   virtual void onCallArgumentSetup(const CallBase &Call) {}
22706408758SMircea Trofin 
22806408758SMircea Trofin   /// Called to account for a load relative intrinsic.
22906408758SMircea Trofin   virtual void onLoadRelativeIntrinsic() {}
23006408758SMircea Trofin 
23106408758SMircea Trofin   /// Called to account for a lowered call.
23206408758SMircea Trofin   virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
23306408758SMircea Trofin   }
23406408758SMircea Trofin 
23506408758SMircea Trofin   /// Account for a jump table of given size. Return false to stop further
23606408758SMircea Trofin   /// processing the switch instruction
23706408758SMircea Trofin   virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
23806408758SMircea Trofin 
23906408758SMircea Trofin   /// Account for a case cluster of given size. Return false to stop further
24006408758SMircea Trofin   /// processing of the instruction.
24106408758SMircea Trofin   virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
24206408758SMircea Trofin 
24306408758SMircea Trofin   /// Called at the end of processing a switch instruction, with the given
24406408758SMircea Trofin   /// number of case clusters.
24506408758SMircea Trofin   virtual void onFinalizeSwitch(unsigned JumpTableSize,
24606408758SMircea Trofin                                 unsigned NumCaseCluster) {}
24706408758SMircea Trofin 
24806408758SMircea Trofin   /// Called to account for any other instruction not specifically accounted
24906408758SMircea Trofin   /// for.
25014a16faeSMircea Trofin   virtual void onMissedSimplification() {}
25106408758SMircea Trofin 
25206408758SMircea Trofin   /// Start accounting potential benefits due to SROA for the given alloca.
25306408758SMircea Trofin   virtual void onInitializeSROAArg(AllocaInst *Arg) {}
25406408758SMircea Trofin 
25506408758SMircea Trofin   /// Account SROA savings for the AllocaInst value.
25606408758SMircea Trofin   virtual void onAggregateSROAUse(AllocaInst *V) {}
25706408758SMircea Trofin 
25806408758SMircea Trofin   bool handleSROA(Value *V, bool DoNotDisable) {
25906408758SMircea Trofin     // Check for SROA candidates in comparisons.
26006408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
26106408758SMircea Trofin       if (DoNotDisable) {
26206408758SMircea Trofin         onAggregateSROAUse(SROAArg);
26306408758SMircea Trofin         return true;
26406408758SMircea Trofin       }
26506408758SMircea Trofin       disableSROAForArg(SROAArg);
26606408758SMircea Trofin     }
26706408758SMircea Trofin     return false;
26806408758SMircea Trofin   }
2697adc3a2bSChandler Carruth 
270eeae45dcSFedor Sergeev   bool IsCallerRecursive = false;
271eeae45dcSFedor Sergeev   bool IsRecursiveCall = false;
272eeae45dcSFedor Sergeev   bool ExposesReturnsTwice = false;
273eeae45dcSFedor Sergeev   bool HasDynamicAlloca = false;
274eeae45dcSFedor Sergeev   bool ContainsNoDuplicateCall = false;
275eeae45dcSFedor Sergeev   bool HasReturn = false;
276eeae45dcSFedor Sergeev   bool HasIndirectBr = false;
277eeae45dcSFedor Sergeev   bool HasUninlineableIntrinsic = false;
278eeae45dcSFedor Sergeev   bool InitsVargArgs = false;
2797adc3a2bSChandler Carruth 
2807adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
281eeae45dcSFedor Sergeev   uint64_t AllocatedSize = 0;
282eeae45dcSFedor Sergeev   unsigned NumInstructions = 0;
283eeae45dcSFedor Sergeev   unsigned NumVectorInstructions = 0;
284eeae45dcSFedor Sergeev 
285f3d122cdSPiotr Padlewski   /// While we walk the potentially-inlined instructions, we build up and
286f3d122cdSPiotr Padlewski   /// maintain a mapping of simplified values specific to this callsite. The
287f3d122cdSPiotr Padlewski   /// idea is to propagate any special information we have about arguments to
288f3d122cdSPiotr Padlewski   /// this call through the inlinable section of the function, and account for
289f3d122cdSPiotr Padlewski   /// likely simplifications post-inlining. The most important aspect we track
290f3d122cdSPiotr Padlewski   /// is CFG altering simplifications -- when we prove a basic block dead, that
291f3d122cdSPiotr Padlewski   /// can cause dramatic shifts in the cost of inlining a function.
2927adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
2937adc3a2bSChandler Carruth 
294f3d122cdSPiotr Padlewski   /// Keep track of the values which map back (through function arguments) to
295f3d122cdSPiotr Padlewski   /// allocas on the caller stack which could be simplified through SROA.
29606408758SMircea Trofin   DenseMap<Value *, AllocaInst *> SROAArgValues;
297338a6016SMircea Trofin 
29806408758SMircea Trofin   /// Keep track of Allocas for which we believe we may get SROA optimization.
2992e42cc7aSMircea Trofin   DenseSet<AllocaInst *> EnabledSROAAllocas;
3007adc3a2bSChandler Carruth 
301f3d122cdSPiotr Padlewski   /// Keep track of values which map to a pointer base and constant offset.
3027adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
3037adc3a2bSChandler Carruth 
3043739e14aSHaicheng Wu   /// Keep track of dead blocks due to the constant arguments.
3053739e14aSHaicheng Wu   SetVector<BasicBlock *> DeadBlocks;
3063739e14aSHaicheng Wu 
3073739e14aSHaicheng Wu   /// The mapping of the blocks to their known unique successors due to the
3083739e14aSHaicheng Wu   /// constant arguments.
3093739e14aSHaicheng Wu   DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
3103739e14aSHaicheng Wu 
311a4461515SHaicheng Wu   /// Model the elimination of repeated loads that is expected to happen
312a4461515SHaicheng Wu   /// whenever we simplify away the stores that would otherwise cause them to be
313a4461515SHaicheng Wu   /// loads.
314a4461515SHaicheng Wu   bool EnableLoadElimination;
315a4461515SHaicheng Wu   SmallPtrSet<Value *, 16> LoadAddrSet;
31606408758SMircea Trofin 
31706408758SMircea Trofin   AllocaInst *getSROAArgForValueOrNull(Value *V) const {
31806408758SMircea Trofin     auto It = SROAArgValues.find(V);
3192e42cc7aSMircea Trofin     if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
32006408758SMircea Trofin       return nullptr;
32106408758SMircea Trofin     return It->second;
32206408758SMircea Trofin   }
323a4461515SHaicheng Wu 
3247adc3a2bSChandler Carruth   // Custom simplification helper routines.
3257adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
32606408758SMircea Trofin   void disableSROAForArg(AllocaInst *SROAArg);
3277adc3a2bSChandler Carruth   void disableSROA(Value *V);
3283739e14aSHaicheng Wu   void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
329a4461515SHaicheng Wu   void disableLoadElimination();
330201b191bSHaicheng Wu   bool isGEPFree(GetElementPtrInst &GEP);
331d3558b5dSEvgeny Astigeevich   bool canFoldInboundsGEP(GetElementPtrInst &I);
3327adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
333652168a9SFedor Sergeev   bool simplifyCallSite(Function *F, CallBase &Call);
334617f6364SEaswaran Raman   template <typename Callable>
335617f6364SEaswaran Raman   bool simplifyInstruction(Instruction &I, Callable Evaluate);
3367adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
3377adc3a2bSChandler Carruth 
3387adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
3397adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
3407adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
3417adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
3427adc3a2bSChandler Carruth   /// itself.
3437adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
3447adc3a2bSChandler Carruth 
3457adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
3467adc3a2bSChandler Carruth   /// inlined through this particular callsite.
3477adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
3487adc3a2bSChandler Carruth 
349652168a9SFedor Sergeev   /// Return true if size growth is allowed when inlining the callee at \p Call.
350652168a9SFedor Sergeev   bool allowSizeGrowth(CallBase &Call);
3519a3fc17aSEaswaran Raman 
3527adc3a2bSChandler Carruth   // Custom analysis routines.
353c0aa4b75SDavid Bolvansky   InlineResult analyzeBlock(BasicBlock *BB,
354c0aa4b75SDavid Bolvansky                             SmallPtrSetImpl<const Value *> &EphValues);
3557adc3a2bSChandler Carruth 
3567adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
3577adc3a2bSChandler Carruth   // them by declaring but not defining them here.
358567556aaSChad Rosier   void visit(Module *);
359567556aaSChad Rosier   void visit(Module &);
360567556aaSChad Rosier   void visit(Function *);
361567556aaSChad Rosier   void visit(Function &);
362567556aaSChad Rosier   void visit(BasicBlock *);
363567556aaSChad Rosier   void visit(BasicBlock &);
3647adc3a2bSChandler Carruth 
3657adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
3667adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
3677adc3a2bSChandler Carruth 
3687adc3a2bSChandler Carruth   // Our visit overrides.
3697adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
3707adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
3717adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
3727adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
3737adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
3747adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
3757adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
3767adc3a2bSChandler Carruth   bool visitUnaryInstruction(UnaryInstruction &I);
3777adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
3787adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
3797adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
3806cda33baSCraig Topper   bool visitFNeg(UnaryOperator &I);
3817adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
3827adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
3837adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
3847adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
385652168a9SFedor Sergeev   bool visitCallBase(CallBase &Call);
3867adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
3877adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
3883ec848bcSHaicheng Wu   bool visitSelectInst(SelectInst &SI);
3897adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
3907adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
3917adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
3927adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
3937adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
3947adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
3957adc3a2bSChandler Carruth 
3967adc3a2bSChandler Carruth public:
39708e2386dSMircea Trofin   CallAnalyzer(
39808e2386dSMircea Trofin       Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
39908e2386dSMircea Trofin       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
40008e2386dSMircea Trofin       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
40108e2386dSMircea Trofin       ProfileSummaryInfo *PSI = nullptr,
40208e2386dSMircea Trofin       OptimizationRemarkEmitter *ORE = nullptr)
40312585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
4040812c5beSHaicheng Wu         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
40506408758SMircea Trofin         CandidateCall(Call), EnableLoadElimination(true) {}
4067adc3a2bSChandler Carruth 
40793ac81ccSMircea Trofin   InlineResult analyze();
4087adc3a2bSChandler Carruth 
4097f094f7fSKirill Naumov   Optional<Constant*> getSimplifiedValue(Instruction *I) {
4107f094f7fSKirill Naumov     if (SimplifiedValues.find(I) != SimplifiedValues.end())
4117f094f7fSKirill Naumov       return SimplifiedValues[I];
4127f094f7fSKirill Naumov     return None;
4137f094f7fSKirill Naumov   }
4147f094f7fSKirill Naumov 
4157adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
4167adc3a2bSChandler Carruth   // out when debugging.
417eeae45dcSFedor Sergeev   unsigned NumConstantArgs = 0;
418eeae45dcSFedor Sergeev   unsigned NumConstantOffsetPtrArgs = 0;
419eeae45dcSFedor Sergeev   unsigned NumAllocaArgs = 0;
420eeae45dcSFedor Sergeev   unsigned NumConstantPtrCmps = 0;
421eeae45dcSFedor Sergeev   unsigned NumConstantPtrDiffs = 0;
422eeae45dcSFedor Sergeev   unsigned NumInstructionsSimplified = 0;
42376aab66dSMircea Trofin 
42476aab66dSMircea Trofin   void dump();
42576aab66dSMircea Trofin };
426338a6016SMircea Trofin 
42706408758SMircea Trofin /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
42806408758SMircea Trofin /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
42906408758SMircea Trofin class InlineCostCallAnalyzer final : public CallAnalyzer {
43006408758SMircea Trofin   const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
43106408758SMircea Trofin   const bool ComputeFullInlineCost;
43206408758SMircea Trofin   int LoadEliminationCost = 0;
43306408758SMircea Trofin   /// Bonus to be applied when percentage of vector instructions in callee is
43406408758SMircea Trofin   /// high (see more details in updateThreshold).
43506408758SMircea Trofin   int VectorBonus = 0;
43606408758SMircea Trofin   /// Bonus to be applied when the callee has only one reachable basic block.
43706408758SMircea Trofin   int SingleBBBonus = 0;
43806408758SMircea Trofin 
43906408758SMircea Trofin   /// Tunable parameters that control the analysis.
44006408758SMircea Trofin   const InlineParams &Params;
44106408758SMircea Trofin 
4421022b5ebSKirill Naumov   // This DenseMap stores the delta change in cost and threshold after
4431022b5ebSKirill Naumov   // accounting for the given instruction. The map is filled only with the
4441022b5ebSKirill Naumov   // flag PrintInstructionComments on.
4451022b5ebSKirill Naumov   DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
4461022b5ebSKirill Naumov 
44706408758SMircea Trofin   /// Upper bound for the inlining cost. Bonuses are being applied to account
44806408758SMircea Trofin   /// for speculative "expected profit" of the inlining decision.
44906408758SMircea Trofin   int Threshold = 0;
45006408758SMircea Trofin 
45106408758SMircea Trofin   /// Attempt to evaluate indirect calls to boost its inline cost.
45206408758SMircea Trofin   const bool BoostIndirectCalls;
45306408758SMircea Trofin 
4548a4013edSMircea Trofin   /// Ignore the threshold when finalizing analysis.
4558a4013edSMircea Trofin   const bool IgnoreThreshold;
4568a4013edSMircea Trofin 
45706408758SMircea Trofin   /// Inlining cost measured in abstract units, accounts for all the
45806408758SMircea Trofin   /// instructions expected to be executed for a given function invocation.
45906408758SMircea Trofin   /// Instructions that are statically proven to be dead based on call-site
46006408758SMircea Trofin   /// arguments are not counted here.
46106408758SMircea Trofin   int Cost = 0;
46206408758SMircea Trofin 
46306408758SMircea Trofin   bool SingleBB = true;
46406408758SMircea Trofin 
46506408758SMircea Trofin   unsigned SROACostSavings = 0;
46606408758SMircea Trofin   unsigned SROACostSavingsLost = 0;
46706408758SMircea Trofin 
46806408758SMircea Trofin   /// The mapping of caller Alloca values to their accumulated cost savings. If
46906408758SMircea Trofin   /// we have to disable SROA for one of the allocas, this tells us how much
47006408758SMircea Trofin   /// cost must be added.
47106408758SMircea Trofin   DenseMap<AllocaInst *, int> SROAArgCosts;
47206408758SMircea Trofin 
47306408758SMircea Trofin   /// Return true if \p Call is a cold callsite.
47406408758SMircea Trofin   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
47506408758SMircea Trofin 
47606408758SMircea Trofin   /// Update Threshold based on callsite properties such as callee
47706408758SMircea Trofin   /// attributes and callee hotness for PGO builds. The Callee is explicitly
47806408758SMircea Trofin   /// passed to support analyzing indirect calls whose target is inferred by
47906408758SMircea Trofin   /// analysis.
48006408758SMircea Trofin   void updateThreshold(CallBase &Call, Function &Callee);
48106408758SMircea Trofin   /// Return a higher threshold if \p Call is a hot callsite.
48206408758SMircea Trofin   Optional<int> getHotCallSiteThreshold(CallBase &Call,
48306408758SMircea Trofin                                         BlockFrequencyInfo *CallerBFI);
48406408758SMircea Trofin 
48506408758SMircea Trofin   /// Handle a capped 'int' increment for Cost.
48606408758SMircea Trofin   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
48706408758SMircea Trofin     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
48806408758SMircea Trofin     Cost = (int)std::min(UpperBound, Cost + Inc);
48906408758SMircea Trofin   }
49006408758SMircea Trofin 
49106408758SMircea Trofin   void onDisableSROA(AllocaInst *Arg) override {
49206408758SMircea Trofin     auto CostIt = SROAArgCosts.find(Arg);
49306408758SMircea Trofin     if (CostIt == SROAArgCosts.end())
49406408758SMircea Trofin       return;
49506408758SMircea Trofin     addCost(CostIt->second);
49606408758SMircea Trofin     SROACostSavings -= CostIt->second;
49706408758SMircea Trofin     SROACostSavingsLost += CostIt->second;
49806408758SMircea Trofin     SROAArgCosts.erase(CostIt);
49906408758SMircea Trofin   }
50006408758SMircea Trofin 
50106408758SMircea Trofin   void onDisableLoadElimination() override {
50206408758SMircea Trofin     addCost(LoadEliminationCost);
50306408758SMircea Trofin     LoadEliminationCost = 0;
50406408758SMircea Trofin   }
50506408758SMircea Trofin   void onCallPenalty() override { addCost(InlineConstants::CallPenalty); }
50606408758SMircea Trofin   void onCallArgumentSetup(const CallBase &Call) override {
50706408758SMircea Trofin     // Pay the price of the argument setup. We account for the average 1
50806408758SMircea Trofin     // instruction per call argument setup here.
50906408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
51006408758SMircea Trofin   }
51106408758SMircea Trofin   void onLoadRelativeIntrinsic() override {
51206408758SMircea Trofin     // This is normally lowered to 4 LLVM instructions.
51306408758SMircea Trofin     addCost(3 * InlineConstants::InstrCost);
51406408758SMircea Trofin   }
51506408758SMircea Trofin   void onLoweredCall(Function *F, CallBase &Call,
51606408758SMircea Trofin                      bool IsIndirectCall) override {
51706408758SMircea Trofin     // We account for the average 1 instruction per call argument setup here.
51806408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
51906408758SMircea Trofin 
52006408758SMircea Trofin     // If we have a constant that we are calling as a function, we can peer
52106408758SMircea Trofin     // through it and see the function target. This happens not infrequently
52206408758SMircea Trofin     // during devirtualization and so we want to give it a hefty bonus for
52306408758SMircea Trofin     // inlining, but cap that bonus in the event that inlining wouldn't pan out.
52406408758SMircea Trofin     // Pretend to inline the function, with a custom threshold.
52506408758SMircea Trofin     if (IsIndirectCall && BoostIndirectCalls) {
52606408758SMircea Trofin       auto IndirectCallParams = Params;
52706408758SMircea Trofin       IndirectCallParams.DefaultThreshold =
52806408758SMircea Trofin           InlineConstants::IndirectCallThreshold;
52906408758SMircea Trofin       /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
53006408758SMircea Trofin       /// to instantiate the derived class.
53108e2386dSMircea Trofin       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
53208e2386dSMircea Trofin                                 GetAssumptionCache, GetBFI, PSI, ORE, false);
5335466597fSMircea Trofin       if (CA.analyze().isSuccess()) {
53406408758SMircea Trofin         // We were able to inline the indirect call! Subtract the cost from the
53506408758SMircea Trofin         // threshold to get the bonus we want to apply, but don't go below zero.
53606408758SMircea Trofin         Cost -= std::max(0, CA.getThreshold() - CA.getCost());
53706408758SMircea Trofin       }
53806408758SMircea Trofin     } else
53906408758SMircea Trofin       // Otherwise simply add the cost for merely making the call.
54006408758SMircea Trofin       addCost(InlineConstants::CallPenalty);
54106408758SMircea Trofin   }
54206408758SMircea Trofin 
54306408758SMircea Trofin   void onFinalizeSwitch(unsigned JumpTableSize,
54406408758SMircea Trofin                         unsigned NumCaseCluster) override {
54506408758SMircea Trofin     // If suitable for a jump table, consider the cost for the table size and
54606408758SMircea Trofin     // branch to destination.
54706408758SMircea Trofin     // Maximum valid cost increased in this function.
54806408758SMircea Trofin     if (JumpTableSize) {
54906408758SMircea Trofin       int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
55006408758SMircea Trofin                        4 * InlineConstants::InstrCost;
55106408758SMircea Trofin 
55206408758SMircea Trofin       addCost(JTCost, (int64_t)CostUpperBound);
55306408758SMircea Trofin       return;
55406408758SMircea Trofin     }
55506408758SMircea Trofin     // Considering forming a binary search, we should find the number of nodes
55606408758SMircea Trofin     // which is same as the number of comparisons when lowered. For a given
55706408758SMircea Trofin     // number of clusters, n, we can define a recursive function, f(n), to find
55806408758SMircea Trofin     // the number of nodes in the tree. The recursion is :
55906408758SMircea Trofin     // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
56006408758SMircea Trofin     // and f(n) = n, when n <= 3.
56106408758SMircea Trofin     // This will lead a binary tree where the leaf should be either f(2) or f(3)
56206408758SMircea Trofin     // when n > 3.  So, the number of comparisons from leaves should be n, while
56306408758SMircea Trofin     // the number of non-leaf should be :
56406408758SMircea Trofin     //   2^(log2(n) - 1) - 1
56506408758SMircea Trofin     //   = 2^log2(n) * 2^-1 - 1
56606408758SMircea Trofin     //   = n / 2 - 1.
56706408758SMircea Trofin     // Considering comparisons from leaf and non-leaf nodes, we can estimate the
56806408758SMircea Trofin     // number of comparisons in a simple closed form :
56906408758SMircea Trofin     //   n + n / 2 - 1 = n * 3 / 2 - 1
57006408758SMircea Trofin     if (NumCaseCluster <= 3) {
57106408758SMircea Trofin       // Suppose a comparison includes one compare and one conditional branch.
57206408758SMircea Trofin       addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
57306408758SMircea Trofin       return;
57406408758SMircea Trofin     }
57506408758SMircea Trofin 
57606408758SMircea Trofin     int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
57706408758SMircea Trofin     int64_t SwitchCost =
57806408758SMircea Trofin         ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
57906408758SMircea Trofin 
58006408758SMircea Trofin     addCost(SwitchCost, (int64_t)CostUpperBound);
58106408758SMircea Trofin   }
58214a16faeSMircea Trofin   void onMissedSimplification() override {
58306408758SMircea Trofin     addCost(InlineConstants::InstrCost);
58406408758SMircea Trofin   }
58506408758SMircea Trofin 
58606408758SMircea Trofin   void onInitializeSROAArg(AllocaInst *Arg) override {
58706408758SMircea Trofin     assert(Arg != nullptr &&
58806408758SMircea Trofin            "Should not initialize SROA costs for null value.");
58906408758SMircea Trofin     SROAArgCosts[Arg] = 0;
59006408758SMircea Trofin   }
59106408758SMircea Trofin 
59206408758SMircea Trofin   void onAggregateSROAUse(AllocaInst *SROAArg) override {
59306408758SMircea Trofin     auto CostIt = SROAArgCosts.find(SROAArg);
59406408758SMircea Trofin     assert(CostIt != SROAArgCosts.end() &&
59506408758SMircea Trofin            "expected this argument to have a cost");
59606408758SMircea Trofin     CostIt->second += InlineConstants::InstrCost;
59706408758SMircea Trofin     SROACostSavings += InlineConstants::InstrCost;
59806408758SMircea Trofin   }
59906408758SMircea Trofin 
60006408758SMircea Trofin   void onBlockAnalyzed(const BasicBlock *BB) override {
60106408758SMircea Trofin     auto *TI = BB->getTerminator();
60206408758SMircea Trofin     // If we had any successors at this point, than post-inlining is likely to
60306408758SMircea Trofin     // have them as well. Note that we assume any basic blocks which existed
60406408758SMircea Trofin     // due to branches or switches which folded above will also fold after
60506408758SMircea Trofin     // inlining.
60606408758SMircea Trofin     if (SingleBB && TI->getNumSuccessors() > 1) {
60706408758SMircea Trofin       // Take off the bonus we applied to the threshold.
60806408758SMircea Trofin       Threshold -= SingleBBBonus;
60906408758SMircea Trofin       SingleBB = false;
61006408758SMircea Trofin     }
61106408758SMircea Trofin   }
6125466597fSMircea Trofin 
613c965fd94SKirill Naumov   void onInstructionAnalysisStart(const Instruction *I) override {
614c965fd94SKirill Naumov     // This function is called to store the initial cost of inlining before
615c965fd94SKirill Naumov     // the given instruction was assessed.
6161022b5ebSKirill Naumov     if (!PrintInstructionComments)
617c965fd94SKirill Naumov       return;
6181022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostBefore = Cost;
6191022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdBefore = Threshold;
620c965fd94SKirill Naumov   }
621c965fd94SKirill Naumov 
622c965fd94SKirill Naumov   void onInstructionAnalysisFinish(const Instruction *I) override {
623c965fd94SKirill Naumov     // This function is called to find new values of cost and threshold after
624c965fd94SKirill Naumov     // the instruction has been assessed.
6251022b5ebSKirill Naumov     if (!PrintInstructionComments)
626c965fd94SKirill Naumov       return;
6271022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostAfter = Cost;
6281022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdAfter = Threshold;
629c965fd94SKirill Naumov   }
630c965fd94SKirill Naumov 
63106408758SMircea Trofin   InlineResult finalizeAnalysis() override {
63206408758SMircea Trofin     // Loops generally act a lot like calls in that they act like barriers to
63306408758SMircea Trofin     // movement, require a certain amount of setup, etc. So when optimising for
63406408758SMircea Trofin     // size, we penalise any call sites that perform loops. We do this after all
63506408758SMircea Trofin     // other costs here, so will likely only be dealing with relatively small
63606408758SMircea Trofin     // functions (and hence DT and LI will hopefully be cheap).
63706408758SMircea Trofin     auto *Caller = CandidateCall.getFunction();
63806408758SMircea Trofin     if (Caller->hasMinSize()) {
63906408758SMircea Trofin       DominatorTree DT(F);
64006408758SMircea Trofin       LoopInfo LI(DT);
64106408758SMircea Trofin       int NumLoops = 0;
64206408758SMircea Trofin       for (Loop *L : LI) {
64306408758SMircea Trofin         // Ignore loops that will not be executed
64406408758SMircea Trofin         if (DeadBlocks.count(L->getHeader()))
64506408758SMircea Trofin           continue;
64606408758SMircea Trofin         NumLoops++;
64706408758SMircea Trofin       }
64806408758SMircea Trofin       addCost(NumLoops * InlineConstants::CallPenalty);
64906408758SMircea Trofin     }
65006408758SMircea Trofin 
65106408758SMircea Trofin     // We applied the maximum possible vector bonus at the beginning. Now,
65206408758SMircea Trofin     // subtract the excess bonus, if any, from the Threshold before
65306408758SMircea Trofin     // comparing against Cost.
65406408758SMircea Trofin     if (NumVectorInstructions <= NumInstructions / 10)
65506408758SMircea Trofin       Threshold -= VectorBonus;
65606408758SMircea Trofin     else if (NumVectorInstructions <= NumInstructions / 2)
65706408758SMircea Trofin       Threshold -= VectorBonus / 2;
65806408758SMircea Trofin 
6598a4013edSMircea Trofin     if (IgnoreThreshold || Cost < std::max(1, Threshold))
6605466597fSMircea Trofin       return InlineResult::success();
6615466597fSMircea Trofin     return InlineResult::failure("Cost over threshold.");
66206408758SMircea Trofin   }
66306408758SMircea Trofin   bool shouldStop() override {
66406408758SMircea Trofin     // Bail out the moment we cross the threshold. This means we'll under-count
66506408758SMircea Trofin     // the cost, but only when undercounting doesn't matter.
6668a4013edSMircea Trofin     return !IgnoreThreshold && Cost >= Threshold && !ComputeFullInlineCost;
66706408758SMircea Trofin   }
66806408758SMircea Trofin 
66906408758SMircea Trofin   void onLoadEliminationOpportunity() override {
67006408758SMircea Trofin     LoadEliminationCost += InlineConstants::InstrCost;
67106408758SMircea Trofin   }
67206408758SMircea Trofin 
67306408758SMircea Trofin   InlineResult onAnalysisStart() override {
67406408758SMircea Trofin     // Perform some tweaks to the cost and threshold based on the direct
67506408758SMircea Trofin     // callsite information.
67606408758SMircea Trofin 
67706408758SMircea Trofin     // We want to more aggressively inline vector-dense kernels, so up the
67806408758SMircea Trofin     // threshold, and we'll lower it if the % of vector instructions gets too
67906408758SMircea Trofin     // low. Note that these bonuses are some what arbitrary and evolved over
68006408758SMircea Trofin     // time by accident as much as because they are principled bonuses.
68106408758SMircea Trofin     //
68206408758SMircea Trofin     // FIXME: It would be nice to remove all such bonuses. At least it would be
68306408758SMircea Trofin     // nice to base the bonus values on something more scientific.
68406408758SMircea Trofin     assert(NumInstructions == 0);
68506408758SMircea Trofin     assert(NumVectorInstructions == 0);
68606408758SMircea Trofin 
68706408758SMircea Trofin     // Update the threshold based on callsite properties
68806408758SMircea Trofin     updateThreshold(CandidateCall, F);
68906408758SMircea Trofin 
69006408758SMircea Trofin     // While Threshold depends on commandline options that can take negative
69106408758SMircea Trofin     // values, we want to enforce the invariant that the computed threshold and
69206408758SMircea Trofin     // bonuses are non-negative.
69306408758SMircea Trofin     assert(Threshold >= 0);
69406408758SMircea Trofin     assert(SingleBBBonus >= 0);
69506408758SMircea Trofin     assert(VectorBonus >= 0);
69606408758SMircea Trofin 
69706408758SMircea Trofin     // Speculatively apply all possible bonuses to Threshold. If cost exceeds
69806408758SMircea Trofin     // this Threshold any time, and cost cannot decrease, we can stop processing
69906408758SMircea Trofin     // the rest of the function body.
70006408758SMircea Trofin     Threshold += (SingleBBBonus + VectorBonus);
70106408758SMircea Trofin 
70206408758SMircea Trofin     // Give out bonuses for the callsite, as the instructions setting them up
70306408758SMircea Trofin     // will be gone after inlining.
70406408758SMircea Trofin     addCost(-getCallsiteCost(this->CandidateCall, DL));
70506408758SMircea Trofin 
70606408758SMircea Trofin     // If this function uses the coldcc calling convention, prefer not to inline
70706408758SMircea Trofin     // it.
70806408758SMircea Trofin     if (F.getCallingConv() == CallingConv::Cold)
70906408758SMircea Trofin       Cost += InlineConstants::ColdccPenalty;
71006408758SMircea Trofin 
71106408758SMircea Trofin     // Check if we're done. This can happen due to bonuses and penalties.
71206408758SMircea Trofin     if (Cost >= Threshold && !ComputeFullInlineCost)
7135466597fSMircea Trofin       return InlineResult::failure("high cost");
71406408758SMircea Trofin 
7155466597fSMircea Trofin     return InlineResult::success();
71606408758SMircea Trofin   }
71706408758SMircea Trofin 
71806408758SMircea Trofin public:
71906408758SMircea Trofin   InlineCostCallAnalyzer(
72008e2386dSMircea Trofin       Function &Callee, CallBase &Call, const InlineParams &Params,
72106408758SMircea Trofin       const TargetTransformInfo &TTI,
72208e2386dSMircea Trofin       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
72308e2386dSMircea Trofin       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
72408e2386dSMircea Trofin       ProfileSummaryInfo *PSI = nullptr,
72508e2386dSMircea Trofin       OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
7268a4013edSMircea Trofin       bool IgnoreThreshold = false)
72708e2386dSMircea Trofin       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI, ORE),
72806408758SMircea Trofin         ComputeFullInlineCost(OptComputeFullInlineCost ||
72906408758SMircea Trofin                               Params.ComputeFullInlineCost || ORE),
73006408758SMircea Trofin         Params(Params), Threshold(Params.DefaultThreshold),
7311022b5ebSKirill Naumov         BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
7321022b5ebSKirill Naumov         Writer(this) {}
733c965fd94SKirill Naumov 
7341022b5ebSKirill Naumov   /// Annotation Writer for instruction details
7351022b5ebSKirill Naumov   InlineCostAnnotationWriter Writer;
736c965fd94SKirill Naumov 
73706408758SMircea Trofin   void dump();
73806408758SMircea Trofin 
739ca899bf9SKirill Naumov   // Prints the same analysis as dump(), but its definition is not dependent
740ca899bf9SKirill Naumov   // on the build.
741ca899bf9SKirill Naumov   void print();
742ca899bf9SKirill Naumov 
7431022b5ebSKirill Naumov   Optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
7441022b5ebSKirill Naumov     if (InstructionCostDetailMap.find(I) != InstructionCostDetailMap.end())
7451022b5ebSKirill Naumov       return InstructionCostDetailMap[I];
7461022b5ebSKirill Naumov     return None;
7471022b5ebSKirill Naumov   }
7481022b5ebSKirill Naumov 
74906408758SMircea Trofin   virtual ~InlineCostCallAnalyzer() {}
75006408758SMircea Trofin   int getThreshold() { return Threshold; }
75106408758SMircea Trofin   int getCost() { return Cost; }
75206408758SMircea Trofin };
7537adc3a2bSChandler Carruth } // namespace
7547adc3a2bSChandler Carruth 
7555f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument.
7567adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
7577adc3a2bSChandler Carruth   return SROAArgValues.count(V);
7587adc3a2bSChandler Carruth }
7597adc3a2bSChandler Carruth 
76006408758SMircea Trofin void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
76106408758SMircea Trofin   onDisableSROA(SROAArg);
7622e42cc7aSMircea Trofin   EnabledSROAAllocas.erase(SROAArg);
763338a6016SMircea Trofin   disableLoadElimination();
764338a6016SMircea Trofin }
765c965fd94SKirill Naumov 
7661022b5ebSKirill Naumov void InlineCostAnnotationWriter::emitInstructionAnnot(const Instruction *I,
7670383253cSKirill Naumov                                                 formatted_raw_ostream &OS) {
768c965fd94SKirill Naumov   // The cost of inlining of the given instruction is printed always.
769c965fd94SKirill Naumov   // The threshold delta is printed only when it is non-zero. It happens
770c965fd94SKirill Naumov   // when we decided to give a bonus at a particular instruction.
7711022b5ebSKirill Naumov   Optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
7721022b5ebSKirill Naumov   if (!Record)
7731022b5ebSKirill Naumov     OS << "; No analysis for the instruction";
7741022b5ebSKirill Naumov   else {
7751022b5ebSKirill Naumov     OS << "; cost before = " << Record->CostBefore
7761022b5ebSKirill Naumov        << ", cost after = " << Record->CostAfter
7771022b5ebSKirill Naumov        << ", threshold before = " << Record->ThresholdBefore
7781022b5ebSKirill Naumov        << ", threshold after = " << Record->ThresholdAfter << ", ";
7791022b5ebSKirill Naumov     OS << "cost delta = " << Record->getCostDelta();
7801022b5ebSKirill Naumov     if (Record->hasThresholdChanged())
7811022b5ebSKirill Naumov       OS << ", threshold delta = " << Record->getThresholdDelta();
7820383253cSKirill Naumov   }
7837f094f7fSKirill Naumov   auto C = ICCA->getSimplifiedValue(const_cast<Instruction *>(I));
7847f094f7fSKirill Naumov   if (C) {
7857f094f7fSKirill Naumov     OS << ", simplified to ";
7867f094f7fSKirill Naumov     C.getValue()->print(OS, true);
7877f094f7fSKirill Naumov   }
788c965fd94SKirill Naumov   OS << "\n";
789c965fd94SKirill Naumov }
790c965fd94SKirill Naumov 
7915f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it.
7927adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
79306408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
79406408758SMircea Trofin     disableSROAForArg(SROAArg);
795338a6016SMircea Trofin   }
7967adc3a2bSChandler Carruth }
7977adc3a2bSChandler Carruth 
798a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() {
799a4461515SHaicheng Wu   if (EnableLoadElimination) {
80006408758SMircea Trofin     onDisableLoadElimination();
801a4461515SHaicheng Wu     EnableLoadElimination = false;
802a4461515SHaicheng Wu   }
803a4461515SHaicheng Wu }
804a4461515SHaicheng Wu 
8055f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible.
8067adc3a2bSChandler Carruth ///
8077adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
8087adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
8097adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
810945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
8117adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
8127adc3a2bSChandler Carruth 
8137adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
8147adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
8157adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
8167adc3a2bSChandler Carruth     if (!OpC)
8177adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
8187adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
8197adc3a2bSChandler Carruth     if (!OpC)
8207adc3a2bSChandler Carruth       return false;
821567556aaSChad Rosier     if (OpC->isZero())
822567556aaSChad Rosier       continue;
8237adc3a2bSChandler Carruth 
8247adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
825ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
8267adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
8277adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
8287adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
8297adc3a2bSChandler Carruth       continue;
8307adc3a2bSChandler Carruth     }
8317adc3a2bSChandler Carruth 
8327adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
8337adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
8347adc3a2bSChandler Carruth   }
8357adc3a2bSChandler Carruth   return true;
8367adc3a2bSChandler Carruth }
8377adc3a2bSChandler Carruth 
8385f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free.
839201b191bSHaicheng Wu ///
840201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
841201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
84261c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
84361c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
84491aff1d8SNick Desaulniers   for (const Use &Op : GEP.indices())
84591aff1d8SNick Desaulniers     if (Constant *SimpleOp = SimplifiedValues.lookup(Op))
84661c1bd5aSEvgeny Astigeevich       Operands.push_back(SimpleOp);
847201b191bSHaicheng Wu     else
84891aff1d8SNick Desaulniers       Operands.push_back(Op);
849e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
8500383253cSKirill Naumov          TTI.getUserCost(&GEP, Operands,
8510383253cSKirill Naumov                          TargetTransformInfo::TCK_SizeAndLatency);
852201b191bSHaicheng Wu }
853201b191bSHaicheng Wu 
8547adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
8557adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
8560f153424SSanjay Patel   // alloca and handle that case.
8577adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
8580f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
8590f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
860090c108dSAmara Emerson       // Sometimes a dynamic alloca could be converted into a static alloca
861090c108dSAmara Emerson       // after this constant prop, and become a huge static alloca on an
862090c108dSAmara Emerson       // unconditional CFG path. Avoid inlining if this is going to happen above
863090c108dSAmara Emerson       // a threshold.
864090c108dSAmara Emerson       // FIXME: If the threshold is removed or lowered too much, we could end up
865090c108dSAmara Emerson       // being too pessimistic and prevent inlining non-problematic code. This
866090c108dSAmara Emerson       // could result in unintended perf regressions. A better overall strategy
867090c108dSAmara Emerson       // is needed to track stack usage during inlining.
8687adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
86922eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
8702ccde3c9SCullen Rhodes           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty).getKnownMinSize(),
871b302561bSGraham Hunter           AllocatedSize);
872090c108dSAmara Emerson       if (AllocatedSize > InlineConstants::MaxSimplifiedDynamicAllocaToInline) {
873090c108dSAmara Emerson         HasDynamicAlloca = true;
874090c108dSAmara Emerson         return false;
875090c108dSAmara Emerson       }
8767adc3a2bSChandler Carruth       return Base::visitAlloca(I);
8777adc3a2bSChandler Carruth     }
8787adc3a2bSChandler Carruth   }
8797adc3a2bSChandler Carruth 
8807adc3a2bSChandler Carruth   // Accumulate the allocated size.
8817adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
8827adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
8835a956c85SMircea Trofin     AllocatedSize =
8842ccde3c9SCullen Rhodes         SaturatingAdd(DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
8857adc3a2bSChandler Carruth   }
8867adc3a2bSChandler Carruth 
8877adc3a2bSChandler Carruth   // We will happily inline static alloca instructions.
8887adc3a2bSChandler Carruth   if (I.isStaticAlloca())
8897adc3a2bSChandler Carruth     return Base::visitAlloca(I);
8907adc3a2bSChandler Carruth 
8917adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
8927adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
8937adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
8947adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
8957adc3a2bSChandler Carruth   HasDynamicAlloca = true;
8967adc3a2bSChandler Carruth   return false;
8977adc3a2bSChandler Carruth }
8987adc3a2bSChandler Carruth 
8997adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
9007adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
9017adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
9027adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
9037adc3a2bSChandler Carruth 
9047adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
90577f32994SBjorn Pettersson   // FIXME: Pointer sizes may differ between different address spaces, so do we
90677f32994SBjorn Pettersson   // need to use correct address space in the call to getPointerSizeInBits here?
90777f32994SBjorn Pettersson   // Or could we skip the getPointerSizeInBits call completely? As far as I can
90877f32994SBjorn Pettersson   // see the ZeroOffset is used as a dummy value, so we can probably use any
90977f32994SBjorn Pettersson   // bit width for the ZeroOffset?
91077f32994SBjorn Pettersson   APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0));
9113739e14aSHaicheng Wu   bool CheckSROA = I.getType()->isPointerTy();
9123739e14aSHaicheng Wu 
9133739e14aSHaicheng Wu   // Track the constant or pointer with constant offset we've seen so far.
9143739e14aSHaicheng Wu   Constant *FirstC = nullptr;
9153739e14aSHaicheng Wu   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
9163739e14aSHaicheng Wu   Value *FirstV = nullptr;
9173739e14aSHaicheng Wu 
9183739e14aSHaicheng Wu   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
9193739e14aSHaicheng Wu     BasicBlock *Pred = I.getIncomingBlock(i);
9203739e14aSHaicheng Wu     // If the incoming block is dead, skip the incoming block.
9213739e14aSHaicheng Wu     if (DeadBlocks.count(Pred))
9223739e14aSHaicheng Wu       continue;
9233739e14aSHaicheng Wu     // If the parent block of phi is not the known successor of the incoming
9243739e14aSHaicheng Wu     // block, skip the incoming block.
9253739e14aSHaicheng Wu     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
9263739e14aSHaicheng Wu     if (KnownSuccessor && KnownSuccessor != I.getParent())
9273739e14aSHaicheng Wu       continue;
9283739e14aSHaicheng Wu 
9293739e14aSHaicheng Wu     Value *V = I.getIncomingValue(i);
9303739e14aSHaicheng Wu     // If the incoming value is this phi itself, skip the incoming value.
9313739e14aSHaicheng Wu     if (&I == V)
9323739e14aSHaicheng Wu       continue;
9333739e14aSHaicheng Wu 
9343739e14aSHaicheng Wu     Constant *C = dyn_cast<Constant>(V);
9353739e14aSHaicheng Wu     if (!C)
9363739e14aSHaicheng Wu       C = SimplifiedValues.lookup(V);
9373739e14aSHaicheng Wu 
9383739e14aSHaicheng Wu     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
9393739e14aSHaicheng Wu     if (!C && CheckSROA)
9403739e14aSHaicheng Wu       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
9413739e14aSHaicheng Wu 
9423739e14aSHaicheng Wu     if (!C && !BaseAndOffset.first)
9433739e14aSHaicheng Wu       // The incoming value is neither a constant nor a pointer with constant
9443739e14aSHaicheng Wu       // offset, exit early.
9453739e14aSHaicheng Wu       return true;
9463739e14aSHaicheng Wu 
9473739e14aSHaicheng Wu     if (FirstC) {
9483739e14aSHaicheng Wu       if (FirstC == C)
9493739e14aSHaicheng Wu         // If we've seen a constant incoming value before and it is the same
9503739e14aSHaicheng Wu         // constant we see this time, continue checking the next incoming value.
9513739e14aSHaicheng Wu         continue;
9523739e14aSHaicheng Wu       // Otherwise early exit because we either see a different constant or saw
9533739e14aSHaicheng Wu       // a constant before but we have a pointer with constant offset this time.
9543739e14aSHaicheng Wu       return true;
9553739e14aSHaicheng Wu     }
9563739e14aSHaicheng Wu 
9573739e14aSHaicheng Wu     if (FirstV) {
9583739e14aSHaicheng Wu       // The same logic as above, but check pointer with constant offset here.
9593739e14aSHaicheng Wu       if (FirstBaseAndOffset == BaseAndOffset)
9603739e14aSHaicheng Wu         continue;
9613739e14aSHaicheng Wu       return true;
9623739e14aSHaicheng Wu     }
9633739e14aSHaicheng Wu 
9643739e14aSHaicheng Wu     if (C) {
9653739e14aSHaicheng Wu       // This is the 1st time we've seen a constant, record it.
9663739e14aSHaicheng Wu       FirstC = C;
9673739e14aSHaicheng Wu       continue;
9683739e14aSHaicheng Wu     }
9693739e14aSHaicheng Wu 
9703739e14aSHaicheng Wu     // The remaining case is that this is the 1st time we've seen a pointer with
9713739e14aSHaicheng Wu     // constant offset, record it.
9723739e14aSHaicheng Wu     FirstV = V;
9733739e14aSHaicheng Wu     FirstBaseAndOffset = BaseAndOffset;
9743739e14aSHaicheng Wu   }
9753739e14aSHaicheng Wu 
9763739e14aSHaicheng Wu   // Check if we can map phi to a constant.
9773739e14aSHaicheng Wu   if (FirstC) {
9783739e14aSHaicheng Wu     SimplifiedValues[&I] = FirstC;
9793739e14aSHaicheng Wu     return true;
9803739e14aSHaicheng Wu   }
9813739e14aSHaicheng Wu 
9823739e14aSHaicheng Wu   // Check if we can map phi to a pointer with constant offset.
9833739e14aSHaicheng Wu   if (FirstBaseAndOffset.first) {
9843739e14aSHaicheng Wu     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
9853739e14aSHaicheng Wu 
98606408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
9873739e14aSHaicheng Wu       SROAArgValues[&I] = SROAArg;
9883739e14aSHaicheng Wu   }
9893739e14aSHaicheng Wu 
9907adc3a2bSChandler Carruth   return true;
9917adc3a2bSChandler Carruth }
9927adc3a2bSChandler Carruth 
9935f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers.
994d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs.
995d3558b5dSEvgeny Astigeevich ///
996d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded.
997d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
998d3558b5dSEvgeny Astigeevich   // Check if we have a base + offset for the pointer.
999d3558b5dSEvgeny Astigeevich   std::pair<Value *, APInt> BaseAndOffset =
1000d3558b5dSEvgeny Astigeevich       ConstantOffsetPtrs.lookup(I.getPointerOperand());
1001d3558b5dSEvgeny Astigeevich   if (!BaseAndOffset.first)
1002d3558b5dSEvgeny Astigeevich     return false;
1003d3558b5dSEvgeny Astigeevich 
1004d3558b5dSEvgeny Astigeevich   // Check if the offset of this GEP is constant, and if so accumulate it
1005d3558b5dSEvgeny Astigeevich   // into Offset.
1006d3558b5dSEvgeny Astigeevich   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1007d3558b5dSEvgeny Astigeevich     return false;
1008d3558b5dSEvgeny Astigeevich 
1009d3558b5dSEvgeny Astigeevich   // Add the result as a new mapping to Base + Offset.
1010d3558b5dSEvgeny Astigeevich   ConstantOffsetPtrs[&I] = BaseAndOffset;
1011d3558b5dSEvgeny Astigeevich 
1012d3558b5dSEvgeny Astigeevich   return true;
1013d3558b5dSEvgeny Astigeevich }
1014d3558b5dSEvgeny Astigeevich 
10157adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
101606408758SMircea Trofin   auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
10177adc3a2bSChandler Carruth 
1018a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
1019a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
102091aff1d8SNick Desaulniers     for (const Use &Op : GEP.indices())
102191aff1d8SNick Desaulniers       if (!isa<Constant>(Op) && !SimplifiedValues.lookup(Op))
1022a8b9cdc9SEaswaran Raman         return false;
1023a8b9cdc9SEaswaran Raman     return true;
1024a8b9cdc9SEaswaran Raman   };
1025a8b9cdc9SEaswaran Raman 
1026d48c7859SKirill Naumov   if (!DisableGEPConstOperand)
1027d48c7859SKirill Naumov     if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1028d48c7859SKirill Naumov         SmallVector<Constant *, 2> Indices;
1029d48c7859SKirill Naumov         for (unsigned int Index = 1 ; Index < COps.size() ; ++Index)
1030d48c7859SKirill Naumov             Indices.push_back(COps[Index]);
1031d48c7859SKirill Naumov         return ConstantExpr::getGetElementPtr(I.getSourceElementType(), COps[0],
1032d48c7859SKirill Naumov                                               Indices, I.isInBounds());
1033d48c7859SKirill Naumov         }))
1034d48c7859SKirill Naumov       return true;
1035d48c7859SKirill Naumov 
1036d3558b5dSEvgeny Astigeevich   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
103706408758SMircea Trofin     if (SROAArg)
10387adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
10397adc3a2bSChandler Carruth 
10407adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
10417adc3a2bSChandler Carruth     return true;
10427adc3a2bSChandler Carruth   }
10437adc3a2bSChandler Carruth 
10447adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
104506408758SMircea Trofin   if (SROAArg)
104606408758SMircea Trofin     disableSROAForArg(SROAArg);
1047201b191bSHaicheng Wu   return isGEPFree(I);
10487adc3a2bSChandler Carruth }
10497adc3a2bSChandler Carruth 
1050617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
1051617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the
1052617f6364SEaswaran Raman /// instruction when all the operands are constants.
1053617f6364SEaswaran Raman template <typename Callable>
1054617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
1055617f6364SEaswaran Raman   SmallVector<Constant *, 2> COps;
1056617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
1057617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
10587adc3a2bSChandler Carruth     if (!COp)
1059617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
1060617f6364SEaswaran Raman     if (!COp)
1061617f6364SEaswaran Raman       return false;
1062617f6364SEaswaran Raman     COps.push_back(COp);
1063617f6364SEaswaran Raman   }
1064617f6364SEaswaran Raman   auto *C = Evaluate(COps);
1065617f6364SEaswaran Raman   if (!C)
1066617f6364SEaswaran Raman     return false;
10677adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
10687adc3a2bSChandler Carruth   return true;
10697adc3a2bSChandler Carruth }
10707adc3a2bSChandler Carruth 
1071617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1072617f6364SEaswaran Raman   // Propagate constants through bitcasts.
1073617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1074617f6364SEaswaran Raman         return ConstantExpr::getBitCast(COps[0], I.getType());
1075617f6364SEaswaran Raman       }))
1076617f6364SEaswaran Raman     return true;
1077617f6364SEaswaran Raman 
10787adc3a2bSChandler Carruth   // Track base/offsets through casts
1079567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
1080567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
10817adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
10827adc3a2bSChandler Carruth   if (BaseAndOffset.first)
10837adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
10847adc3a2bSChandler Carruth 
10857adc3a2bSChandler Carruth   // Also look for SROA candidates here.
108606408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
10877adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
10887adc3a2bSChandler Carruth 
10897adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
10907adc3a2bSChandler Carruth   return true;
10917adc3a2bSChandler Carruth }
10927adc3a2bSChandler Carruth 
10937adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
10947adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1095617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1096617f6364SEaswaran Raman         return ConstantExpr::getPtrToInt(COps[0], I.getType());
1097617f6364SEaswaran Raman       }))
10987adc3a2bSChandler Carruth     return true;
10997adc3a2bSChandler Carruth 
11007adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
11017adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
11027adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
110377f32994SBjorn Pettersson   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1104faf848acSMikael Holmen   if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1105567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
1106567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
11077adc3a2bSChandler Carruth     if (BaseAndOffset.first)
11087adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
11097adc3a2bSChandler Carruth   }
11107adc3a2bSChandler Carruth 
11117adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
11127adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
11137adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
11147adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
11157adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
11167adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
11177adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
111806408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
11197adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
11207adc3a2bSChandler Carruth 
1121e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
1122e9c9329aSSam Parker          TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
11237adc3a2bSChandler Carruth }
11247adc3a2bSChandler Carruth 
11257adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
11267adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1127617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1128617f6364SEaswaran Raman         return ConstantExpr::getIntToPtr(COps[0], I.getType());
1129617f6364SEaswaran Raman       }))
11307adc3a2bSChandler Carruth     return true;
11317adc3a2bSChandler Carruth 
11327adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
11337adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
11347adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
11357adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
113677f32994SBjorn Pettersson   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
11377adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
11387adc3a2bSChandler Carruth     if (BaseAndOffset.first)
11397adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
11407adc3a2bSChandler Carruth   }
11417adc3a2bSChandler Carruth 
11427adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
114306408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(Op))
11447adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
11457adc3a2bSChandler Carruth 
1146e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
1147e9c9329aSSam Parker          TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
11487adc3a2bSChandler Carruth }
11497adc3a2bSChandler Carruth 
11507adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
1151ab53c5e5SCraig Topper   // Propagate constants through casts.
1152617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1153617f6364SEaswaran Raman         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
1154617f6364SEaswaran Raman       }))
11557adc3a2bSChandler Carruth     return true;
11567adc3a2bSChandler Carruth 
115710563e16SEric Christopher   // Disable SROA in the face of arbitrary casts we don't explicitly list
115810563e16SEric Christopher   // elsewhere.
11597adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
11607adc3a2bSChandler Carruth 
116139ed9a60SEli Friedman   // If this is a floating-point cast, and the target says this operation
116239ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
116339ed9a60SEli Friedman   // as such.
116439ed9a60SEli Friedman   switch (I.getOpcode()) {
116539ed9a60SEli Friedman   case Instruction::FPTrunc:
116639ed9a60SEli Friedman   case Instruction::FPExt:
116739ed9a60SEli Friedman   case Instruction::UIToFP:
116839ed9a60SEli Friedman   case Instruction::SIToFP:
116939ed9a60SEli Friedman   case Instruction::FPToUI:
117039ed9a60SEli Friedman   case Instruction::FPToSI:
117139ed9a60SEli Friedman     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
117206408758SMircea Trofin       onCallPenalty();
11734dc0b1acSReid Kleckner     break;
117439ed9a60SEli Friedman   default:
117539ed9a60SEli Friedman     break;
117639ed9a60SEli Friedman   }
117739ed9a60SEli Friedman 
1178e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
1179e9c9329aSSam Parker          TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
11807adc3a2bSChandler Carruth }
11817adc3a2bSChandler Carruth 
11827adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
11837adc3a2bSChandler Carruth   Value *Operand = I.getOperand(0);
1184617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1185617f6364SEaswaran Raman         return ConstantFoldInstOperands(&I, COps[0], DL);
1186617f6364SEaswaran Raman       }))
11877adc3a2bSChandler Carruth     return true;
11887adc3a2bSChandler Carruth 
1189ab53c5e5SCraig Topper   // Disable any SROA on the argument to arbitrary unary instructions.
11907adc3a2bSChandler Carruth   disableSROA(Operand);
11917adc3a2bSChandler Carruth 
11927adc3a2bSChandler Carruth   return false;
11937adc3a2bSChandler Carruth }
11947adc3a2bSChandler Carruth 
11957adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1196652168a9SFedor Sergeev   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
11977adc3a2bSChandler Carruth }
11987adc3a2bSChandler Carruth 
11997adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
12007adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
12017adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
12027adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
12037adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
12047adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
12057adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
12067adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
12077adc3a2bSChandler Carruth       return true;
12087adc3a2bSChandler Carruth 
12097adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
12107adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
12117adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
12127adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
12137adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
12147adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
12157adc3a2bSChandler Carruth     // SROA firing.
12167adc3a2bSChandler Carruth     return true;
12177adc3a2bSChandler Carruth 
12187adc3a2bSChandler Carruth   return false;
12197adc3a2bSChandler Carruth }
12207adc3a2bSChandler Carruth 
1221652168a9SFedor Sergeev bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
12229a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
12239a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
12249a3fc17aSEaswaran Raman   // unless there is literally zero cost.
12259a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
12269a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
12279a3fc17aSEaswaran Raman   // beneficial :
12289a3fc17aSEaswaran Raman   // main() {
12299a3fc17aSEaswaran Raman   //   hot_call_1();
12309a3fc17aSEaswaran Raman   //   ...
12319a3fc17aSEaswaran Raman   //   hot_call_N()
12329a3fc17aSEaswaran Raman   //   exit(0);
12339a3fc17aSEaswaran Raman   // }
12349a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
12359a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
12369a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
1237652168a9SFedor Sergeev   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
12389a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
12399a3fc17aSEaswaran Raman       return false;
1240652168a9SFedor Sergeev   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
12419a3fc17aSEaswaran Raman     return false;
12429a3fc17aSEaswaran Raman 
12439a3fc17aSEaswaran Raman   return true;
12449a3fc17aSEaswaran Raman }
12459a3fc17aSEaswaran Raman 
124606408758SMircea Trofin bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1247652168a9SFedor Sergeev                                             BlockFrequencyInfo *CallerBFI) {
1248c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
1249c5fa6358SEaswaran Raman   // determined based on that.
1250bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary())
1251ec73ae11SMircea Trofin     return PSI->isColdCallSite(Call, CallerBFI);
1252bba762a1SChandler Carruth 
1253bba762a1SChandler Carruth   // Otherwise we need BFI to be available.
1254c5fa6358SEaswaran Raman   if (!CallerBFI)
1255c5fa6358SEaswaran Raman     return false;
1256c5fa6358SEaswaran Raman 
1257bba762a1SChandler Carruth   // Determine if the callsite is cold relative to caller's entry. We could
1258bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1259bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1260bba762a1SChandler Carruth   // profiles.
1261c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
1262652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1263c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1264c5fa6358SEaswaran Raman   auto CallerEntryFreq =
1265652168a9SFedor Sergeev       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1266c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
1267c5fa6358SEaswaran Raman }
1268c5fa6358SEaswaran Raman 
1269974d4eeaSEaswaran Raman Optional<int>
127006408758SMircea Trofin InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1271974d4eeaSEaswaran Raman                                                 BlockFrequencyInfo *CallerBFI) {
1272bba762a1SChandler Carruth 
1273974d4eeaSEaswaran Raman   // If global profile summary is available, then callsite's hotness is
1274974d4eeaSEaswaran Raman   // determined based on that.
1275ec73ae11SMircea Trofin   if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1276bba762a1SChandler Carruth     return Params.HotCallSiteThreshold;
1277974d4eeaSEaswaran Raman 
1278bba762a1SChandler Carruth   // Otherwise we need BFI to be available and to have a locally hot callsite
1279bba762a1SChandler Carruth   // threshold.
1280bba762a1SChandler Carruth   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1281974d4eeaSEaswaran Raman     return None;
1282974d4eeaSEaswaran Raman 
1283bba762a1SChandler Carruth   // Determine if the callsite is hot relative to caller's entry. We could
1284bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1285bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1286bba762a1SChandler Carruth   // profiles.
1287652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1288974d4eeaSEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
1289974d4eeaSEaswaran Raman   auto CallerEntryFreq = CallerBFI->getEntryFreq();
1290974d4eeaSEaswaran Raman   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
1291bba762a1SChandler Carruth     return Params.LocallyHotCallSiteThreshold;
1292bba762a1SChandler Carruth 
1293bba762a1SChandler Carruth   // Otherwise treat it normally.
1294974d4eeaSEaswaran Raman   return None;
1295974d4eeaSEaswaran Raman }
1296974d4eeaSEaswaran Raman 
129706408758SMircea Trofin void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
12989a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
1299652168a9SFedor Sergeev   if (!allowSizeGrowth(Call)) {
13009a3fc17aSEaswaran Raman     Threshold = 0;
13019a3fc17aSEaswaran Raman     return;
13029a3fc17aSEaswaran Raman   }
13039a3fc17aSEaswaran Raman 
1304652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
13051c57cc2bSEaswaran Raman 
13061c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
13071c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
13081c57cc2bSEaswaran Raman     return B ? std::min(A, B.getValue()) : A;
13091c57cc2bSEaswaran Raman   };
13101c57cc2bSEaswaran Raman 
13110d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
13120d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
13130d58fcacSEaswaran Raman     return B ? std::max(A, B.getValue()) : A;
13140d58fcacSEaswaran Raman   };
13150d58fcacSEaswaran Raman 
131651b809bfSEaswaran Raman   // Various bonus percentages. These are multiplied by Threshold to get the
131751b809bfSEaswaran Raman   // bonus values.
131851b809bfSEaswaran Raman   // SingleBBBonus: This bonus is applied if the callee has a single reachable
131951b809bfSEaswaran Raman   // basic block at the given callsite context. This is speculatively applied
132051b809bfSEaswaran Raman   // and withdrawn if more than one basic block is seen.
132151b809bfSEaswaran Raman   //
132251b809bfSEaswaran Raman   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
132351b809bfSEaswaran Raman   // of the last call to a static function as inlining such functions is
132451b809bfSEaswaran Raman   // guaranteed to reduce code size.
132551b809bfSEaswaran Raman   //
132651b809bfSEaswaran Raman   // These bonus percentages may be set to 0 based on properties of the caller
132751b809bfSEaswaran Raman   // and the callsite.
132851b809bfSEaswaran Raman   int SingleBBBonusPercent = 50;
1329d912a9baSDaniil Fukalov   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
133002647f73SJordan Rupprecht   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
133151b809bfSEaswaran Raman 
133251b809bfSEaswaran Raman   // Lambda to set all the above bonus and bonus percentages to 0.
133351b809bfSEaswaran Raman   auto DisallowAllBonuses = [&]() {
133451b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
133551b809bfSEaswaran Raman     VectorBonusPercent = 0;
133651b809bfSEaswaran Raman     LastCallToStaticBonus = 0;
133751b809bfSEaswaran Raman   };
133851b809bfSEaswaran Raman 
13391c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
13401c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
134185bd3978SEvandro Menezes   if (Caller->hasMinSize()) {
13421c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
134351b809bfSEaswaran Raman     // For minsize, we want to disable the single BB bonus and the vector
134451b809bfSEaswaran Raman     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
134551b809bfSEaswaran Raman     // a static function will, at the minimum, eliminate the parameter setup and
134651b809bfSEaswaran Raman     // call/return instructions.
134751b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
134851b809bfSEaswaran Raman     VectorBonusPercent = 0;
134985bd3978SEvandro Menezes   } else if (Caller->hasOptSize())
13501c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
1351f4bb2f0dSEaswaran Raman 
1352e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
1353e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
135485bd3978SEvandro Menezes   if (!Caller->hasMinSize()) {
1355e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
13560d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1357bba762a1SChandler Carruth 
13583cd1479cSEaswaran Raman     // FIXME: After switching to the new passmanager, simplify the logic below
1359bba762a1SChandler Carruth     // by checking only the callsite hotness/coldness as we will reliably
1360bba762a1SChandler Carruth     // have local profile information.
13613cd1479cSEaswaran Raman     //
1362bba762a1SChandler Carruth     // Callsite hotness and coldness can be determined if sample profile is
1363bba762a1SChandler Carruth     // used (which adds hotness metadata to calls) or if caller's
1364bba762a1SChandler Carruth     // BlockFrequencyInfo is available.
136508e2386dSMircea Trofin     BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
1366652168a9SFedor Sergeev     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
136785bd3978SEvandro Menezes     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
1368d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
1369974d4eeaSEaswaran Raman       // FIXME: This should update the threshold only if it exceeds the
1370974d4eeaSEaswaran Raman       // current threshold, but AutoFDO + ThinLTO currently relies on this
1371974d4eeaSEaswaran Raman       // behavior to prevent inlining of hot callsites during ThinLTO
1372974d4eeaSEaswaran Raman       // compile phase.
1373974d4eeaSEaswaran Raman       Threshold = HotCallSiteThreshold.getValue();
1374652168a9SFedor Sergeev     } else if (isColdCallSite(Call, CallerBFI)) {
1375d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
137651b809bfSEaswaran Raman       // Do not apply bonuses for a cold callsite including the
137751b809bfSEaswaran Raman       // LastCallToStatic bonus. While this bonus might result in code size
137851b809bfSEaswaran Raman       // reduction, it can cause the size of a non-cold caller to increase
137951b809bfSEaswaran Raman       // preventing it from being inlined.
138051b809bfSEaswaran Raman       DisallowAllBonuses();
13813cd1479cSEaswaran Raman       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
1382bba762a1SChandler Carruth     } else if (PSI) {
1383bba762a1SChandler Carruth       // Use callee's global profile information only if we have no way of
1384bba762a1SChandler Carruth       // determining this via callsite information.
13853cd1479cSEaswaran Raman       if (PSI->isFunctionEntryHot(&Callee)) {
1386d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Hot callee.\n");
1387e08b139dSEaswaran Raman         // If callsite hotness can not be determined, we may still know
1388e08b139dSEaswaran Raman         // that the callee is hot and treat it as a weaker hint for threshold
1389e08b139dSEaswaran Raman         // increase.
1390e08b139dSEaswaran Raman         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1391e08b139dSEaswaran Raman       } else if (PSI->isFunctionEntryCold(&Callee)) {
1392d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Cold callee.\n");
139351b809bfSEaswaran Raman         // Do not apply bonuses for a cold callee including the
139451b809bfSEaswaran Raman         // LastCallToStatic bonus. While this bonus might result in code size
139551b809bfSEaswaran Raman         // reduction, it can cause the size of a non-cold caller to increase
139651b809bfSEaswaran Raman         // preventing it from being inlined.
139751b809bfSEaswaran Raman         DisallowAllBonuses();
13981c57cc2bSEaswaran Raman         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
1399e08b139dSEaswaran Raman       }
1400e08b139dSEaswaran Raman     }
1401e08b139dSEaswaran Raman   }
14028650a4daSJustin Lebar 
140302647f73SJordan Rupprecht   // Finally, take the target-specific inlining threshold multiplier into
140402647f73SJordan Rupprecht   // account.
14058650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
140651b809bfSEaswaran Raman 
140751b809bfSEaswaran Raman   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
140851b809bfSEaswaran Raman   VectorBonus = Threshold * VectorBonusPercent / 100;
140951b809bfSEaswaran Raman 
141002647f73SJordan Rupprecht   bool OnlyOneCallAndLocalLinkage =
141102647f73SJordan Rupprecht       F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction();
141202647f73SJordan Rupprecht   // If there is only one call of the function, and it has internal linkage,
141302647f73SJordan Rupprecht   // the cost of inlining it drops dramatically. It may seem odd to update
141402647f73SJordan Rupprecht   // Cost in updateThreshold, but the bonus depends on the logic in this method.
141502647f73SJordan Rupprecht   if (OnlyOneCallAndLocalLinkage)
141602647f73SJordan Rupprecht     Cost -= LastCallToStaticBonus;
1417f4bb2f0dSEaswaran Raman }
1418f4bb2f0dSEaswaran Raman 
14197adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
14207adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
14217adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
1422617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1423617f6364SEaswaran Raman         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
1424617f6364SEaswaran Raman       }))
14257adc3a2bSChandler Carruth     return true;
14267adc3a2bSChandler Carruth 
14277adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
14287adc3a2bSChandler Carruth     return false;
14297adc3a2bSChandler Carruth 
14307adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
14317adc3a2bSChandler Carruth   // a common base.
14327adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
14337adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
14347adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
14357adc3a2bSChandler Carruth   if (LHSBase) {
14367adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
14377adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
14387adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
14397adc3a2bSChandler Carruth       // offsets.
14407adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
14417adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
14427adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
14437adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
14447adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
14457adc3a2bSChandler Carruth         return true;
14467adc3a2bSChandler Carruth       }
14477adc3a2bSChandler Carruth     }
14487adc3a2bSChandler Carruth   }
14497adc3a2bSChandler Carruth 
14507adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
14517adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
14527adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
14537adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
14547adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
14557adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
14567adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
14577adc3a2bSChandler Carruth     return true;
14587adc3a2bSChandler Carruth   }
145906408758SMircea Trofin   return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
14607adc3a2bSChandler Carruth }
14617adc3a2bSChandler Carruth 
14627adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
14637adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
14647adc3a2bSChandler Carruth   // constant-related pointers.
14657adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
14667adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
14677adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
14687adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
14697adc3a2bSChandler Carruth   if (LHSBase) {
14707adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
14717adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
14727adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
14737adc3a2bSChandler Carruth       // offsets.
14747adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
14757adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
14767adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
14777adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
14787adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
14797adc3a2bSChandler Carruth         return true;
14807adc3a2bSChandler Carruth       }
14817adc3a2bSChandler Carruth     }
14827adc3a2bSChandler Carruth   }
14837adc3a2bSChandler Carruth 
14847adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
14857adc3a2bSChandler Carruth   // instructions.
14867adc3a2bSChandler Carruth   return Base::visitSub(I);
14877adc3a2bSChandler Carruth }
14887adc3a2bSChandler Carruth 
14897adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
14907adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
14916d14dfe8SHaicheng Wu   Constant *CLHS = dyn_cast<Constant>(LHS);
14926d14dfe8SHaicheng Wu   if (!CLHS)
14936d14dfe8SHaicheng Wu     CLHS = SimplifiedValues.lookup(LHS);
14946d14dfe8SHaicheng Wu   Constant *CRHS = dyn_cast<Constant>(RHS);
14956d14dfe8SHaicheng Wu   if (!CRHS)
14966d14dfe8SHaicheng Wu     CRHS = SimplifiedValues.lookup(RHS);
14976d14dfe8SHaicheng Wu 
14987adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
14997adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
15005a956c85SMircea Trofin     SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
15015a956c85SMircea Trofin                             FI->getFastMathFlags(), DL);
15027adc3a2bSChandler Carruth   else
15036d14dfe8SHaicheng Wu     SimpleV =
15046d14dfe8SHaicheng Wu         SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
15057adc3a2bSChandler Carruth 
15066d14dfe8SHaicheng Wu   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
15076d14dfe8SHaicheng Wu     SimplifiedValues[&I] = C;
15086d14dfe8SHaicheng Wu 
15096d14dfe8SHaicheng Wu   if (SimpleV)
15107adc3a2bSChandler Carruth     return true;
15117adc3a2bSChandler Carruth 
15127adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
15137adc3a2bSChandler Carruth   disableSROA(LHS);
15147adc3a2bSChandler Carruth   disableSROA(RHS);
15157adc3a2bSChandler Carruth 
151639ed9a60SEli Friedman   // If the instruction is floating point, and the target says this operation
151739ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
15187cebf0afSCraig Topper   // as such. Unless it's fneg which can be implemented with an xor.
15197cebf0afSCraig Topper   using namespace llvm::PatternMatch;
152039ed9a60SEli Friedman   if (I.getType()->isFloatingPointTy() &&
15217cebf0afSCraig Topper       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
15227cebf0afSCraig Topper       !match(&I, m_FNeg(m_Value())))
152306408758SMircea Trofin     onCallPenalty();
152439ed9a60SEli Friedman 
15257adc3a2bSChandler Carruth   return false;
15267adc3a2bSChandler Carruth }
15277adc3a2bSChandler Carruth 
15286cda33baSCraig Topper bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
15296cda33baSCraig Topper   Value *Op = I.getOperand(0);
15306cda33baSCraig Topper   Constant *COp = dyn_cast<Constant>(Op);
15316cda33baSCraig Topper   if (!COp)
15326cda33baSCraig Topper     COp = SimplifiedValues.lookup(Op);
15336cda33baSCraig Topper 
15345a956c85SMircea Trofin   Value *SimpleV = SimplifyFNegInst(
15355a956c85SMircea Trofin       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
15366cda33baSCraig Topper 
15376cda33baSCraig Topper   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
15386cda33baSCraig Topper     SimplifiedValues[&I] = C;
15396cda33baSCraig Topper 
15406cda33baSCraig Topper   if (SimpleV)
15416cda33baSCraig Topper     return true;
15426cda33baSCraig Topper 
15436cda33baSCraig Topper   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
15446cda33baSCraig Topper   disableSROA(Op);
15456cda33baSCraig Topper 
15466cda33baSCraig Topper   return false;
15476cda33baSCraig Topper }
15486cda33baSCraig Topper 
15497adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
155006408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
15517adc3a2bSChandler Carruth     return true;
15527adc3a2bSChandler Carruth 
1553a4461515SHaicheng Wu   // If the data is already loaded from this address and hasn't been clobbered
1554a4461515SHaicheng Wu   // by any stores or calls, this load is likely to be redundant and can be
1555a4461515SHaicheng Wu   // eliminated.
1556a4461515SHaicheng Wu   if (EnableLoadElimination &&
1557b3689cabSHaicheng Wu       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
155806408758SMircea Trofin     onLoadEliminationOpportunity();
1559a4461515SHaicheng Wu     return true;
1560a4461515SHaicheng Wu   }
1561a4461515SHaicheng Wu 
15627adc3a2bSChandler Carruth   return false;
15637adc3a2bSChandler Carruth }
15647adc3a2bSChandler Carruth 
15657adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
156606408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
15677adc3a2bSChandler Carruth     return true;
15687adc3a2bSChandler Carruth 
1569a4461515SHaicheng Wu   // The store can potentially clobber loads and prevent repeated loads from
1570a4461515SHaicheng Wu   // being eliminated.
1571a4461515SHaicheng Wu   // FIXME:
1572a4461515SHaicheng Wu   // 1. We can probably keep an initial set of eliminatable loads substracted
1573a4461515SHaicheng Wu   // from the cost even when we finally see a store. We just need to disable
1574a4461515SHaicheng Wu   // *further* accumulation of elimination savings.
1575a4461515SHaicheng Wu   // 2. We should probably at some point thread MemorySSA for the callee into
1576a4461515SHaicheng Wu   // this and then use that to actually compute *really* precise savings.
1577a4461515SHaicheng Wu   disableLoadElimination();
15787adc3a2bSChandler Carruth   return false;
15797adc3a2bSChandler Carruth }
15807adc3a2bSChandler Carruth 
15817adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
15827adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
1583617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1584617f6364SEaswaran Raman         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
1585617f6364SEaswaran Raman       }))
15867adc3a2bSChandler Carruth     return true;
15877adc3a2bSChandler Carruth 
15887adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
15897adc3a2bSChandler Carruth   return false;
15907adc3a2bSChandler Carruth }
15917adc3a2bSChandler Carruth 
15927adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
15937adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
1594617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1595617f6364SEaswaran Raman         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
1596617f6364SEaswaran Raman                                             /*InsertedValueOperand*/ COps[1],
1597617f6364SEaswaran Raman                                             I.getIndices());
1598617f6364SEaswaran Raman       }))
15997adc3a2bSChandler Carruth     return true;
16007adc3a2bSChandler Carruth 
16017adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
16027adc3a2bSChandler Carruth   return false;
16037adc3a2bSChandler Carruth }
16047adc3a2bSChandler Carruth 
16055f8f34e4SAdrian Prantl /// Try to simplify a call site.
16067adc3a2bSChandler Carruth ///
16077adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
16087adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
16097adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
16107adc3a2bSChandler Carruth /// free.
1611652168a9SFedor Sergeev bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
16127adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
16137adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
16147adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
16157adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
1616652168a9SFedor Sergeev   if (!canConstantFoldCallTo(&Call, F))
16177adc3a2bSChandler Carruth     return false;
16187adc3a2bSChandler Carruth 
16197adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
16207adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
1621652168a9SFedor Sergeev   ConstantArgs.reserve(Call.arg_size());
1622652168a9SFedor Sergeev   for (Value *I : Call.args()) {
1623652168a9SFedor Sergeev     Constant *C = dyn_cast<Constant>(I);
16247adc3a2bSChandler Carruth     if (!C)
1625652168a9SFedor Sergeev       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
16267adc3a2bSChandler Carruth     if (!C)
16277adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
16287adc3a2bSChandler Carruth 
16297adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
16307adc3a2bSChandler Carruth   }
1631652168a9SFedor Sergeev   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
1632652168a9SFedor Sergeev     SimplifiedValues[&Call] = C;
16337adc3a2bSChandler Carruth     return true;
16347adc3a2bSChandler Carruth   }
16357adc3a2bSChandler Carruth 
16367adc3a2bSChandler Carruth   return false;
16377adc3a2bSChandler Carruth }
16387adc3a2bSChandler Carruth 
1639652168a9SFedor Sergeev bool CallAnalyzer::visitCallBase(CallBase &Call) {
1640652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
16417adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
16427adc3a2bSChandler Carruth     // This aborts the entire analysis.
16437adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
16447adc3a2bSChandler Carruth     return false;
16457adc3a2bSChandler Carruth   }
1646652168a9SFedor Sergeev   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
16477adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
16487adc3a2bSChandler Carruth 
1649825debe8SEhud Katz   Value *Callee = Call.getCalledOperand();
1650825debe8SEhud Katz   Function *F = dyn_cast_or_null<Function>(Callee);
1651825debe8SEhud Katz   bool IsIndirectCall = !F;
1652825debe8SEhud Katz   if (IsIndirectCall) {
1653825debe8SEhud Katz     // Check if this happens to be an indirect function call to a known function
1654825debe8SEhud Katz     // in this inline context. If not, we've done all we can.
1655825debe8SEhud Katz     F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
1656825debe8SEhud Katz     if (!F) {
165706408758SMircea Trofin       onCallArgumentSetup(Call);
1658825debe8SEhud Katz 
1659825debe8SEhud Katz       if (!Call.onlyReadsMemory())
1660825debe8SEhud Katz         disableLoadElimination();
1661825debe8SEhud Katz       return Base::visitCallBase(Call);
1662825debe8SEhud Katz     }
1663825debe8SEhud Katz   }
1664825debe8SEhud Katz 
1665825debe8SEhud Katz   assert(F && "Expected a call to a known function");
1666825debe8SEhud Katz 
16677adc3a2bSChandler Carruth   // When we have a concrete function, first try to simplify it directly.
1668652168a9SFedor Sergeev   if (simplifyCallSite(F, Call))
16697adc3a2bSChandler Carruth     return true;
16707adc3a2bSChandler Carruth 
16717adc3a2bSChandler Carruth   // Next check if it is an intrinsic we know about.
16727adc3a2bSChandler Carruth   // FIXME: Lift this into part of the InstVisitor.
1673652168a9SFedor Sergeev   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
16747adc3a2bSChandler Carruth     switch (II->getIntrinsicID()) {
16757adc3a2bSChandler Carruth     default:
1676652168a9SFedor Sergeev       if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
1677a4461515SHaicheng Wu         disableLoadElimination();
1678652168a9SFedor Sergeev       return Base::visitCallBase(Call);
16797adc3a2bSChandler Carruth 
16807dd8dbf4SPeter Collingbourne     case Intrinsic::load_relative:
168106408758SMircea Trofin       onLoadRelativeIntrinsic();
16827dd8dbf4SPeter Collingbourne       return false;
16837dd8dbf4SPeter Collingbourne 
16847adc3a2bSChandler Carruth     case Intrinsic::memset:
16857adc3a2bSChandler Carruth     case Intrinsic::memcpy:
16867adc3a2bSChandler Carruth     case Intrinsic::memmove:
1687a4461515SHaicheng Wu       disableLoadElimination();
16887adc3a2bSChandler Carruth       // SROA can usually chew through these intrinsics, but they aren't free.
16897adc3a2bSChandler Carruth       return false;
16904296ea72SVitaly Buka     case Intrinsic::icall_branch_funnel:
16917adc3a2bSChandler Carruth     case Intrinsic::localescape:
16924296ea72SVitaly Buka       HasUninlineableIntrinsic = true;
16937adc3a2bSChandler Carruth       return false;
169480788d80SFlorian Hahn     case Intrinsic::vastart:
169577beee41SSameer AbuAsal       InitsVargArgs = true;
169680788d80SFlorian Hahn       return false;
16977adc3a2bSChandler Carruth     }
16987adc3a2bSChandler Carruth   }
16997adc3a2bSChandler Carruth 
1700652168a9SFedor Sergeev   if (F == Call.getFunction()) {
17017adc3a2bSChandler Carruth     // This flag will fully abort the analysis, so don't bother with anything
17027adc3a2bSChandler Carruth     // else.
17037adc3a2bSChandler Carruth     IsRecursiveCall = true;
17047adc3a2bSChandler Carruth     return false;
17057adc3a2bSChandler Carruth   }
17067adc3a2bSChandler Carruth 
17077adc3a2bSChandler Carruth   if (TTI.isLoweredToCall(F)) {
170806408758SMircea Trofin     onLoweredCall(F, Call, IsIndirectCall);
1709825debe8SEhud Katz   }
17107adc3a2bSChandler Carruth 
1711825debe8SEhud Katz   if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
1712a4461515SHaicheng Wu     disableLoadElimination();
1713652168a9SFedor Sergeev   return Base::visitCallBase(Call);
17147adc3a2bSChandler Carruth }
17157adc3a2bSChandler Carruth 
17167adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
17177adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
17187adc3a2bSChandler Carruth   bool Free = !HasReturn;
17197adc3a2bSChandler Carruth   HasReturn = true;
17207adc3a2bSChandler Carruth   return Free;
17217adc3a2bSChandler Carruth }
17227adc3a2bSChandler Carruth 
17237adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
17247adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
17257adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
17267adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
17277adc3a2bSChandler Carruth   // which will fold away are also free.
17287adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
17297adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
17307adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
17317adc3a2bSChandler Carruth }
17327adc3a2bSChandler Carruth 
17333ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
17343ec848bcSHaicheng Wu   bool CheckSROA = SI.getType()->isPointerTy();
17353ec848bcSHaicheng Wu   Value *TrueVal = SI.getTrueValue();
17363ec848bcSHaicheng Wu   Value *FalseVal = SI.getFalseValue();
17373ec848bcSHaicheng Wu 
17383ec848bcSHaicheng Wu   Constant *TrueC = dyn_cast<Constant>(TrueVal);
17393ec848bcSHaicheng Wu   if (!TrueC)
17403ec848bcSHaicheng Wu     TrueC = SimplifiedValues.lookup(TrueVal);
17413ec848bcSHaicheng Wu   Constant *FalseC = dyn_cast<Constant>(FalseVal);
17423ec848bcSHaicheng Wu   if (!FalseC)
17433ec848bcSHaicheng Wu     FalseC = SimplifiedValues.lookup(FalseVal);
17443ec848bcSHaicheng Wu   Constant *CondC =
17453ec848bcSHaicheng Wu       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
17463ec848bcSHaicheng Wu 
17473ec848bcSHaicheng Wu   if (!CondC) {
17483ec848bcSHaicheng Wu     // Select C, X, X => X
17493ec848bcSHaicheng Wu     if (TrueC == FalseC && TrueC) {
17503ec848bcSHaicheng Wu       SimplifiedValues[&SI] = TrueC;
17513ec848bcSHaicheng Wu       return true;
17523ec848bcSHaicheng Wu     }
17533ec848bcSHaicheng Wu 
17543ec848bcSHaicheng Wu     if (!CheckSROA)
17553ec848bcSHaicheng Wu       return Base::visitSelectInst(SI);
17563ec848bcSHaicheng Wu 
17573ec848bcSHaicheng Wu     std::pair<Value *, APInt> TrueBaseAndOffset =
17583ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(TrueVal);
17593ec848bcSHaicheng Wu     std::pair<Value *, APInt> FalseBaseAndOffset =
17603ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(FalseVal);
17613ec848bcSHaicheng Wu     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
17623ec848bcSHaicheng Wu       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
17633ec848bcSHaicheng Wu 
176406408758SMircea Trofin       if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
17653ec848bcSHaicheng Wu         SROAArgValues[&SI] = SROAArg;
17663ec848bcSHaicheng Wu       return true;
17673ec848bcSHaicheng Wu     }
17683ec848bcSHaicheng Wu 
17693ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
17703ec848bcSHaicheng Wu   }
17713ec848bcSHaicheng Wu 
17723ec848bcSHaicheng Wu   // Select condition is a constant.
17733ec848bcSHaicheng Wu   Value *SelectedV = CondC->isAllOnesValue()
17743ec848bcSHaicheng Wu                          ? TrueVal
17753ec848bcSHaicheng Wu                          : (CondC->isNullValue()) ? FalseVal : nullptr;
17763ec848bcSHaicheng Wu   if (!SelectedV) {
17773ec848bcSHaicheng Wu     // Condition is a vector constant that is not all 1s or all 0s.  If all
17783ec848bcSHaicheng Wu     // operands are constants, ConstantExpr::getSelect() can handle the cases
17793ec848bcSHaicheng Wu     // such as select vectors.
17803ec848bcSHaicheng Wu     if (TrueC && FalseC) {
17813ec848bcSHaicheng Wu       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
17823ec848bcSHaicheng Wu         SimplifiedValues[&SI] = C;
17833ec848bcSHaicheng Wu         return true;
17843ec848bcSHaicheng Wu       }
17853ec848bcSHaicheng Wu     }
17863ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
17873ec848bcSHaicheng Wu   }
17883ec848bcSHaicheng Wu 
17893ec848bcSHaicheng Wu   // Condition is either all 1s or all 0s. SI can be simplified.
17903ec848bcSHaicheng Wu   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
17913ec848bcSHaicheng Wu     SimplifiedValues[&SI] = SelectedC;
17923ec848bcSHaicheng Wu     return true;
17933ec848bcSHaicheng Wu   }
17943ec848bcSHaicheng Wu 
17953ec848bcSHaicheng Wu   if (!CheckSROA)
17963ec848bcSHaicheng Wu     return true;
17973ec848bcSHaicheng Wu 
17983ec848bcSHaicheng Wu   std::pair<Value *, APInt> BaseAndOffset =
17993ec848bcSHaicheng Wu       ConstantOffsetPtrs.lookup(SelectedV);
18003ec848bcSHaicheng Wu   if (BaseAndOffset.first) {
18013ec848bcSHaicheng Wu     ConstantOffsetPtrs[&SI] = BaseAndOffset;
18023ec848bcSHaicheng Wu 
180306408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
18043ec848bcSHaicheng Wu       SROAArgValues[&SI] = SROAArg;
18053ec848bcSHaicheng Wu   }
18063ec848bcSHaicheng Wu 
18073ec848bcSHaicheng Wu   return true;
18083ec848bcSHaicheng Wu }
18093ec848bcSHaicheng Wu 
18107adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
18117adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
18127adc3a2bSChandler Carruth   // branches.
18137adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
18147adc3a2bSChandler Carruth     return true;
18157adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
18167adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
18177adc3a2bSChandler Carruth       return true;
18187adc3a2bSChandler Carruth 
18197ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
1820919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
1821919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
1822919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
1823919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
1824919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
18252960d41eSJun Bum Lim   //
18262960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
18272960d41eSJun Bum Lim   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
18282960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
18292960d41eSJun Bum Lim   // does not (yet) fire.
1830919f9e8dSJun Bum Lim 
1831919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
183208e2386dSMircea Trofin   BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
1833919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
18340d987e41SHiroshi Yamauchi       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
1835919f9e8dSJun Bum Lim 
183606408758SMircea Trofin   onFinalizeSwitch(JumpTableSize, NumCaseCluster);
1837919f9e8dSJun Bum Lim   return false;
1838919f9e8dSJun Bum Lim }
1839919f9e8dSJun Bum Lim 
18407adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
18417adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
18427adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
18437adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
18447adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
18457adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
18467adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
18477adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
18487adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
18497adc3a2bSChandler Carruth   HasIndirectBr = true;
18507adc3a2bSChandler Carruth   return false;
18517adc3a2bSChandler Carruth }
18527adc3a2bSChandler Carruth 
18537adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
18547adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
18557adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
18567adc3a2bSChandler Carruth   return false;
18577adc3a2bSChandler Carruth }
18587adc3a2bSChandler Carruth 
18597adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
18607adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
18617adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
18627adc3a2bSChandler Carruth   return false;
18637adc3a2bSChandler Carruth }
18647adc3a2bSChandler Carruth 
18657adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
18667adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
18678220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
18687adc3a2bSChandler Carruth   return false;
18697adc3a2bSChandler Carruth }
18707adc3a2bSChandler Carruth 
18717adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
18727adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
18737adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
18747adc3a2bSChandler Carruth   // code size.
18757adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
18767adc3a2bSChandler Carruth }
18777adc3a2bSChandler Carruth 
18787adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
18797adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
18807adc3a2bSChandler Carruth   // handled by SROA, etc.
1881e9c9329aSSam Parker   if (TargetTransformInfo::TCC_Free ==
1882e9c9329aSSam Parker       TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency))
18837adc3a2bSChandler Carruth     return true;
18847adc3a2bSChandler Carruth 
18857adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
18867adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
188791aff1d8SNick Desaulniers   for (const Use &Op : I.operands())
188891aff1d8SNick Desaulniers     disableSROA(Op);
18897adc3a2bSChandler Carruth 
18907adc3a2bSChandler Carruth   return false;
18917adc3a2bSChandler Carruth }
18927adc3a2bSChandler Carruth 
18935f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost.
18947adc3a2bSChandler Carruth ///
18957adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
18967adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
18977adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
18987adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
18997adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
1900c0aa4b75SDavid Bolvansky InlineResult
1901c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB,
19027adc3a2bSChandler Carruth                            SmallPtrSetImpl<const Value *> &EphValues) {
190391aff1d8SNick Desaulniers   for (Instruction &I : *BB) {
19047adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
19057adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
19067adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
19077adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
19087adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
19097adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
19107adc3a2bSChandler Carruth     // hack around it here.
19117adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
19127adc3a2bSChandler Carruth       continue;
19137adc3a2bSChandler Carruth 
1914f3c44569SHongtao Yu     // Skip pseudo-probes.
1915f3c44569SHongtao Yu     if (isa<PseudoProbeInst>(I))
1916f3c44569SHongtao Yu       continue;
1917f3c44569SHongtao Yu 
19187adc3a2bSChandler Carruth     // Skip ephemeral values.
191991aff1d8SNick Desaulniers     if (EphValues.count(&I))
19207adc3a2bSChandler Carruth       continue;
19217adc3a2bSChandler Carruth 
19227adc3a2bSChandler Carruth     ++NumInstructions;
192391aff1d8SNick Desaulniers     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
19247adc3a2bSChandler Carruth       ++NumVectorInstructions;
19257adc3a2bSChandler Carruth 
19267adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
19277adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
19287adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
19297adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
19307adc3a2bSChandler Carruth     // cost should count against inlining.
193191aff1d8SNick Desaulniers     onInstructionAnalysisStart(&I);
1932c965fd94SKirill Naumov 
193391aff1d8SNick Desaulniers     if (Base::visit(&I))
19347adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
19357adc3a2bSChandler Carruth     else
193614a16faeSMircea Trofin       onMissedSimplification();
19377adc3a2bSChandler Carruth 
193891aff1d8SNick Desaulniers     onInstructionAnalysisFinish(&I);
19390812c5beSHaicheng Wu     using namespace ore;
19407adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
19415466597fSMircea Trofin     InlineResult IR = InlineResult::success();
1942c0aa4b75SDavid Bolvansky     if (IsRecursiveCall)
19435466597fSMircea Trofin       IR = InlineResult::failure("recursive");
1944c0aa4b75SDavid Bolvansky     else if (ExposesReturnsTwice)
19455466597fSMircea Trofin       IR = InlineResult::failure("exposes returns twice");
1946c0aa4b75SDavid Bolvansky     else if (HasDynamicAlloca)
19475466597fSMircea Trofin       IR = InlineResult::failure("dynamic alloca");
1948c0aa4b75SDavid Bolvansky     else if (HasIndirectBr)
19495466597fSMircea Trofin       IR = InlineResult::failure("indirect branch");
1950c0aa4b75SDavid Bolvansky     else if (HasUninlineableIntrinsic)
19515466597fSMircea Trofin       IR = InlineResult::failure("uninlinable intrinsic");
195277beee41SSameer AbuAsal     else if (InitsVargArgs)
19535466597fSMircea Trofin       IR = InlineResult::failure("varargs");
19545466597fSMircea Trofin     if (!IR.isSuccess()) {
19550812c5beSHaicheng Wu       if (ORE)
19569590658fSVivek Pandya         ORE->emit([&]() {
19579590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
1958652168a9SFedor Sergeev                                           &CandidateCall)
1959c0aa4b75SDavid Bolvansky                  << NV("Callee", &F) << " has uninlinable pattern ("
19605466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
1961c0aa4b75SDavid Bolvansky                  << ") and cost is not fully computed";
19629590658fSVivek Pandya         });
1963c0aa4b75SDavid Bolvansky       return IR;
19640812c5beSHaicheng Wu     }
19657adc3a2bSChandler Carruth 
19667adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
19677adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
19687adc3a2bSChandler Carruth     // the caller stack usage dramatically.
19697adc3a2bSChandler Carruth     if (IsCallerRecursive &&
19700812c5beSHaicheng Wu         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
19715466597fSMircea Trofin       auto IR =
19725466597fSMircea Trofin           InlineResult::failure("recursive and allocates too much stack space");
19730812c5beSHaicheng Wu       if (ORE)
19749590658fSVivek Pandya         ORE->emit([&]() {
19759590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
1976652168a9SFedor Sergeev                                           &CandidateCall)
19775466597fSMircea Trofin                  << NV("Callee", &F) << " is "
19785466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
1979c0aa4b75SDavid Bolvansky                  << ". Cost is not fully computed";
19809590658fSVivek Pandya         });
1981c0aa4b75SDavid Bolvansky       return IR;
19820812c5beSHaicheng Wu     }
19837adc3a2bSChandler Carruth 
198406408758SMircea Trofin     if (shouldStop())
19855466597fSMircea Trofin       return InlineResult::failure(
19865466597fSMircea Trofin           "Call site analysis is not favorable to inlining.");
19877adc3a2bSChandler Carruth   }
19887adc3a2bSChandler Carruth 
19895466597fSMircea Trofin   return InlineResult::success();
19907adc3a2bSChandler Carruth }
19917adc3a2bSChandler Carruth 
19925f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V.
19937adc3a2bSChandler Carruth ///
19947adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
19957adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
19967adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
19977adc3a2bSChandler Carruth /// no constant offsets applied.
19987adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
19997adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
20007adc3a2bSChandler Carruth     return nullptr;
20017adc3a2bSChandler Carruth 
200277f32994SBjorn Pettersson   unsigned AS = V->getType()->getPointerAddressSpace();
2003945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
20047adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
20057adc3a2bSChandler Carruth 
20067adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
20077adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
20087adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
20097adc3a2bSChandler Carruth   Visited.insert(V);
20107adc3a2bSChandler Carruth   do {
20117adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
20127adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
20137adc3a2bSChandler Carruth         return nullptr;
20147adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
20157adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
20167adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
20177adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
20185ce32728SSanjoy Das       if (GA->isInterposable())
20197adc3a2bSChandler Carruth         break;
20207adc3a2bSChandler Carruth       V = GA->getAliasee();
20217adc3a2bSChandler Carruth     } else {
20227adc3a2bSChandler Carruth       break;
20237adc3a2bSChandler Carruth     }
20247adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
20257adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
20267adc3a2bSChandler Carruth 
202797572775SNicola Zaghen   Type *IdxPtrTy = DL.getIndexType(V->getType());
202897572775SNicola Zaghen   return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
20297adc3a2bSChandler Carruth }
20307adc3a2bSChandler Carruth 
20315f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining.
20323739e14aSHaicheng Wu ///
20333739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p
20343739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have
20353739e14aSHaicheng Wu /// no live incoming CFG edges.  If one block is found to be dead, we can
20363739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead
20373739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not.
20383739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
20393739e14aSHaicheng Wu   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
204002a2bb2fSHiroshi Inoue     // A CFG edge is dead if the predecessor is dead or the predecessor has a
20413739e14aSHaicheng Wu     // known successor which is not the one under exam.
20423739e14aSHaicheng Wu     return (DeadBlocks.count(Pred) ||
20433739e14aSHaicheng Wu             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
20443739e14aSHaicheng Wu   };
20453739e14aSHaicheng Wu 
20463739e14aSHaicheng Wu   auto IsNewlyDead = [&](BasicBlock *BB) {
20473739e14aSHaicheng Wu     // If all the edges to a block are dead, the block is also dead.
20483739e14aSHaicheng Wu     return (!DeadBlocks.count(BB) &&
20493739e14aSHaicheng Wu             llvm::all_of(predecessors(BB),
20503739e14aSHaicheng Wu                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
20513739e14aSHaicheng Wu   };
20523739e14aSHaicheng Wu 
20533739e14aSHaicheng Wu   for (BasicBlock *Succ : successors(CurrBB)) {
20543739e14aSHaicheng Wu     if (Succ == NextBB || !IsNewlyDead(Succ))
20553739e14aSHaicheng Wu       continue;
20563739e14aSHaicheng Wu     SmallVector<BasicBlock *, 4> NewDead;
20573739e14aSHaicheng Wu     NewDead.push_back(Succ);
20583739e14aSHaicheng Wu     while (!NewDead.empty()) {
20593739e14aSHaicheng Wu       BasicBlock *Dead = NewDead.pop_back_val();
20603739e14aSHaicheng Wu       if (DeadBlocks.insert(Dead))
20613739e14aSHaicheng Wu         // Continue growing the dead block lists.
20623739e14aSHaicheng Wu         for (BasicBlock *S : successors(Dead))
20633739e14aSHaicheng Wu           if (IsNewlyDead(S))
20643739e14aSHaicheng Wu             NewDead.push_back(S);
20653739e14aSHaicheng Wu     }
20663739e14aSHaicheng Wu   }
20673739e14aSHaicheng Wu }
20683739e14aSHaicheng Wu 
20695f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining.
20707adc3a2bSChandler Carruth ///
20717adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
20727adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
20737adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
20747adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
20757adc3a2bSChandler Carruth /// some artifact of the routine.
207693ac81ccSMircea Trofin InlineResult CallAnalyzer::analyze() {
20777adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
20787adc3a2bSChandler Carruth 
207906408758SMircea Trofin   auto Result = onAnalysisStart();
20805466597fSMircea Trofin   if (!Result.isSuccess())
208106408758SMircea Trofin     return Result;
20827adc3a2bSChandler Carruth 
20837adc3a2bSChandler Carruth   if (F.empty())
20845466597fSMircea Trofin     return InlineResult::success();
20857adc3a2bSChandler Carruth 
208693ac81ccSMircea Trofin   Function *Caller = CandidateCall.getFunction();
20877adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
20887adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
2089652168a9SFedor Sergeev     CallBase *Call = dyn_cast<CallBase>(U);
2090652168a9SFedor Sergeev     if (Call && Call->getFunction() == Caller) {
20917adc3a2bSChandler Carruth       IsCallerRecursive = true;
20927adc3a2bSChandler Carruth       break;
20937adc3a2bSChandler Carruth     }
20947adc3a2bSChandler Carruth   }
20957adc3a2bSChandler Carruth 
20967adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
20977adc3a2bSChandler Carruth   // arguments with known important simplifications.
209893ac81ccSMircea Trofin   auto CAI = CandidateCall.arg_begin();
209991aff1d8SNick Desaulniers   for (Argument &FAI : F.args()) {
210093ac81ccSMircea Trofin     assert(CAI != CandidateCall.arg_end());
21017adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
210291aff1d8SNick Desaulniers       SimplifiedValues[&FAI] = C;
21037adc3a2bSChandler Carruth 
21047adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
21057adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
210691aff1d8SNick Desaulniers       ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
21077adc3a2bSChandler Carruth 
21087adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
210906408758SMircea Trofin       if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
211091aff1d8SNick Desaulniers         SROAArgValues[&FAI] = SROAArg;
211106408758SMircea Trofin         onInitializeSROAArg(SROAArg);
21122e42cc7aSMircea Trofin         EnabledSROAAllocas.insert(SROAArg);
21137adc3a2bSChandler Carruth       }
21147adc3a2bSChandler Carruth     }
211591aff1d8SNick Desaulniers     ++CAI;
21167adc3a2bSChandler Carruth   }
21177adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
21187adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
21197adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
21207adc3a2bSChandler Carruth 
21217adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
21227adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
21237adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
21247adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
2125aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
21267adc3a2bSChandler Carruth 
21277adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
21287adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
21297adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
21307adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
21317adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
21327adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
21337adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
21347adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
2135567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
2136567556aaSChad Rosier       BBSetVector;
21377adc3a2bSChandler Carruth   BBSetVector BBWorklist;
21387adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
213906408758SMircea Trofin 
21407adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
21417adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
214206408758SMircea Trofin     if (shouldStop())
21437adc3a2bSChandler Carruth       break;
21447adc3a2bSChandler Carruth 
21457adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
21467adc3a2bSChandler Carruth     if (BB->empty())
21477adc3a2bSChandler Carruth       continue;
21487adc3a2bSChandler Carruth 
2149639b29b1SNick Desaulniers     // Disallow inlining a blockaddress with uses other than strictly callbr.
2150639b29b1SNick Desaulniers     // A blockaddress only has defined behavior for an indirect branch in the
2151639b29b1SNick Desaulniers     // same function, and we do not currently support inlining indirect
2152639b29b1SNick Desaulniers     // branches.  But, the inliner may not see an indirect branch that ends up
2153639b29b1SNick Desaulniers     // being dead code at a particular call site. If the blockaddress escapes
2154639b29b1SNick Desaulniers     // the function, e.g., via a global variable, inlining may lead to an
2155639b29b1SNick Desaulniers     // invalid cross-function reference.
2156639b29b1SNick Desaulniers     // FIXME: pr/39560: continue relaxing this overt restriction.
21576a84cd3bSNick Desaulniers     if (BB->hasAddressTaken())
2158639b29b1SNick Desaulniers       for (User *U : BlockAddress::get(&*BB)->users())
2159639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
21605466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
21617adc3a2bSChandler Carruth 
21627adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
21637adc3a2bSChandler Carruth     // returns false, and we can bail on out.
2164c0aa4b75SDavid Bolvansky     InlineResult IR = analyzeBlock(BB, EphValues);
21655466597fSMircea Trofin     if (!IR.isSuccess())
2166c0aa4b75SDavid Bolvansky       return IR;
21677adc3a2bSChandler Carruth 
2168edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
21697adc3a2bSChandler Carruth 
21707adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
21717adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
21727adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
21737adc3a2bSChandler Carruth       if (BI->isConditional()) {
21747adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
2175567556aaSChad Rosier         if (ConstantInt *SimpleCond =
2176567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
21773739e14aSHaicheng Wu           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
21783739e14aSHaicheng Wu           BBWorklist.insert(NextBB);
21793739e14aSHaicheng Wu           KnownSuccessors[BB] = NextBB;
21803739e14aSHaicheng Wu           findDeadBlocks(BB, NextBB);
21817adc3a2bSChandler Carruth           continue;
21827adc3a2bSChandler Carruth         }
21837adc3a2bSChandler Carruth       }
21847adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
21857adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
2186567556aaSChad Rosier       if (ConstantInt *SimpleCond =
2187567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
21883739e14aSHaicheng Wu         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
21893739e14aSHaicheng Wu         BBWorklist.insert(NextBB);
21903739e14aSHaicheng Wu         KnownSuccessors[BB] = NextBB;
21913739e14aSHaicheng Wu         findDeadBlocks(BB, NextBB);
21927adc3a2bSChandler Carruth         continue;
21937adc3a2bSChandler Carruth       }
21947adc3a2bSChandler Carruth     }
21957adc3a2bSChandler Carruth 
21967adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
21977adc3a2bSChandler Carruth     // them.
21987adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
21997adc3a2bSChandler Carruth          ++TIdx)
22007adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
22017adc3a2bSChandler Carruth 
220206408758SMircea Trofin     onBlockAnalyzed(BB);
22037adc3a2bSChandler Carruth   }
22047adc3a2bSChandler Carruth 
220593ac81ccSMircea Trofin   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
220693ac81ccSMircea Trofin                                     &F == CandidateCall.getCalledFunction();
22077adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
22087adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
22097adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
22107adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
22115466597fSMircea Trofin     return InlineResult::failure("noduplicate");
22127adc3a2bSChandler Carruth 
221306408758SMircea Trofin   return finalizeAnalysis();
22147adc3a2bSChandler Carruth }
22157adc3a2bSChandler Carruth 
2216ca899bf9SKirill Naumov void InlineCostCallAnalyzer::print() {
22177adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
22181022b5ebSKirill Naumov   if (PrintInstructionComments)
2219c965fd94SKirill Naumov     F.print(dbgs(), &Writer);
22207adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
22217adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
22227adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
22237adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
22247adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
22257adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
22267adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
22277adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
22287adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
2229a4461515SHaicheng Wu   DEBUG_PRINT_STAT(LoadEliminationCost);
22307adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
22317adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
22327adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
22337adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
22347adc3a2bSChandler Carruth }
2235ca899bf9SKirill Naumov 
2236ca899bf9SKirill Naumov #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2237ca899bf9SKirill Naumov /// Dump stats about this call's analysis.
2238ca899bf9SKirill Naumov LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() {
2239ca899bf9SKirill Naumov   print();
2240ca899bf9SKirill Naumov }
22417adc3a2bSChandler Carruth #endif
22427adc3a2bSChandler Carruth 
22435f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee
22447adc3a2bSChandler Carruth ///        that prevent inlining.
2245f9ca75f1STeresa Johnson static bool functionsHaveCompatibleAttributes(
2246f9ca75f1STeresa Johnson     Function *Caller, Function *Callee, TargetTransformInfo &TTI,
2247f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
2248f9ca75f1STeresa Johnson   // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
2249f9ca75f1STeresa Johnson   // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
2250f9ca75f1STeresa Johnson   // object, and always returns the same object (which is overwritten on each
2251f9ca75f1STeresa Johnson   // GetTLI call). Therefore we copy the first result.
2252f9ca75f1STeresa Johnson   auto CalleeTLI = GetTLI(*Callee);
22537adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
2254f9ca75f1STeresa Johnson          GetTLI(*Caller).areInlineCompatible(CalleeTLI,
2255ed03d948SMehdi Amini                                              InlineCallerSupersetNoBuiltin) &&
22561cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
22577adc3a2bSChandler Carruth }
22587adc3a2bSChandler Carruth 
2259652168a9SFedor Sergeev int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
2260351d9b01SXinliang David Li   int Cost = 0;
2261652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
2262652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2263351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
2264351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
2265652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
2266351d9b01SXinliang David Li       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
226777f32994SBjorn Pettersson       unsigned AS = PTy->getAddressSpace();
226877f32994SBjorn Pettersson       unsigned PointerSize = DL.getPointerSizeInBits(AS);
2269351d9b01SXinliang David Li       // Ceiling division.
2270351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2271351d9b01SXinliang David Li 
2272351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
2273351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
2274351d9b01SXinliang David Li       // one load and one store per word copied.
2275351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
2276351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
2277351d9b01SXinliang David Li       // DataLayout.
2278351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
2279351d9b01SXinliang David Li 
2280351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
2281351d9b01SXinliang David Li     } else {
2282351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
2283351d9b01SXinliang David Li       // argument.
2284351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
2285351d9b01SXinliang David Li     }
2286351d9b01SXinliang David Li   }
2287351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
2288351d9b01SXinliang David Li   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
2289351d9b01SXinliang David Li   return Cost;
2290351d9b01SXinliang David Li }
2291351d9b01SXinliang David Li 
2292ab6a6837SSean Silva InlineCost llvm::getInlineCost(
2293652168a9SFedor Sergeev     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
229408e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2295f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
229608e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
22970812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2298652168a9SFedor Sergeev   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
229908e2386dSMircea Trofin                        GetAssumptionCache, GetTLI, GetBFI, PSI, ORE);
2300b9f7120eSEaswaran Raman }
2301b9f7120eSEaswaran Raman 
2302011a07c0SMircea Trofin Optional<int> llvm::getInliningCostEstimate(
23038a4013edSMircea Trofin     CallBase &Call, TargetTransformInfo &CalleeTTI,
230408e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
230508e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
23068a4013edSMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
23078a4013edSMircea Trofin   const InlineParams Params = {/* DefaultThreshold*/ 0,
23088a4013edSMircea Trofin                                /*HintThreshold*/ {},
23098a4013edSMircea Trofin                                /*ColdThreshold*/ {},
23108a4013edSMircea Trofin                                /*OptSizeThreshold*/ {},
23118a4013edSMircea Trofin                                /*OptMinSizeThreshold*/ {},
23128a4013edSMircea Trofin                                /*HotCallSiteThreshold*/ {},
23138a4013edSMircea Trofin                                /*LocallyHotCallSiteThreshold*/ {},
23148a4013edSMircea Trofin                                /*ColdCallSiteThreshold*/ {},
2315347a599eSKazu Hirata                                /*ComputeFullInlineCost*/ true,
2316347a599eSKazu Hirata                                /*EnableDeferral*/ true};
23178a4013edSMircea Trofin 
231808e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
231908e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE, true,
23208a4013edSMircea Trofin                             /*IgnoreThreshold*/ true);
23218a4013edSMircea Trofin   auto R = CA.analyze();
23228a4013edSMircea Trofin   if (!R.isSuccess())
23238a4013edSMircea Trofin     return None;
23248a4013edSMircea Trofin   return CA.getCost();
23258a4013edSMircea Trofin }
23268a4013edSMircea Trofin 
2327201498c6SMircea Trofin Optional<InlineResult> llvm::getAttributeBasedInliningDecision(
2328201498c6SMircea Trofin     CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
2329201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
2330f4bb2f0dSEaswaran Raman 
23317adc3a2bSChandler Carruth   // Cannot inline indirect calls.
23327adc3a2bSChandler Carruth   if (!Callee)
2333201498c6SMircea Trofin     return InlineResult::failure("indirect call");
23347adc3a2bSChandler Carruth 
2335*31e60b91SXun Li   // When callee coroutine function is inlined into caller coroutine function
2336*31e60b91SXun Li   // before coro-split pass,
2337*31e60b91SXun Li   // coro-early pass can not handle this quiet well.
2338*31e60b91SXun Li   // So we won't inline the coroutine function if it have not been unsplited
2339*31e60b91SXun Li   if (Callee->isPresplitCoroutine())
2340*31e60b91SXun Li     return InlineResult::failure("unsplited coroutine call");
2341*31e60b91SXun Li 
23423851496eSBjorn Pettersson   // Never inline calls with byval arguments that does not have the alloca
23433851496eSBjorn Pettersson   // address space. Since byval arguments can be replaced with a copy to an
23443851496eSBjorn Pettersson   // alloca, the inlined code would need to be adjusted to handle that the
23453851496eSBjorn Pettersson   // argument is in the alloca address space (so it is a little bit complicated
23463851496eSBjorn Pettersson   // to solve).
23473851496eSBjorn Pettersson   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2348652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2349652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2350652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
23513851496eSBjorn Pettersson       if (PTy->getAddressSpace() != AllocaAS)
2352201498c6SMircea Trofin         return InlineResult::failure("byval arguments without alloca"
2353c0aa4b75SDavid Bolvansky                                      " address space");
23543851496eSBjorn Pettersson     }
23553851496eSBjorn Pettersson 
23567adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
23577adc3a2bSChandler Carruth   // whenever possible.
2358652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
235915b17d0aSYevgeny Rouban     auto IsViable = isInlineViable(*Callee);
23605466597fSMircea Trofin     if (IsViable.isSuccess())
2361201498c6SMircea Trofin       return InlineResult::success();
2362201498c6SMircea Trofin     return InlineResult::failure(IsViable.getFailureReason());
23637adc3a2bSChandler Carruth   }
23647adc3a2bSChandler Carruth 
23657adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
23667adc3a2bSChandler Carruth   // always-inline attribute).
2367652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
2368f9ca75f1STeresa Johnson   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI, GetTLI))
2369201498c6SMircea Trofin     return InlineResult::failure("conflicting attributes");
23707adc3a2bSChandler Carruth 
23717adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
237285bd3978SEvandro Menezes   if (Caller->hasOptNone())
2373201498c6SMircea Trofin     return InlineResult::failure("optnone attribute");
23747adc3a2bSChandler Carruth 
237577eeac3dSManoj Gupta   // Don't inline a function that treats null pointer as valid into a caller
237677eeac3dSManoj Gupta   // that does not have this attribute.
237777eeac3dSManoj Gupta   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2378201498c6SMircea Trofin     return InlineResult::failure("nullptr definitions incompatible");
237977eeac3dSManoj Gupta 
2380c0aa4b75SDavid Bolvansky   // Don't inline functions which can be interposed at link-time.
2381c0aa4b75SDavid Bolvansky   if (Callee->isInterposable())
2382201498c6SMircea Trofin     return InlineResult::failure("interposable");
2383c0aa4b75SDavid Bolvansky 
2384c0aa4b75SDavid Bolvansky   // Don't inline functions marked noinline.
2385c0aa4b75SDavid Bolvansky   if (Callee->hasFnAttribute(Attribute::NoInline))
2386201498c6SMircea Trofin     return InlineResult::failure("noinline function attribute");
2387c0aa4b75SDavid Bolvansky 
2388c0aa4b75SDavid Bolvansky   // Don't inline call sites marked noinline.
2389652168a9SFedor Sergeev   if (Call.isNoInline())
2390201498c6SMircea Trofin     return InlineResult::failure("noinline call site attribute");
2391201498c6SMircea Trofin 
2392bc044a88SNick Desaulniers   // Don't inline functions if one does not have any stack protector attribute
2393bc044a88SNick Desaulniers   // but the other does.
2394bc044a88SNick Desaulniers   if (Caller->hasStackProtectorFnAttr() && !Callee->hasStackProtectorFnAttr())
2395bc044a88SNick Desaulniers     return InlineResult::failure(
2396bc044a88SNick Desaulniers         "stack protected caller but callee requested no stack protector");
2397bc044a88SNick Desaulniers   if (Callee->hasStackProtectorFnAttr() && !Caller->hasStackProtectorFnAttr())
2398bc044a88SNick Desaulniers     return InlineResult::failure(
2399bc044a88SNick Desaulniers         "stack protected callee but caller requested no stack protector");
2400bc044a88SNick Desaulniers 
2401201498c6SMircea Trofin   return None;
2402201498c6SMircea Trofin }
2403201498c6SMircea Trofin 
2404201498c6SMircea Trofin InlineCost llvm::getInlineCost(
2405201498c6SMircea Trofin     CallBase &Call, Function *Callee, const InlineParams &Params,
2406201498c6SMircea Trofin     TargetTransformInfo &CalleeTTI,
240708e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2408201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
240908e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2410201498c6SMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2411201498c6SMircea Trofin 
2412201498c6SMircea Trofin   auto UserDecision =
2413201498c6SMircea Trofin       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
2414201498c6SMircea Trofin 
2415201498c6SMircea Trofin   if (UserDecision.hasValue()) {
2416201498c6SMircea Trofin     if (UserDecision->isSuccess())
2417201498c6SMircea Trofin       return llvm::InlineCost::getAlways("always inline attribute");
2418201498c6SMircea Trofin     return llvm::InlineCost::getNever(UserDecision->getFailureReason());
2419201498c6SMircea Trofin   }
24207adc3a2bSChandler Carruth 
2421d34e60caSNicola Zaghen   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
2422201498c6SMircea Trofin                           << "... (caller:" << Call.getCaller()->getName()
2423201498c6SMircea Trofin                           << ")\n");
24247adc3a2bSChandler Carruth 
242508e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
242608e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE);
242793ac81ccSMircea Trofin   InlineResult ShouldInline = CA.analyze();
24287adc3a2bSChandler Carruth 
2429d34e60caSNicola Zaghen   LLVM_DEBUG(CA.dump());
24307adc3a2bSChandler Carruth 
24317adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
24325466597fSMircea Trofin   if (!ShouldInline.isSuccess() && CA.getCost() < CA.getThreshold())
24335466597fSMircea Trofin     return InlineCost::getNever(ShouldInline.getFailureReason());
24345466597fSMircea Trofin   if (ShouldInline.isSuccess() && CA.getCost() >= CA.getThreshold())
2435c0aa4b75SDavid Bolvansky     return InlineCost::getAlways("empty function");
24367adc3a2bSChandler Carruth 
24377adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
24387adc3a2bSChandler Carruth }
24397adc3a2bSChandler Carruth 
244015b17d0aSYevgeny Rouban InlineResult llvm::isInlineViable(Function &F) {
24417adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
244291aff1d8SNick Desaulniers   for (BasicBlock &BB : F) {
2443639b29b1SNick Desaulniers     // Disallow inlining of functions which contain indirect branches.
244491aff1d8SNick Desaulniers     if (isa<IndirectBrInst>(BB.getTerminator()))
24455466597fSMircea Trofin       return InlineResult::failure("contains indirect branches");
244615b17d0aSYevgeny Rouban 
2447639b29b1SNick Desaulniers     // Disallow inlining of blockaddresses which are used by non-callbr
2448639b29b1SNick Desaulniers     // instructions.
244991aff1d8SNick Desaulniers     if (BB.hasAddressTaken())
245091aff1d8SNick Desaulniers       for (User *U : BlockAddress::get(&BB)->users())
2451639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
24525466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
24537adc3a2bSChandler Carruth 
245491aff1d8SNick Desaulniers     for (auto &II : BB) {
2455652168a9SFedor Sergeev       CallBase *Call = dyn_cast<CallBase>(&II);
2456652168a9SFedor Sergeev       if (!Call)
24577adc3a2bSChandler Carruth         continue;
24587adc3a2bSChandler Carruth 
24597adc3a2bSChandler Carruth       // Disallow recursive calls.
2460bc044a88SNick Desaulniers       Function *Callee = Call->getCalledFunction();
2461bc044a88SNick Desaulniers       if (&F == Callee)
24625466597fSMircea Trofin         return InlineResult::failure("recursive call");
24637adc3a2bSChandler Carruth 
24647adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
24657adc3a2bSChandler Carruth       // attributed as such.
2466652168a9SFedor Sergeev       if (!ReturnsTwice && isa<CallInst>(Call) &&
2467652168a9SFedor Sergeev           cast<CallInst>(Call)->canReturnTwice())
24685466597fSMircea Trofin         return InlineResult::failure("exposes returns-twice attribute");
24697adc3a2bSChandler Carruth 
2470bc044a88SNick Desaulniers       if (Callee)
2471bc044a88SNick Desaulniers         switch (Callee->getIntrinsicID()) {
24721636651eSFlorian Hahn         default:
24731636651eSFlorian Hahn           break;
247406408758SMircea Trofin         case llvm::Intrinsic::icall_branch_funnel:
24754296ea72SVitaly Buka           // Disallow inlining of @llvm.icall.branch.funnel because current
24764296ea72SVitaly Buka           // backend can't separate call targets from call arguments.
24775466597fSMircea Trofin           return InlineResult::failure(
24785466597fSMircea Trofin               "disallowed inlining of @llvm.icall.branch.funnel");
247906408758SMircea Trofin         case llvm::Intrinsic::localescape:
24807adc3a2bSChandler Carruth           // Disallow inlining functions that call @llvm.localescape. Doing this
24817adc3a2bSChandler Carruth           // correctly would require major changes to the inliner.
24825466597fSMircea Trofin           return InlineResult::failure(
24835466597fSMircea Trofin               "disallowed inlining of @llvm.localescape");
24841636651eSFlorian Hahn         case llvm::Intrinsic::vastart:
248506408758SMircea Trofin           // Disallow inlining of functions that initialize VarArgs with
248606408758SMircea Trofin           // va_start.
24875466597fSMircea Trofin           return InlineResult::failure(
24885466597fSMircea Trofin               "contains VarArgs initialized with va_start");
24897adc3a2bSChandler Carruth         }
24907adc3a2bSChandler Carruth     }
24911636651eSFlorian Hahn   }
24927adc3a2bSChandler Carruth 
24935466597fSMircea Trofin   return InlineResult::success();
24947adc3a2bSChandler Carruth }
24951c57cc2bSEaswaran Raman 
24961c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
24971c57cc2bSEaswaran Raman // parameters.
24981c57cc2bSEaswaran Raman 
24991c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
25001c57cc2bSEaswaran Raman   InlineParams Params;
25011c57cc2bSEaswaran Raman 
25021c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
25031c57cc2bSEaswaran Raman   // derived from one or more of:
25041c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
25051c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
25061c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
25071c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
25081c57cc2bSEaswaran Raman   //  irrespective of anything else.
25091c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
25101c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
25111c57cc2bSEaswaran Raman   else
25121c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
25131c57cc2bSEaswaran Raman 
25141c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
25151c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
25161c57cc2bSEaswaran Raman 
25171c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
25181c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
25191c57cc2bSEaswaran Raman 
2520974d4eeaSEaswaran Raman   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
2521974d4eeaSEaswaran Raman   // populate LocallyHotCallSiteThreshold. Later, we populate
2522974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
2523974d4eeaSEaswaran Raman   // we know that optimization level is O3 (in the getInlineParams variant that
2524974d4eeaSEaswaran Raman   // takes the opt and size levels).
2525974d4eeaSEaswaran Raman   // FIXME: Remove this check (and make the assignment unconditional) after
2526974d4eeaSEaswaran Raman   // addressing size regression issues at O2.
2527974d4eeaSEaswaran Raman   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
2528974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2529974d4eeaSEaswaran Raman 
25305a956c85SMircea Trofin   // Set the ColdCallSiteThreshold knob from the
25315a956c85SMircea Trofin   // -inline-cold-callsite-threshold.
253212585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
253312585b01SEaswaran Raman 
25341c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
25351c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
25361c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
25371c57cc2bSEaswaran Raman   // minsize attributes.
25381c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
25391c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
25401c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
25411c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
25421c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
25431c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
25441c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
25451c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
25461c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
25471c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
25481c57cc2bSEaswaran Raman   }
25491c57cc2bSEaswaran Raman   return Params;
25501c57cc2bSEaswaran Raman }
25511c57cc2bSEaswaran Raman 
25521c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
25537f37a802STeresa Johnson   return getInlineParams(DefaultThreshold);
25541c57cc2bSEaswaran Raman }
25551c57cc2bSEaswaran Raman 
25561c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
25571c57cc2bSEaswaran Raman // size opt level.
25581c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
25591c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
25601c57cc2bSEaswaran Raman   if (OptLevel > 2)
25611c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
25621c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
25631c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
25641c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
25651c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
25667f37a802STeresa Johnson   return DefaultThreshold;
25671c57cc2bSEaswaran Raman }
25681c57cc2bSEaswaran Raman 
25691c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
2570974d4eeaSEaswaran Raman   auto Params =
2571974d4eeaSEaswaran Raman       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
2572974d4eeaSEaswaran Raman   // At O3, use the value of -locally-hot-callsite-threshold option to populate
2573974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
2574974d4eeaSEaswaran Raman   // when it is specified explicitly.
2575974d4eeaSEaswaran Raman   if (OptLevel > 2)
2576974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2577974d4eeaSEaswaran Raman   return Params;
25781c57cc2bSEaswaran Raman }
25796a5d7d49SKirill Naumov 
25806a5d7d49SKirill Naumov PreservedAnalyses
25816a5d7d49SKirill Naumov InlineCostAnnotationPrinterPass::run(Function &F,
25826a5d7d49SKirill Naumov                                      FunctionAnalysisManager &FAM) {
25836a5d7d49SKirill Naumov   PrintInstructionComments = true;
25846a5d7d49SKirill Naumov   std::function<AssumptionCache &(Function &)> GetAssumptionCache = [&](
25856a5d7d49SKirill Naumov       Function &F) -> AssumptionCache & {
25866a5d7d49SKirill Naumov     return FAM.getResult<AssumptionAnalysis>(F);
25876a5d7d49SKirill Naumov   };
25886a5d7d49SKirill Naumov   Module *M = F.getParent();
25896a5d7d49SKirill Naumov   ProfileSummaryInfo PSI(*M);
25906a5d7d49SKirill Naumov   DataLayout DL(M);
25916a5d7d49SKirill Naumov   TargetTransformInfo TTI(DL);
25926a5d7d49SKirill Naumov   // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
25936a5d7d49SKirill Naumov   // In the current implementation, the type of InlineParams doesn't matter as
25946a5d7d49SKirill Naumov   // the pass serves only for verification of inliner's decisions.
25956a5d7d49SKirill Naumov   // We can add a flag which determines InlineParams for this run. Right now,
25966a5d7d49SKirill Naumov   // the default InlineParams are used.
25976a5d7d49SKirill Naumov   const InlineParams Params = llvm::getInlineParams();
25986a5d7d49SKirill Naumov   for (BasicBlock &BB : F) {
25996a5d7d49SKirill Naumov     for (Instruction &I : BB) {
26006a5d7d49SKirill Naumov       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
26016a5d7d49SKirill Naumov         Function *CalledFunction = CI->getCalledFunction();
26026a5d7d49SKirill Naumov         if (!CalledFunction || CalledFunction->isDeclaration())
26036a5d7d49SKirill Naumov           continue;
26046a5d7d49SKirill Naumov         OptimizationRemarkEmitter ORE(CalledFunction);
26056a5d7d49SKirill Naumov         InlineCostCallAnalyzer ICCA(*CalledFunction, *CI, Params, TTI,
26066a5d7d49SKirill Naumov                                     GetAssumptionCache, nullptr, &PSI, &ORE);
26076a5d7d49SKirill Naumov         ICCA.analyze();
26086a5d7d49SKirill Naumov         OS << "      Analyzing call of " << CalledFunction->getName()
26096a5d7d49SKirill Naumov            << "... (caller:" << CI->getCaller()->getName() << ")\n";
26106a5d7d49SKirill Naumov         ICCA.print();
26116a5d7d49SKirill Naumov       }
26126a5d7d49SKirill Naumov     }
26136a5d7d49SKirill Naumov   }
26146a5d7d49SKirill Naumov   return PreservedAnalyses::all();
26156a5d7d49SKirill Naumov }
2616