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 
749895c701SKazu Hirata static cl::opt<bool> InlineEnableCostBenefitAnalysis(
759895c701SKazu Hirata     "inline-enable-cost-benefit-analysis", cl::Hidden, cl::init(false),
769895c701SKazu Hirata     cl::desc("Enable the cost-benefit analysis for the inliner"));
779895c701SKazu Hirata 
789895c701SKazu Hirata static cl::opt<int> InlineSavingsMultiplier(
799895c701SKazu Hirata     "inline-savings-multiplier", cl::Hidden, cl::init(8), cl::ZeroOrMore,
809895c701SKazu Hirata     cl::desc("Multiplier to multiply cycle savings by during inlining"));
819895c701SKazu Hirata 
829895c701SKazu Hirata static cl::opt<int>
839895c701SKazu Hirata     InlineSizeAllowance("inline-size-allowance", cl::Hidden, cl::init(100),
849895c701SKazu Hirata                         cl::ZeroOrMore,
859895c701SKazu Hirata                         cl::desc("The maximum size of a callee that get's "
869895c701SKazu Hirata                                  "inlined without sufficient cycle savings"));
879895c701SKazu Hirata 
88f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based
89f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and
90f4bb2f0dSEaswaran Raman // BFI.
91f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold(
92fd3e7a93SDavid Callahan     "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore,
93f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with cold attribute"));
94f4bb2f0dSEaswaran Raman 
95de39cb93SDehao Chen static cl::opt<int>
96de39cb93SDehao Chen     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
97de39cb93SDehao Chen                          cl::ZeroOrMore,
98de39cb93SDehao Chen                          cl::desc("Threshold for hot callsites "));
99de39cb93SDehao Chen 
100974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold(
101974d4eeaSEaswaran Raman     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore,
102974d4eeaSEaswaran Raman     cl::desc("Threshold for locally hot callsites "));
103974d4eeaSEaswaran Raman 
104c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq(
105c5fa6358SEaswaran Raman     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
10602a2bb2fSHiroshi Inoue     cl::desc("Maximum block frequency, expressed as a percentage of caller's "
107c5fa6358SEaswaran Raman              "entry frequency, for a callsite to be cold in the absence of "
108c5fa6358SEaswaran Raman              "profile information."));
109c5fa6358SEaswaran Raman 
110974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq(
111974d4eeaSEaswaran Raman     "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore,
112ff77cc75SEaswaran Raman     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
113974d4eeaSEaswaran Raman              "entry frequency, for a callsite to be hot in the absence of "
114974d4eeaSEaswaran Raman              "profile information."));
115974d4eeaSEaswaran Raman 
11646c03668SPhilipp Krones static cl::opt<int> CallPenalty(
11746c03668SPhilipp Krones     "inline-call-penalty", cl::Hidden, cl::init(25),
11846c03668SPhilipp Krones     cl::desc("Call penalty that is applied per callsite when inlining"));
11946c03668SPhilipp Krones 
1204924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost(
121fd3e7a93SDavid Callahan     "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore,
1220812c5beSHaicheng Wu     cl::desc("Compute the full inline cost of a call site even when the cost "
1230812c5beSHaicheng Wu              "exceeds the threshold."));
1240812c5beSHaicheng Wu 
125ed03d948SMehdi Amini static cl::opt<bool> InlineCallerSupersetNoBuiltin(
126ed03d948SMehdi Amini     "inline-caller-superset-nobuiltin", cl::Hidden, cl::init(true),
127ed03d948SMehdi Amini     cl::ZeroOrMore,
128ed03d948SMehdi Amini     cl::desc("Allow inlining when caller has a superset of callee's nobuiltin "
129f9ca75f1STeresa Johnson              "attributes."));
130f9ca75f1STeresa Johnson 
131d48c7859SKirill Naumov static cl::opt<bool> DisableGEPConstOperand(
132d48c7859SKirill Naumov     "disable-gep-const-evaluation", cl::Hidden, cl::init(false),
133d48c7859SKirill Naumov     cl::desc("Disables evaluation of GetElementPtr with constant operands"));
134d48c7859SKirill Naumov 
1357adc3a2bSChandler Carruth namespace {
13606408758SMircea Trofin class InlineCostCallAnalyzer;
137c965fd94SKirill Naumov 
1385c97507eSDaniil Suchkov /// This function behaves more like CallBase::hasFnAttr: when it looks for the
1395c97507eSDaniil Suchkov /// requested attribute, it check both the call instruction and the called
1405c97507eSDaniil Suchkov /// function (if it's available and operand bundles don't prohibit that).
1415c97507eSDaniil Suchkov Attribute getFnAttr(CallBase &CB, StringRef AttrKind) {
1425c97507eSDaniil Suchkov   Attribute CallAttr = CB.getFnAttr(AttrKind);
1435c97507eSDaniil Suchkov   if (CallAttr.isValid())
1445c97507eSDaniil Suchkov     return CallAttr;
1455c97507eSDaniil Suchkov 
1465c97507eSDaniil Suchkov   // Operand bundles override attributes on the called function, but don't
1475c97507eSDaniil Suchkov   // override attributes directly present on the call instruction.
1485c97507eSDaniil Suchkov   if (!CB.isFnAttrDisallowedByOpBundle(AttrKind))
1495c97507eSDaniil Suchkov     if (const Function *F = CB.getCalledFunction())
1505c97507eSDaniil Suchkov       return F->getFnAttribute(AttrKind);
1515c97507eSDaniil Suchkov 
1525c97507eSDaniil Suchkov   return {};
1535c97507eSDaniil Suchkov }
1545c97507eSDaniil Suchkov 
1555c97507eSDaniil Suchkov Optional<int> getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind) {
1565c97507eSDaniil Suchkov   Attribute Attr = getFnAttr(CB, AttrKind);
1575c97507eSDaniil Suchkov   int AttrValue;
1585c97507eSDaniil Suchkov   if (Attr.getValueAsString().getAsInteger(10, AttrValue))
1595c97507eSDaniil Suchkov     return None;
1605c97507eSDaniil Suchkov   return AttrValue;
1615c97507eSDaniil Suchkov }
1625c97507eSDaniil Suchkov 
163c965fd94SKirill Naumov // This struct is used to store information about inline cost of a
164c965fd94SKirill Naumov // particular instruction
165c965fd94SKirill Naumov struct InstructionCostDetail {
166b4924f01SMircea Trofin   int CostBefore = 0;
167b4924f01SMircea Trofin   int CostAfter = 0;
168b4924f01SMircea Trofin   int ThresholdBefore = 0;
169b4924f01SMircea Trofin   int ThresholdAfter = 0;
170b4924f01SMircea Trofin 
171b4924f01SMircea Trofin   int getThresholdDelta() const { return ThresholdAfter - ThresholdBefore; }
172b4924f01SMircea Trofin 
173b4924f01SMircea Trofin   int getCostDelta() const { return CostAfter - CostBefore; }
174b4924f01SMircea Trofin 
175b4924f01SMircea Trofin   bool hasThresholdChanged() const { return ThresholdAfter != ThresholdBefore; }
176c965fd94SKirill Naumov };
177c965fd94SKirill Naumov 
1781022b5ebSKirill Naumov class InlineCostAnnotationWriter : public AssemblyAnnotationWriter {
1791022b5ebSKirill Naumov private:
1801022b5ebSKirill Naumov   InlineCostCallAnalyzer *const ICCA;
181c965fd94SKirill Naumov 
1821022b5ebSKirill Naumov public:
1831022b5ebSKirill Naumov   InlineCostAnnotationWriter(InlineCostCallAnalyzer *ICCA) : ICCA(ICCA) {}
184c965fd94SKirill Naumov   virtual void emitInstructionAnnot(const Instruction *I,
1851022b5ebSKirill Naumov                                     formatted_raw_ostream &OS) override;
186c965fd94SKirill Naumov };
187c965fd94SKirill Naumov 
18808e2386dSMircea Trofin /// Carry out call site analysis, in order to evaluate inlinability.
18908e2386dSMircea Trofin /// NOTE: the type is currently used as implementation detail of functions such
19008e2386dSMircea Trofin /// as llvm::getInlineCost. Note the function_ref constructor parameters - the
19108e2386dSMircea Trofin /// expectation is that they come from the outer scope, from the wrapper
19208e2386dSMircea Trofin /// functions. If we want to support constructing CallAnalyzer objects where
19308e2386dSMircea Trofin /// lambdas are provided inline at construction, or where the object needs to
19408e2386dSMircea Trofin /// otherwise survive past the scope of the provided functions, we need to
19508e2386dSMircea Trofin /// revisit the argument types.
1967adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
1977adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
1987adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
1997adc3a2bSChandler Carruth 
20006408758SMircea Trofin protected:
20106408758SMircea Trofin   virtual ~CallAnalyzer() {}
2027adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
2037adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
2047adc3a2bSChandler Carruth 
205aec2fa35SDaniel Jasper   /// Getter for the cache of @llvm.assume intrinsics.
20608e2386dSMircea Trofin   function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
207aec2fa35SDaniel Jasper 
20812585b01SEaswaran Raman   /// Getter for BlockFrequencyInfo
20908e2386dSMircea Trofin   function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
21012585b01SEaswaran Raman 
21171069cf6SEaswaran Raman   /// Profile summary information.
21271069cf6SEaswaran Raman   ProfileSummaryInfo *PSI;
21371069cf6SEaswaran Raman 
214f3d122cdSPiotr Padlewski   /// The called function.
2157adc3a2bSChandler Carruth   Function &F;
2167adc3a2bSChandler Carruth 
21785be8ca8SEric Christopher   // Cache the DataLayout since we use it a lot.
21885be8ca8SEric Christopher   const DataLayout &DL;
21985be8ca8SEric Christopher 
2200812c5beSHaicheng Wu   /// The OptimizationRemarkEmitter available for this compilation.
2210812c5beSHaicheng Wu   OptimizationRemarkEmitter *ORE;
2220812c5beSHaicheng Wu 
223f3d122cdSPiotr Padlewski   /// The candidate callsite being analyzed. Please do not use this to do
224f3d122cdSPiotr Padlewski   /// analysis in the caller function; we want the inline cost query to be
225f3d122cdSPiotr Padlewski   /// easily cacheable. Instead, use the cover function paramHasAttr.
226652168a9SFedor Sergeev   CallBase &CandidateCall;
2277adc3a2bSChandler Carruth 
22806408758SMircea Trofin   /// Extension points for handling callsite features.
2299895c701SKazu Hirata   // Called before a basic block was analyzed.
2309895c701SKazu Hirata   virtual void onBlockStart(const BasicBlock *BB) {}
2319895c701SKazu Hirata 
23206408758SMircea Trofin   /// Called after a basic block was analyzed.
23306408758SMircea Trofin   virtual void onBlockAnalyzed(const BasicBlock *BB) {}
2341c57cc2bSEaswaran Raman 
235c965fd94SKirill Naumov   /// Called before an instruction was analyzed
236c965fd94SKirill Naumov   virtual void onInstructionAnalysisStart(const Instruction *I) {}
237c965fd94SKirill Naumov 
238c965fd94SKirill Naumov   /// Called after an instruction was analyzed
239c965fd94SKirill Naumov   virtual void onInstructionAnalysisFinish(const Instruction *I) {}
240c965fd94SKirill Naumov 
24106408758SMircea Trofin   /// Called at the end of the analysis of the callsite. Return the outcome of
24206408758SMircea Trofin   /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
24306408758SMircea Trofin   /// the reason it can't.
2445466597fSMircea Trofin   virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
24506408758SMircea Trofin   /// Called when we're about to start processing a basic block, and every time
24606408758SMircea Trofin   /// we are done processing an instruction. Return true if there is no point in
24706408758SMircea Trofin   /// continuing the analysis (e.g. we've determined already the call site is
24806408758SMircea Trofin   /// too expensive to inline)
24906408758SMircea Trofin   virtual bool shouldStop() { return false; }
250eeae45dcSFedor Sergeev 
25106408758SMircea Trofin   /// Called before the analysis of the callee body starts (with callsite
25206408758SMircea Trofin   /// contexts propagated).  It checks callsite-specific information. Return a
25306408758SMircea Trofin   /// reason analysis can't continue if that's the case, or 'true' if it may
25406408758SMircea Trofin   /// continue.
2555466597fSMircea Trofin   virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
25606408758SMircea Trofin   /// Called if the analysis engine decides SROA cannot be done for the given
25706408758SMircea Trofin   /// alloca.
25806408758SMircea Trofin   virtual void onDisableSROA(AllocaInst *Arg) {}
25906408758SMircea Trofin 
26006408758SMircea Trofin   /// Called the analysis engine determines load elimination won't happen.
26106408758SMircea Trofin   virtual void onDisableLoadElimination() {}
26206408758SMircea Trofin 
2635c97507eSDaniil Suchkov   /// Called when we visit a CallBase, before the analysis starts. Return false
2645c97507eSDaniil Suchkov   /// to stop further processing of the instruction.
2655c97507eSDaniil Suchkov   virtual bool onCallBaseVisitStart(CallBase &Call) { return true; }
2665c97507eSDaniil Suchkov 
26706408758SMircea Trofin   /// Called to account for a call.
26806408758SMircea Trofin   virtual void onCallPenalty() {}
26906408758SMircea Trofin 
27006408758SMircea Trofin   /// Called to account for the expectation the inlining would result in a load
27106408758SMircea Trofin   /// elimination.
27206408758SMircea Trofin   virtual void onLoadEliminationOpportunity() {}
27306408758SMircea Trofin 
27406408758SMircea Trofin   /// Called to account for the cost of argument setup for the Call in the
27506408758SMircea Trofin   /// callee's body (not the callsite currently under analysis).
27606408758SMircea Trofin   virtual void onCallArgumentSetup(const CallBase &Call) {}
27706408758SMircea Trofin 
27806408758SMircea Trofin   /// Called to account for a load relative intrinsic.
27906408758SMircea Trofin   virtual void onLoadRelativeIntrinsic() {}
28006408758SMircea Trofin 
28106408758SMircea Trofin   /// Called to account for a lowered call.
28206408758SMircea Trofin   virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
28306408758SMircea Trofin   }
28406408758SMircea Trofin 
28506408758SMircea Trofin   /// Account for a jump table of given size. Return false to stop further
28606408758SMircea Trofin   /// processing the switch instruction
28706408758SMircea Trofin   virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
28806408758SMircea Trofin 
28906408758SMircea Trofin   /// Account for a case cluster of given size. Return false to stop further
29006408758SMircea Trofin   /// processing of the instruction.
29106408758SMircea Trofin   virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
29206408758SMircea Trofin 
29306408758SMircea Trofin   /// Called at the end of processing a switch instruction, with the given
29406408758SMircea Trofin   /// number of case clusters.
29506408758SMircea Trofin   virtual void onFinalizeSwitch(unsigned JumpTableSize,
29606408758SMircea Trofin                                 unsigned NumCaseCluster) {}
29706408758SMircea Trofin 
29806408758SMircea Trofin   /// Called to account for any other instruction not specifically accounted
29906408758SMircea Trofin   /// for.
30014a16faeSMircea Trofin   virtual void onMissedSimplification() {}
30106408758SMircea Trofin 
30206408758SMircea Trofin   /// Start accounting potential benefits due to SROA for the given alloca.
30306408758SMircea Trofin   virtual void onInitializeSROAArg(AllocaInst *Arg) {}
30406408758SMircea Trofin 
30506408758SMircea Trofin   /// Account SROA savings for the AllocaInst value.
30606408758SMircea Trofin   virtual void onAggregateSROAUse(AllocaInst *V) {}
30706408758SMircea Trofin 
30806408758SMircea Trofin   bool handleSROA(Value *V, bool DoNotDisable) {
30906408758SMircea Trofin     // Check for SROA candidates in comparisons.
31006408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
31106408758SMircea Trofin       if (DoNotDisable) {
31206408758SMircea Trofin         onAggregateSROAUse(SROAArg);
31306408758SMircea Trofin         return true;
31406408758SMircea Trofin       }
31506408758SMircea Trofin       disableSROAForArg(SROAArg);
31606408758SMircea Trofin     }
31706408758SMircea Trofin     return false;
31806408758SMircea Trofin   }
3197adc3a2bSChandler Carruth 
320eeae45dcSFedor Sergeev   bool IsCallerRecursive = false;
321eeae45dcSFedor Sergeev   bool IsRecursiveCall = false;
322eeae45dcSFedor Sergeev   bool ExposesReturnsTwice = false;
323eeae45dcSFedor Sergeev   bool HasDynamicAlloca = false;
324eeae45dcSFedor Sergeev   bool ContainsNoDuplicateCall = false;
325eeae45dcSFedor Sergeev   bool HasReturn = false;
326eeae45dcSFedor Sergeev   bool HasIndirectBr = false;
327eeae45dcSFedor Sergeev   bool HasUninlineableIntrinsic = false;
328eeae45dcSFedor Sergeev   bool InitsVargArgs = false;
3297adc3a2bSChandler Carruth 
3307adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
331eeae45dcSFedor Sergeev   uint64_t AllocatedSize = 0;
332eeae45dcSFedor Sergeev   unsigned NumInstructions = 0;
333eeae45dcSFedor Sergeev   unsigned NumVectorInstructions = 0;
334eeae45dcSFedor Sergeev 
335f3d122cdSPiotr Padlewski   /// While we walk the potentially-inlined instructions, we build up and
336f3d122cdSPiotr Padlewski   /// maintain a mapping of simplified values specific to this callsite. The
337f3d122cdSPiotr Padlewski   /// idea is to propagate any special information we have about arguments to
338f3d122cdSPiotr Padlewski   /// this call through the inlinable section of the function, and account for
339f3d122cdSPiotr Padlewski   /// likely simplifications post-inlining. The most important aspect we track
340f3d122cdSPiotr Padlewski   /// is CFG altering simplifications -- when we prove a basic block dead, that
341f3d122cdSPiotr Padlewski   /// can cause dramatic shifts in the cost of inlining a function.
3427adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
3437adc3a2bSChandler Carruth 
344f3d122cdSPiotr Padlewski   /// Keep track of the values which map back (through function arguments) to
345f3d122cdSPiotr Padlewski   /// allocas on the caller stack which could be simplified through SROA.
34606408758SMircea Trofin   DenseMap<Value *, AllocaInst *> SROAArgValues;
347338a6016SMircea Trofin 
34806408758SMircea Trofin   /// Keep track of Allocas for which we believe we may get SROA optimization.
3492e42cc7aSMircea Trofin   DenseSet<AllocaInst *> EnabledSROAAllocas;
3507adc3a2bSChandler Carruth 
351f3d122cdSPiotr Padlewski   /// Keep track of values which map to a pointer base and constant offset.
3527adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
3537adc3a2bSChandler Carruth 
3543739e14aSHaicheng Wu   /// Keep track of dead blocks due to the constant arguments.
3553739e14aSHaicheng Wu   SetVector<BasicBlock *> DeadBlocks;
3563739e14aSHaicheng Wu 
3573739e14aSHaicheng Wu   /// The mapping of the blocks to their known unique successors due to the
3583739e14aSHaicheng Wu   /// constant arguments.
3593739e14aSHaicheng Wu   DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
3603739e14aSHaicheng Wu 
361a4461515SHaicheng Wu   /// Model the elimination of repeated loads that is expected to happen
362a4461515SHaicheng Wu   /// whenever we simplify away the stores that would otherwise cause them to be
363a4461515SHaicheng Wu   /// loads.
364a4461515SHaicheng Wu   bool EnableLoadElimination;
365*f7fff46aSWenlei He 
366*f7fff46aSWenlei He   /// Whether we allow inlining for recursive call.
367*f7fff46aSWenlei He   bool AllowRecursiveCall;
368*f7fff46aSWenlei He 
369a4461515SHaicheng Wu   SmallPtrSet<Value *, 16> LoadAddrSet;
37006408758SMircea Trofin 
37106408758SMircea Trofin   AllocaInst *getSROAArgForValueOrNull(Value *V) const {
37206408758SMircea Trofin     auto It = SROAArgValues.find(V);
3732e42cc7aSMircea Trofin     if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
37406408758SMircea Trofin       return nullptr;
37506408758SMircea Trofin     return It->second;
37606408758SMircea Trofin   }
377a4461515SHaicheng Wu 
3787adc3a2bSChandler Carruth   // Custom simplification helper routines.
3797adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
38006408758SMircea Trofin   void disableSROAForArg(AllocaInst *SROAArg);
3817adc3a2bSChandler Carruth   void disableSROA(Value *V);
3823739e14aSHaicheng Wu   void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
383a4461515SHaicheng Wu   void disableLoadElimination();
384201b191bSHaicheng Wu   bool isGEPFree(GetElementPtrInst &GEP);
385d3558b5dSEvgeny Astigeevich   bool canFoldInboundsGEP(GetElementPtrInst &I);
3867adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
387652168a9SFedor Sergeev   bool simplifyCallSite(Function *F, CallBase &Call);
388617f6364SEaswaran Raman   template <typename Callable>
389617f6364SEaswaran Raman   bool simplifyInstruction(Instruction &I, Callable Evaluate);
3907adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
3917adc3a2bSChandler Carruth 
3927adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
3937adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
3947adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
3957adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
3967adc3a2bSChandler Carruth   /// itself.
3977adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
3987adc3a2bSChandler Carruth 
3997adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
4007adc3a2bSChandler Carruth   /// inlined through this particular callsite.
4017adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
4027adc3a2bSChandler Carruth 
403652168a9SFedor Sergeev   /// Return true if size growth is allowed when inlining the callee at \p Call.
404652168a9SFedor Sergeev   bool allowSizeGrowth(CallBase &Call);
4059a3fc17aSEaswaran Raman 
4067adc3a2bSChandler Carruth   // Custom analysis routines.
407c0aa4b75SDavid Bolvansky   InlineResult analyzeBlock(BasicBlock *BB,
408c0aa4b75SDavid Bolvansky                             SmallPtrSetImpl<const Value *> &EphValues);
4097adc3a2bSChandler Carruth 
4107adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
4117adc3a2bSChandler Carruth   // them by declaring but not defining them here.
412567556aaSChad Rosier   void visit(Module *);
413567556aaSChad Rosier   void visit(Module &);
414567556aaSChad Rosier   void visit(Function *);
415567556aaSChad Rosier   void visit(Function &);
416567556aaSChad Rosier   void visit(BasicBlock *);
417567556aaSChad Rosier   void visit(BasicBlock &);
4187adc3a2bSChandler Carruth 
4197adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
4207adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
4217adc3a2bSChandler Carruth 
4227adc3a2bSChandler Carruth   // Our visit overrides.
4237adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
4247adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
4257adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
4267adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
4277adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
4287adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
4297adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
4307adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
4317adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
4327adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
4336cda33baSCraig Topper   bool visitFNeg(UnaryOperator &I);
4347adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
4357adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
4367adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
4377adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
438652168a9SFedor Sergeev   bool visitCallBase(CallBase &Call);
4397adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
4407adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
4413ec848bcSHaicheng Wu   bool visitSelectInst(SelectInst &SI);
4427adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
4437adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
4447adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
4457adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
4467adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
4477adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
4487adc3a2bSChandler Carruth 
4497adc3a2bSChandler Carruth public:
4507b639f50SJacob Hegna   CallAnalyzer(Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
45108e2386dSMircea Trofin                function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
45208e2386dSMircea Trofin                function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
45308e2386dSMircea Trofin                ProfileSummaryInfo *PSI = nullptr,
45408e2386dSMircea Trofin                OptimizationRemarkEmitter *ORE = nullptr)
45512585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
4560812c5beSHaicheng Wu         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
457*f7fff46aSWenlei He         CandidateCall(Call), EnableLoadElimination(true),
458*f7fff46aSWenlei He         AllowRecursiveCall(false) {}
4597adc3a2bSChandler Carruth 
46093ac81ccSMircea Trofin   InlineResult analyze();
4617adc3a2bSChandler Carruth 
4627f094f7fSKirill Naumov   Optional<Constant *> getSimplifiedValue(Instruction *I) {
4637f094f7fSKirill Naumov     if (SimplifiedValues.find(I) != SimplifiedValues.end())
4647f094f7fSKirill Naumov       return SimplifiedValues[I];
4657f094f7fSKirill Naumov     return None;
4667f094f7fSKirill Naumov   }
4677f094f7fSKirill Naumov 
4687adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
4697adc3a2bSChandler Carruth   // out when debugging.
470eeae45dcSFedor Sergeev   unsigned NumConstantArgs = 0;
471eeae45dcSFedor Sergeev   unsigned NumConstantOffsetPtrArgs = 0;
472eeae45dcSFedor Sergeev   unsigned NumAllocaArgs = 0;
473eeae45dcSFedor Sergeev   unsigned NumConstantPtrCmps = 0;
474eeae45dcSFedor Sergeev   unsigned NumConstantPtrDiffs = 0;
475eeae45dcSFedor Sergeev   unsigned NumInstructionsSimplified = 0;
47676aab66dSMircea Trofin 
47776aab66dSMircea Trofin   void dump();
47876aab66dSMircea Trofin };
479338a6016SMircea Trofin 
48099f00635SJacob Hegna // Considering forming a binary search, we should find the number of nodes
48199f00635SJacob Hegna // which is same as the number of comparisons when lowered. For a given
48299f00635SJacob Hegna // number of clusters, n, we can define a recursive function, f(n), to find
48399f00635SJacob Hegna // the number of nodes in the tree. The recursion is :
48499f00635SJacob Hegna // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
48599f00635SJacob Hegna // and f(n) = n, when n <= 3.
48699f00635SJacob Hegna // This will lead a binary tree where the leaf should be either f(2) or f(3)
48799f00635SJacob Hegna // when n > 3.  So, the number of comparisons from leaves should be n, while
48899f00635SJacob Hegna // the number of non-leaf should be :
48999f00635SJacob Hegna //   2^(log2(n) - 1) - 1
49099f00635SJacob Hegna //   = 2^log2(n) * 2^-1 - 1
49199f00635SJacob Hegna //   = n / 2 - 1.
49299f00635SJacob Hegna // Considering comparisons from leaf and non-leaf nodes, we can estimate the
49399f00635SJacob Hegna // number of comparisons in a simple closed form :
49499f00635SJacob Hegna //   n + n / 2 - 1 = n * 3 / 2 - 1
49599f00635SJacob Hegna int64_t getExpectedNumberOfCompare(int NumCaseCluster) {
49699f00635SJacob Hegna   return 3 * static_cast<int64_t>(NumCaseCluster) / 2 - 1;
49799f00635SJacob Hegna }
49899f00635SJacob Hegna 
49906408758SMircea Trofin /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
50006408758SMircea Trofin /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
50106408758SMircea Trofin class InlineCostCallAnalyzer final : public CallAnalyzer {
50206408758SMircea Trofin   const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
50306408758SMircea Trofin   const bool ComputeFullInlineCost;
50406408758SMircea Trofin   int LoadEliminationCost = 0;
50506408758SMircea Trofin   /// Bonus to be applied when percentage of vector instructions in callee is
50606408758SMircea Trofin   /// high (see more details in updateThreshold).
50706408758SMircea Trofin   int VectorBonus = 0;
50806408758SMircea Trofin   /// Bonus to be applied when the callee has only one reachable basic block.
50906408758SMircea Trofin   int SingleBBBonus = 0;
51006408758SMircea Trofin 
51106408758SMircea Trofin   /// Tunable parameters that control the analysis.
51206408758SMircea Trofin   const InlineParams &Params;
51306408758SMircea Trofin 
5141022b5ebSKirill Naumov   // This DenseMap stores the delta change in cost and threshold after
5151022b5ebSKirill Naumov   // accounting for the given instruction. The map is filled only with the
5161022b5ebSKirill Naumov   // flag PrintInstructionComments on.
5171022b5ebSKirill Naumov   DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
5181022b5ebSKirill Naumov 
51906408758SMircea Trofin   /// Upper bound for the inlining cost. Bonuses are being applied to account
52006408758SMircea Trofin   /// for speculative "expected profit" of the inlining decision.
52106408758SMircea Trofin   int Threshold = 0;
52206408758SMircea Trofin 
52306408758SMircea Trofin   /// Attempt to evaluate indirect calls to boost its inline cost.
52406408758SMircea Trofin   const bool BoostIndirectCalls;
52506408758SMircea Trofin 
5268a4013edSMircea Trofin   /// Ignore the threshold when finalizing analysis.
5278a4013edSMircea Trofin   const bool IgnoreThreshold;
5288a4013edSMircea Trofin 
5299895c701SKazu Hirata   // True if the cost-benefit-analysis-based inliner is enabled.
5309895c701SKazu Hirata   const bool CostBenefitAnalysisEnabled;
5319895c701SKazu Hirata 
53206408758SMircea Trofin   /// Inlining cost measured in abstract units, accounts for all the
53306408758SMircea Trofin   /// instructions expected to be executed for a given function invocation.
53406408758SMircea Trofin   /// Instructions that are statically proven to be dead based on call-site
53506408758SMircea Trofin   /// arguments are not counted here.
53606408758SMircea Trofin   int Cost = 0;
53706408758SMircea Trofin 
5389895c701SKazu Hirata   // The cumulative cost at the beginning of the basic block being analyzed.  At
5399895c701SKazu Hirata   // the end of analyzing each basic block, "Cost - CostAtBBStart" represents
5409895c701SKazu Hirata   // the size of that basic block.
5419895c701SKazu Hirata   int CostAtBBStart = 0;
5429895c701SKazu Hirata 
5439895c701SKazu Hirata   // The static size of live but cold basic blocks.  This is "static" in the
5449895c701SKazu Hirata   // sense that it's not weighted by profile counts at all.
5459895c701SKazu Hirata   int ColdSize = 0;
5469895c701SKazu Hirata 
5476869e6c1SWenlei He   // Whether inlining is decided by cost-benefit analysis.
5486869e6c1SWenlei He   bool DecidedByCostBenefit = false;
5496869e6c1SWenlei He 
5504bdfea2cSLiqiang Tao   // The cost-benefit pair computed by cost-benefit analysis.
5514bdfea2cSLiqiang Tao   Optional<CostBenefitPair> CostBenefit = None;
5524bdfea2cSLiqiang Tao 
55306408758SMircea Trofin   bool SingleBB = true;
55406408758SMircea Trofin 
55506408758SMircea Trofin   unsigned SROACostSavings = 0;
55606408758SMircea Trofin   unsigned SROACostSavingsLost = 0;
55706408758SMircea Trofin 
55806408758SMircea Trofin   /// The mapping of caller Alloca values to their accumulated cost savings. If
55906408758SMircea Trofin   /// we have to disable SROA for one of the allocas, this tells us how much
56006408758SMircea Trofin   /// cost must be added.
56106408758SMircea Trofin   DenseMap<AllocaInst *, int> SROAArgCosts;
56206408758SMircea Trofin 
56306408758SMircea Trofin   /// Return true if \p Call is a cold callsite.
56406408758SMircea Trofin   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
56506408758SMircea Trofin 
56606408758SMircea Trofin   /// Update Threshold based on callsite properties such as callee
56706408758SMircea Trofin   /// attributes and callee hotness for PGO builds. The Callee is explicitly
56806408758SMircea Trofin   /// passed to support analyzing indirect calls whose target is inferred by
56906408758SMircea Trofin   /// analysis.
57006408758SMircea Trofin   void updateThreshold(CallBase &Call, Function &Callee);
57106408758SMircea Trofin   /// Return a higher threshold if \p Call is a hot callsite.
57206408758SMircea Trofin   Optional<int> getHotCallSiteThreshold(CallBase &Call,
57306408758SMircea Trofin                                         BlockFrequencyInfo *CallerBFI);
57406408758SMircea Trofin 
57506408758SMircea Trofin   /// Handle a capped 'int' increment for Cost.
57606408758SMircea Trofin   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
57706408758SMircea Trofin     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
578cfc4def8SJacob Hegna     Cost = std::min<int>(UpperBound, Cost + Inc);
57906408758SMircea Trofin   }
58006408758SMircea Trofin 
58106408758SMircea Trofin   void onDisableSROA(AllocaInst *Arg) override {
58206408758SMircea Trofin     auto CostIt = SROAArgCosts.find(Arg);
58306408758SMircea Trofin     if (CostIt == SROAArgCosts.end())
58406408758SMircea Trofin       return;
58506408758SMircea Trofin     addCost(CostIt->second);
58606408758SMircea Trofin     SROACostSavings -= CostIt->second;
58706408758SMircea Trofin     SROACostSavingsLost += CostIt->second;
58806408758SMircea Trofin     SROAArgCosts.erase(CostIt);
58906408758SMircea Trofin   }
59006408758SMircea Trofin 
59106408758SMircea Trofin   void onDisableLoadElimination() override {
59206408758SMircea Trofin     addCost(LoadEliminationCost);
59306408758SMircea Trofin     LoadEliminationCost = 0;
59406408758SMircea Trofin   }
5955c97507eSDaniil Suchkov 
5965c97507eSDaniil Suchkov   bool onCallBaseVisitStart(CallBase &Call) override {
5975c97507eSDaniil Suchkov     if (Optional<int> AttrCallThresholdBonus =
5985c97507eSDaniil Suchkov             getStringFnAttrAsInt(Call, "call-threshold-bonus"))
5995c97507eSDaniil Suchkov       Threshold += *AttrCallThresholdBonus;
6005c97507eSDaniil Suchkov 
6015c97507eSDaniil Suchkov     if (Optional<int> AttrCallCost =
6025c97507eSDaniil Suchkov             getStringFnAttrAsInt(Call, "call-inline-cost")) {
6035c97507eSDaniil Suchkov       addCost(*AttrCallCost);
6045c97507eSDaniil Suchkov       // Prevent further processing of the call since we want to override its
6055c97507eSDaniil Suchkov       // inline cost, not just add to it.
6065c97507eSDaniil Suchkov       return false;
6075c97507eSDaniil Suchkov     }
6085c97507eSDaniil Suchkov     return true;
6095c97507eSDaniil Suchkov   }
6105c97507eSDaniil Suchkov 
61146c03668SPhilipp Krones   void onCallPenalty() override { addCost(CallPenalty); }
61206408758SMircea Trofin   void onCallArgumentSetup(const CallBase &Call) override {
61306408758SMircea Trofin     // Pay the price of the argument setup. We account for the average 1
61406408758SMircea Trofin     // instruction per call argument setup here.
61506408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
61606408758SMircea Trofin   }
61706408758SMircea Trofin   void onLoadRelativeIntrinsic() override {
61806408758SMircea Trofin     // This is normally lowered to 4 LLVM instructions.
61906408758SMircea Trofin     addCost(3 * InlineConstants::InstrCost);
62006408758SMircea Trofin   }
62106408758SMircea Trofin   void onLoweredCall(Function *F, CallBase &Call,
62206408758SMircea Trofin                      bool IsIndirectCall) override {
62306408758SMircea Trofin     // We account for the average 1 instruction per call argument setup here.
62406408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
62506408758SMircea Trofin 
62606408758SMircea Trofin     // If we have a constant that we are calling as a function, we can peer
62706408758SMircea Trofin     // through it and see the function target. This happens not infrequently
62806408758SMircea Trofin     // during devirtualization and so we want to give it a hefty bonus for
62906408758SMircea Trofin     // inlining, but cap that bonus in the event that inlining wouldn't pan out.
63006408758SMircea Trofin     // Pretend to inline the function, with a custom threshold.
63106408758SMircea Trofin     if (IsIndirectCall && BoostIndirectCalls) {
63206408758SMircea Trofin       auto IndirectCallParams = Params;
63306408758SMircea Trofin       IndirectCallParams.DefaultThreshold =
63406408758SMircea Trofin           InlineConstants::IndirectCallThreshold;
63506408758SMircea Trofin       /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
63606408758SMircea Trofin       /// to instantiate the derived class.
63708e2386dSMircea Trofin       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
63808e2386dSMircea Trofin                                 GetAssumptionCache, GetBFI, PSI, ORE, false);
6395466597fSMircea Trofin       if (CA.analyze().isSuccess()) {
64006408758SMircea Trofin         // We were able to inline the indirect call! Subtract the cost from the
64106408758SMircea Trofin         // threshold to get the bonus we want to apply, but don't go below zero.
64206408758SMircea Trofin         Cost -= std::max(0, CA.getThreshold() - CA.getCost());
64306408758SMircea Trofin       }
64406408758SMircea Trofin     } else
64506408758SMircea Trofin       // Otherwise simply add the cost for merely making the call.
64646c03668SPhilipp Krones       addCost(CallPenalty);
64706408758SMircea Trofin   }
64806408758SMircea Trofin 
64906408758SMircea Trofin   void onFinalizeSwitch(unsigned JumpTableSize,
65006408758SMircea Trofin                         unsigned NumCaseCluster) override {
65106408758SMircea Trofin     // If suitable for a jump table, consider the cost for the table size and
65206408758SMircea Trofin     // branch to destination.
65306408758SMircea Trofin     // Maximum valid cost increased in this function.
65406408758SMircea Trofin     if (JumpTableSize) {
655cfc4def8SJacob Hegna       int64_t JTCost =
656cfc4def8SJacob Hegna           static_cast<int64_t>(JumpTableSize) * InlineConstants::InstrCost +
65706408758SMircea Trofin           4 * InlineConstants::InstrCost;
65806408758SMircea Trofin 
659cfc4def8SJacob Hegna       addCost(JTCost, static_cast<int64_t>(CostUpperBound));
66006408758SMircea Trofin       return;
66106408758SMircea Trofin     }
66299f00635SJacob Hegna 
66306408758SMircea Trofin     if (NumCaseCluster <= 3) {
66406408758SMircea Trofin       // Suppose a comparison includes one compare and one conditional branch.
66506408758SMircea Trofin       addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
66606408758SMircea Trofin       return;
66706408758SMircea Trofin     }
66806408758SMircea Trofin 
66999f00635SJacob Hegna     int64_t ExpectedNumberOfCompare =
67099f00635SJacob Hegna         getExpectedNumberOfCompare(NumCaseCluster);
67106408758SMircea Trofin     int64_t SwitchCost =
67206408758SMircea Trofin         ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
67306408758SMircea Trofin 
674cfc4def8SJacob Hegna     addCost(SwitchCost, static_cast<int64_t>(CostUpperBound));
67506408758SMircea Trofin   }
67614a16faeSMircea Trofin   void onMissedSimplification() override {
67706408758SMircea Trofin     addCost(InlineConstants::InstrCost);
67806408758SMircea Trofin   }
67906408758SMircea Trofin 
68006408758SMircea Trofin   void onInitializeSROAArg(AllocaInst *Arg) override {
68106408758SMircea Trofin     assert(Arg != nullptr &&
68206408758SMircea Trofin            "Should not initialize SROA costs for null value.");
68306408758SMircea Trofin     SROAArgCosts[Arg] = 0;
68406408758SMircea Trofin   }
68506408758SMircea Trofin 
68606408758SMircea Trofin   void onAggregateSROAUse(AllocaInst *SROAArg) override {
68706408758SMircea Trofin     auto CostIt = SROAArgCosts.find(SROAArg);
68806408758SMircea Trofin     assert(CostIt != SROAArgCosts.end() &&
68906408758SMircea Trofin            "expected this argument to have a cost");
69006408758SMircea Trofin     CostIt->second += InlineConstants::InstrCost;
69106408758SMircea Trofin     SROACostSavings += InlineConstants::InstrCost;
69206408758SMircea Trofin   }
69306408758SMircea Trofin 
6949895c701SKazu Hirata   void onBlockStart(const BasicBlock *BB) override { CostAtBBStart = Cost; }
6959895c701SKazu Hirata 
69606408758SMircea Trofin   void onBlockAnalyzed(const BasicBlock *BB) override {
6979895c701SKazu Hirata     if (CostBenefitAnalysisEnabled) {
6989895c701SKazu Hirata       // Keep track of the static size of live but cold basic blocks.  For now,
6999895c701SKazu Hirata       // we define a cold basic block to be one that's never executed.
7009895c701SKazu Hirata       assert(GetBFI && "GetBFI must be available");
7019895c701SKazu Hirata       BlockFrequencyInfo *BFI = &(GetBFI(F));
7029895c701SKazu Hirata       assert(BFI && "BFI must be available");
7039895c701SKazu Hirata       auto ProfileCount = BFI->getBlockProfileCount(BB);
7049895c701SKazu Hirata       assert(ProfileCount.hasValue());
7059895c701SKazu Hirata       if (ProfileCount.getValue() == 0)
7069895c701SKazu Hirata         ColdSize += Cost - CostAtBBStart;
7079895c701SKazu Hirata     }
7089895c701SKazu Hirata 
70906408758SMircea Trofin     auto *TI = BB->getTerminator();
71006408758SMircea Trofin     // If we had any successors at this point, than post-inlining is likely to
71106408758SMircea Trofin     // have them as well. Note that we assume any basic blocks which existed
71206408758SMircea Trofin     // due to branches or switches which folded above will also fold after
71306408758SMircea Trofin     // inlining.
71406408758SMircea Trofin     if (SingleBB && TI->getNumSuccessors() > 1) {
71506408758SMircea Trofin       // Take off the bonus we applied to the threshold.
71606408758SMircea Trofin       Threshold -= SingleBBBonus;
71706408758SMircea Trofin       SingleBB = false;
71806408758SMircea Trofin     }
71906408758SMircea Trofin   }
7205466597fSMircea Trofin 
721c965fd94SKirill Naumov   void onInstructionAnalysisStart(const Instruction *I) override {
722c965fd94SKirill Naumov     // This function is called to store the initial cost of inlining before
723c965fd94SKirill Naumov     // the given instruction was assessed.
7241022b5ebSKirill Naumov     if (!PrintInstructionComments)
725c965fd94SKirill Naumov       return;
7261022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostBefore = Cost;
7271022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdBefore = Threshold;
728c965fd94SKirill Naumov   }
729c965fd94SKirill Naumov 
730c965fd94SKirill Naumov   void onInstructionAnalysisFinish(const Instruction *I) override {
731c965fd94SKirill Naumov     // This function is called to find new values of cost and threshold after
732c965fd94SKirill Naumov     // the instruction has been assessed.
7331022b5ebSKirill Naumov     if (!PrintInstructionComments)
734c965fd94SKirill Naumov       return;
7351022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostAfter = Cost;
7361022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdAfter = Threshold;
737c965fd94SKirill Naumov   }
738c965fd94SKirill Naumov 
7399895c701SKazu Hirata   bool isCostBenefitAnalysisEnabled() {
7409895c701SKazu Hirata     if (!PSI || !PSI->hasProfileSummary())
7419895c701SKazu Hirata       return false;
7429895c701SKazu Hirata 
7439895c701SKazu Hirata     if (!GetBFI)
7449895c701SKazu Hirata       return false;
7459895c701SKazu Hirata 
7469d375a40SKazu Hirata     if (InlineEnableCostBenefitAnalysis.getNumOccurrences()) {
7479d375a40SKazu Hirata       // Honor the explicit request from the user.
7489d375a40SKazu Hirata       if (!InlineEnableCostBenefitAnalysis)
7499d375a40SKazu Hirata         return false;
7509d375a40SKazu Hirata     } else {
7519d375a40SKazu Hirata       // Otherwise, require instrumentation profile.
7529d375a40SKazu Hirata       if (!PSI->hasInstrumentationProfile())
7539d375a40SKazu Hirata         return false;
7549d375a40SKazu Hirata     }
7559d375a40SKazu Hirata 
7569895c701SKazu Hirata     auto *Caller = CandidateCall.getParent()->getParent();
7579895c701SKazu Hirata     if (!Caller->getEntryCount())
7589895c701SKazu Hirata       return false;
7599895c701SKazu Hirata 
7609895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*Caller));
7619895c701SKazu Hirata     if (!CallerBFI)
7629895c701SKazu Hirata       return false;
7639895c701SKazu Hirata 
7649895c701SKazu Hirata     // For now, limit to hot call site.
7659895c701SKazu Hirata     if (!PSI->isHotCallSite(CandidateCall, CallerBFI))
7669895c701SKazu Hirata       return false;
7679895c701SKazu Hirata 
7683c775d93SKazu Hirata     // Make sure we have a nonzero entry count.
7693c775d93SKazu Hirata     auto EntryCount = F.getEntryCount();
7703c775d93SKazu Hirata     if (!EntryCount || !EntryCount.getCount())
7719895c701SKazu Hirata       return false;
7729895c701SKazu Hirata 
7739895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
7749895c701SKazu Hirata     if (!CalleeBFI)
7759895c701SKazu Hirata       return false;
7769895c701SKazu Hirata 
7779895c701SKazu Hirata     return true;
7789895c701SKazu Hirata   }
7799895c701SKazu Hirata 
7809895c701SKazu Hirata   // Determine whether we should inline the given call site, taking into account
7819895c701SKazu Hirata   // both the size cost and the cycle savings.  Return None if we don't have
7829895c701SKazu Hirata   // suficient profiling information to determine.
7839895c701SKazu Hirata   Optional<bool> costBenefitAnalysis() {
7849895c701SKazu Hirata     if (!CostBenefitAnalysisEnabled)
7859895c701SKazu Hirata       return None;
7869895c701SKazu Hirata 
7879895c701SKazu Hirata     // buildInlinerPipeline in the pass builder sets HotCallSiteThreshold to 0
7889895c701SKazu Hirata     // for the prelink phase of the AutoFDO + ThinLTO build.  Honor the logic by
7899895c701SKazu Hirata     // falling back to the cost-based metric.
7909895c701SKazu Hirata     // TODO: Improve this hacky condition.
7919895c701SKazu Hirata     if (Threshold == 0)
7929895c701SKazu Hirata       return None;
7939895c701SKazu Hirata 
7949895c701SKazu Hirata     assert(GetBFI);
7959895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
7969895c701SKazu Hirata     assert(CalleeBFI);
7979895c701SKazu Hirata 
7989895c701SKazu Hirata     // The cycle savings expressed as the sum of InlineConstants::InstrCost
7999895c701SKazu Hirata     // multiplied by the estimated dynamic count of each instruction we can
8009895c701SKazu Hirata     // avoid.  Savings come from the call site cost, such as argument setup and
8019895c701SKazu Hirata     // the call instruction, as well as the instructions that are folded.
8029895c701SKazu Hirata     //
8039895c701SKazu Hirata     // We use 128-bit APInt here to avoid potential overflow.  This variable
8049895c701SKazu Hirata     // should stay well below 10^^24 (or 2^^80) in practice.  This "worst" case
8059895c701SKazu Hirata     // assumes that we can avoid or fold a billion instructions, each with a
8069895c701SKazu Hirata     // profile count of 10^^15 -- roughly the number of cycles for a 24-hour
8079895c701SKazu Hirata     // period on a 4GHz machine.
8089895c701SKazu Hirata     APInt CycleSavings(128, 0);
8099895c701SKazu Hirata 
8109895c701SKazu Hirata     for (auto &BB : F) {
8119895c701SKazu Hirata       APInt CurrentSavings(128, 0);
8129895c701SKazu Hirata       for (auto &I : BB) {
8139895c701SKazu Hirata         if (BranchInst *BI = dyn_cast<BranchInst>(&I)) {
8149895c701SKazu Hirata           // Count a conditional branch as savings if it becomes unconditional.
8159895c701SKazu Hirata           if (BI->isConditional() &&
8169895c701SKazu Hirata               dyn_cast_or_null<ConstantInt>(
8179895c701SKazu Hirata                   SimplifiedValues.lookup(BI->getCondition()))) {
8189895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
8199895c701SKazu Hirata           }
8209895c701SKazu Hirata         } else if (Value *V = dyn_cast<Value>(&I)) {
8219895c701SKazu Hirata           // Count an instruction as savings if we can fold it.
8229895c701SKazu Hirata           if (SimplifiedValues.count(V)) {
8239895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
8249895c701SKazu Hirata           }
8259895c701SKazu Hirata         }
8269895c701SKazu Hirata       }
8279895c701SKazu Hirata 
8289895c701SKazu Hirata       auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
8299895c701SKazu Hirata       assert(ProfileCount.hasValue());
8309895c701SKazu Hirata       CurrentSavings *= ProfileCount.getValue();
8319895c701SKazu Hirata       CycleSavings += CurrentSavings;
8329895c701SKazu Hirata     }
8339895c701SKazu Hirata 
8349895c701SKazu Hirata     // Compute the cycle savings per call.
8359895c701SKazu Hirata     auto EntryProfileCount = F.getEntryCount();
8363c775d93SKazu Hirata     assert(EntryProfileCount.hasValue() && EntryProfileCount.getCount());
8379895c701SKazu Hirata     auto EntryCount = EntryProfileCount.getCount();
8389895c701SKazu Hirata     CycleSavings += EntryCount / 2;
8399895c701SKazu Hirata     CycleSavings = CycleSavings.udiv(EntryCount);
8409895c701SKazu Hirata 
8419895c701SKazu Hirata     // Compute the total savings for the call site.
8429895c701SKazu Hirata     auto *CallerBB = CandidateCall.getParent();
8439895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*(CallerBB->getParent())));
8449895c701SKazu Hirata     CycleSavings += getCallsiteCost(this->CandidateCall, DL);
8459895c701SKazu Hirata     CycleSavings *= CallerBFI->getBlockProfileCount(CallerBB).getValue();
8469895c701SKazu Hirata 
8479895c701SKazu Hirata     // Remove the cost of the cold basic blocks.
8489895c701SKazu Hirata     int Size = Cost - ColdSize;
8499895c701SKazu Hirata 
8509895c701SKazu Hirata     // Allow tiny callees to be inlined regardless of whether they meet the
8519895c701SKazu Hirata     // savings threshold.
8529895c701SKazu Hirata     Size = Size > InlineSizeAllowance ? Size - InlineSizeAllowance : 1;
8539895c701SKazu Hirata 
8544bdfea2cSLiqiang Tao     CostBenefit.emplace(APInt(128, Size), CycleSavings);
8554bdfea2cSLiqiang Tao 
8569895c701SKazu Hirata     // Return true if the savings justify the cost of inlining.  Specifically,
8579895c701SKazu Hirata     // we evaluate the following inequality:
8589895c701SKazu Hirata     //
8599895c701SKazu Hirata     //  CycleSavings      PSI->getOrCompHotCountThreshold()
8609895c701SKazu Hirata     // -------------- >= -----------------------------------
8619895c701SKazu Hirata     //       Size              InlineSavingsMultiplier
8629895c701SKazu Hirata     //
8639895c701SKazu Hirata     // Note that the left hand side is specific to a call site.  The right hand
8649895c701SKazu Hirata     // side is a constant for the entire executable.
8659895c701SKazu Hirata     APInt LHS = CycleSavings;
8669895c701SKazu Hirata     LHS *= InlineSavingsMultiplier;
8679895c701SKazu Hirata     APInt RHS(128, PSI->getOrCompHotCountThreshold());
8689895c701SKazu Hirata     RHS *= Size;
8699895c701SKazu Hirata     return LHS.uge(RHS);
8709895c701SKazu Hirata   }
8719895c701SKazu Hirata 
87206408758SMircea Trofin   InlineResult finalizeAnalysis() override {
87306408758SMircea Trofin     // Loops generally act a lot like calls in that they act like barriers to
87406408758SMircea Trofin     // movement, require a certain amount of setup, etc. So when optimising for
87506408758SMircea Trofin     // size, we penalise any call sites that perform loops. We do this after all
87606408758SMircea Trofin     // other costs here, so will likely only be dealing with relatively small
87706408758SMircea Trofin     // functions (and hence DT and LI will hopefully be cheap).
87806408758SMircea Trofin     auto *Caller = CandidateCall.getFunction();
87906408758SMircea Trofin     if (Caller->hasMinSize()) {
88006408758SMircea Trofin       DominatorTree DT(F);
88106408758SMircea Trofin       LoopInfo LI(DT);
88206408758SMircea Trofin       int NumLoops = 0;
88306408758SMircea Trofin       for (Loop *L : LI) {
88406408758SMircea Trofin         // Ignore loops that will not be executed
88506408758SMircea Trofin         if (DeadBlocks.count(L->getHeader()))
88606408758SMircea Trofin           continue;
88706408758SMircea Trofin         NumLoops++;
88806408758SMircea Trofin       }
88946c03668SPhilipp Krones       addCost(NumLoops * InlineConstants::LoopPenalty);
89006408758SMircea Trofin     }
89106408758SMircea Trofin 
89206408758SMircea Trofin     // We applied the maximum possible vector bonus at the beginning. Now,
89306408758SMircea Trofin     // subtract the excess bonus, if any, from the Threshold before
89406408758SMircea Trofin     // comparing against Cost.
89506408758SMircea Trofin     if (NumVectorInstructions <= NumInstructions / 10)
89606408758SMircea Trofin       Threshold -= VectorBonus;
89706408758SMircea Trofin     else if (NumVectorInstructions <= NumInstructions / 2)
89806408758SMircea Trofin       Threshold -= VectorBonus / 2;
89906408758SMircea Trofin 
9005c97507eSDaniil Suchkov     if (Optional<int> AttrCost =
9015c97507eSDaniil Suchkov             getStringFnAttrAsInt(CandidateCall, "function-inline-cost"))
9025c97507eSDaniil Suchkov       Cost = *AttrCost;
9035c97507eSDaniil Suchkov 
9045c97507eSDaniil Suchkov     if (Optional<int> AttrThreshold =
9055c97507eSDaniil Suchkov             getStringFnAttrAsInt(CandidateCall, "function-inline-threshold"))
9065c97507eSDaniil Suchkov       Threshold = *AttrThreshold;
9075c97507eSDaniil Suchkov 
9089895c701SKazu Hirata     if (auto Result = costBenefitAnalysis()) {
9096869e6c1SWenlei He       DecidedByCostBenefit = true;
9109895c701SKazu Hirata       if (Result.getValue())
9119895c701SKazu Hirata         return InlineResult::success();
9129895c701SKazu Hirata       else
9139895c701SKazu Hirata         return InlineResult::failure("Cost over threshold.");
9149895c701SKazu Hirata     }
9159895c701SKazu Hirata 
9168a4013edSMircea Trofin     if (IgnoreThreshold || Cost < std::max(1, Threshold))
9175466597fSMircea Trofin       return InlineResult::success();
9185466597fSMircea Trofin     return InlineResult::failure("Cost over threshold.");
91906408758SMircea Trofin   }
92006408758SMircea Trofin   bool shouldStop() override {
92106408758SMircea Trofin     // Bail out the moment we cross the threshold. This means we'll under-count
92206408758SMircea Trofin     // the cost, but only when undercounting doesn't matter.
9238a4013edSMircea Trofin     return !IgnoreThreshold && Cost >= Threshold && !ComputeFullInlineCost;
92406408758SMircea Trofin   }
92506408758SMircea Trofin 
92606408758SMircea Trofin   void onLoadEliminationOpportunity() override {
92706408758SMircea Trofin     LoadEliminationCost += InlineConstants::InstrCost;
92806408758SMircea Trofin   }
92906408758SMircea Trofin 
93006408758SMircea Trofin   InlineResult onAnalysisStart() override {
93106408758SMircea Trofin     // Perform some tweaks to the cost and threshold based on the direct
93206408758SMircea Trofin     // callsite information.
93306408758SMircea Trofin 
93406408758SMircea Trofin     // We want to more aggressively inline vector-dense kernels, so up the
93506408758SMircea Trofin     // threshold, and we'll lower it if the % of vector instructions gets too
93606408758SMircea Trofin     // low. Note that these bonuses are some what arbitrary and evolved over
93706408758SMircea Trofin     // time by accident as much as because they are principled bonuses.
93806408758SMircea Trofin     //
93906408758SMircea Trofin     // FIXME: It would be nice to remove all such bonuses. At least it would be
94006408758SMircea Trofin     // nice to base the bonus values on something more scientific.
94106408758SMircea Trofin     assert(NumInstructions == 0);
94206408758SMircea Trofin     assert(NumVectorInstructions == 0);
94306408758SMircea Trofin 
94406408758SMircea Trofin     // Update the threshold based on callsite properties
94506408758SMircea Trofin     updateThreshold(CandidateCall, F);
94606408758SMircea Trofin 
94706408758SMircea Trofin     // While Threshold depends on commandline options that can take negative
94806408758SMircea Trofin     // values, we want to enforce the invariant that the computed threshold and
94906408758SMircea Trofin     // bonuses are non-negative.
95006408758SMircea Trofin     assert(Threshold >= 0);
95106408758SMircea Trofin     assert(SingleBBBonus >= 0);
95206408758SMircea Trofin     assert(VectorBonus >= 0);
95306408758SMircea Trofin 
95406408758SMircea Trofin     // Speculatively apply all possible bonuses to Threshold. If cost exceeds
95506408758SMircea Trofin     // this Threshold any time, and cost cannot decrease, we can stop processing
95606408758SMircea Trofin     // the rest of the function body.
95706408758SMircea Trofin     Threshold += (SingleBBBonus + VectorBonus);
95806408758SMircea Trofin 
95906408758SMircea Trofin     // Give out bonuses for the callsite, as the instructions setting them up
96006408758SMircea Trofin     // will be gone after inlining.
96106408758SMircea Trofin     addCost(-getCallsiteCost(this->CandidateCall, DL));
96206408758SMircea Trofin 
96306408758SMircea Trofin     // If this function uses the coldcc calling convention, prefer not to inline
96406408758SMircea Trofin     // it.
96506408758SMircea Trofin     if (F.getCallingConv() == CallingConv::Cold)
96606408758SMircea Trofin       Cost += InlineConstants::ColdccPenalty;
96706408758SMircea Trofin 
96806408758SMircea Trofin     // Check if we're done. This can happen due to bonuses and penalties.
96906408758SMircea Trofin     if (Cost >= Threshold && !ComputeFullInlineCost)
9705466597fSMircea Trofin       return InlineResult::failure("high cost");
97106408758SMircea Trofin 
9725466597fSMircea Trofin     return InlineResult::success();
97306408758SMircea Trofin   }
97406408758SMircea Trofin 
97506408758SMircea Trofin public:
97606408758SMircea Trofin   InlineCostCallAnalyzer(
97708e2386dSMircea Trofin       Function &Callee, CallBase &Call, const InlineParams &Params,
97806408758SMircea Trofin       const TargetTransformInfo &TTI,
97908e2386dSMircea Trofin       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
98008e2386dSMircea Trofin       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
98108e2386dSMircea Trofin       ProfileSummaryInfo *PSI = nullptr,
98208e2386dSMircea Trofin       OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
9838a4013edSMircea Trofin       bool IgnoreThreshold = false)
98408e2386dSMircea Trofin       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI, ORE),
98506408758SMircea Trofin         ComputeFullInlineCost(OptComputeFullInlineCost ||
98665cd3cbbSKazu Hirata                               Params.ComputeFullInlineCost || ORE ||
98765cd3cbbSKazu Hirata                               isCostBenefitAnalysisEnabled()),
98806408758SMircea Trofin         Params(Params), Threshold(Params.DefaultThreshold),
9891022b5ebSKirill Naumov         BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
9909895c701SKazu Hirata         CostBenefitAnalysisEnabled(isCostBenefitAnalysisEnabled()),
991*f7fff46aSWenlei He         Writer(this) {
992*f7fff46aSWenlei He     AllowRecursiveCall = Params.AllowRecursiveCall.getValue();
993*f7fff46aSWenlei He   }
994c965fd94SKirill Naumov 
9951022b5ebSKirill Naumov   /// Annotation Writer for instruction details
9961022b5ebSKirill Naumov   InlineCostAnnotationWriter Writer;
997c965fd94SKirill Naumov 
99806408758SMircea Trofin   void dump();
99906408758SMircea Trofin 
1000ca899bf9SKirill Naumov   // Prints the same analysis as dump(), but its definition is not dependent
1001ca899bf9SKirill Naumov   // on the build.
1002ca899bf9SKirill Naumov   void print();
1003ca899bf9SKirill Naumov 
10041022b5ebSKirill Naumov   Optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
10051022b5ebSKirill Naumov     if (InstructionCostDetailMap.find(I) != InstructionCostDetailMap.end())
10061022b5ebSKirill Naumov       return InstructionCostDetailMap[I];
10071022b5ebSKirill Naumov     return None;
10081022b5ebSKirill Naumov   }
10091022b5ebSKirill Naumov 
101006408758SMircea Trofin   virtual ~InlineCostCallAnalyzer() {}
1011cfc4def8SJacob Hegna   int getThreshold() const { return Threshold; }
1012cfc4def8SJacob Hegna   int getCost() const { return Cost; }
10134bdfea2cSLiqiang Tao   Optional<CostBenefitPair> getCostBenefitPair() { return CostBenefit; }
1014cfc4def8SJacob Hegna   bool wasDecidedByCostBenefit() const { return DecidedByCostBenefit; }
101506408758SMircea Trofin };
101699f00635SJacob Hegna 
101799f00635SJacob Hegna class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
101899f00635SJacob Hegna private:
101999f00635SJacob Hegna   InlineCostFeatures Cost = {};
102099f00635SJacob Hegna 
102199f00635SJacob Hegna   // FIXME: These constants are taken from the heuristic-based cost visitor.
102299f00635SJacob Hegna   // These should be removed entirely in a later revision to avoid reliance on
102399f00635SJacob Hegna   // heuristics in the ML inliner.
102499f00635SJacob Hegna   static constexpr int JTCostMultiplier = 4;
102599f00635SJacob Hegna   static constexpr int CaseClusterCostMultiplier = 2;
102699f00635SJacob Hegna   static constexpr int SwitchCostMultiplier = 2;
102799f00635SJacob Hegna 
102899f00635SJacob Hegna   // FIXME: These are taken from the heuristic-based cost visitor: we should
102999f00635SJacob Hegna   // eventually abstract these to the CallAnalyzer to avoid duplication.
103099f00635SJacob Hegna   unsigned SROACostSavingOpportunities = 0;
103199f00635SJacob Hegna   int VectorBonus = 0;
103299f00635SJacob Hegna   int SingleBBBonus = 0;
103399f00635SJacob Hegna   int Threshold = 5;
103499f00635SJacob Hegna 
103599f00635SJacob Hegna   DenseMap<AllocaInst *, unsigned> SROACosts;
103699f00635SJacob Hegna 
103799f00635SJacob Hegna   void increment(InlineCostFeatureIndex Feature, int64_t Delta = 1) {
103899f00635SJacob Hegna     Cost[static_cast<size_t>(Feature)] += Delta;
103999f00635SJacob Hegna   }
104099f00635SJacob Hegna 
104199f00635SJacob Hegna   void set(InlineCostFeatureIndex Feature, int64_t Value) {
104299f00635SJacob Hegna     Cost[static_cast<size_t>(Feature)] = Value;
104399f00635SJacob Hegna   }
104499f00635SJacob Hegna 
104599f00635SJacob Hegna   void onDisableSROA(AllocaInst *Arg) override {
104699f00635SJacob Hegna     auto CostIt = SROACosts.find(Arg);
104799f00635SJacob Hegna     if (CostIt == SROACosts.end())
104899f00635SJacob Hegna       return;
104999f00635SJacob Hegna 
105099f00635SJacob Hegna     increment(InlineCostFeatureIndex::SROALosses, CostIt->second);
105199f00635SJacob Hegna     SROACostSavingOpportunities -= CostIt->second;
105299f00635SJacob Hegna     SROACosts.erase(CostIt);
105399f00635SJacob Hegna   }
105499f00635SJacob Hegna 
105599f00635SJacob Hegna   void onDisableLoadElimination() override {
105699f00635SJacob Hegna     set(InlineCostFeatureIndex::LoadElimination, 1);
105799f00635SJacob Hegna   }
105899f00635SJacob Hegna 
105999f00635SJacob Hegna   void onCallPenalty() override {
106046c03668SPhilipp Krones     increment(InlineCostFeatureIndex::CallPenalty, CallPenalty);
106199f00635SJacob Hegna   }
106299f00635SJacob Hegna 
106399f00635SJacob Hegna   void onCallArgumentSetup(const CallBase &Call) override {
106499f00635SJacob Hegna     increment(InlineCostFeatureIndex::CallArgumentSetup,
106599f00635SJacob Hegna               Call.arg_size() * InlineConstants::InstrCost);
106699f00635SJacob Hegna   }
106799f00635SJacob Hegna 
106899f00635SJacob Hegna   void onLoadRelativeIntrinsic() override {
106999f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoadRelativeIntrinsic,
107099f00635SJacob Hegna               3 * InlineConstants::InstrCost);
107199f00635SJacob Hegna   }
107299f00635SJacob Hegna 
107399f00635SJacob Hegna   void onLoweredCall(Function *F, CallBase &Call,
107499f00635SJacob Hegna                      bool IsIndirectCall) override {
107599f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoweredCallArgSetup,
107699f00635SJacob Hegna               Call.arg_size() * InlineConstants::InstrCost);
107799f00635SJacob Hegna 
107899f00635SJacob Hegna     if (IsIndirectCall) {
107999f00635SJacob Hegna       InlineParams IndirectCallParams = {/* DefaultThreshold*/ 0,
108099f00635SJacob Hegna                                          /*HintThreshold*/ {},
108199f00635SJacob Hegna                                          /*ColdThreshold*/ {},
108299f00635SJacob Hegna                                          /*OptSizeThreshold*/ {},
108399f00635SJacob Hegna                                          /*OptMinSizeThreshold*/ {},
108499f00635SJacob Hegna                                          /*HotCallSiteThreshold*/ {},
108599f00635SJacob Hegna                                          /*LocallyHotCallSiteThreshold*/ {},
108699f00635SJacob Hegna                                          /*ColdCallSiteThreshold*/ {},
108799f00635SJacob Hegna                                          /*ComputeFullInlineCost*/ true,
108899f00635SJacob Hegna                                          /*EnableDeferral*/ true};
108999f00635SJacob Hegna       IndirectCallParams.DefaultThreshold =
109099f00635SJacob Hegna           InlineConstants::IndirectCallThreshold;
109199f00635SJacob Hegna 
109299f00635SJacob Hegna       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
109399f00635SJacob Hegna                                 GetAssumptionCache, GetBFI, PSI, ORE, false,
109499f00635SJacob Hegna                                 true);
109599f00635SJacob Hegna       if (CA.analyze().isSuccess()) {
109699f00635SJacob Hegna         increment(InlineCostFeatureIndex::NestedInlineCostEstimate,
109799f00635SJacob Hegna                   CA.getCost());
109899f00635SJacob Hegna         increment(InlineCostFeatureIndex::NestedInlines, 1);
109999f00635SJacob Hegna       }
110099f00635SJacob Hegna     } else {
110199f00635SJacob Hegna       onCallPenalty();
110299f00635SJacob Hegna     }
110399f00635SJacob Hegna   }
110499f00635SJacob Hegna 
110599f00635SJacob Hegna   void onFinalizeSwitch(unsigned JumpTableSize,
110699f00635SJacob Hegna                         unsigned NumCaseCluster) override {
110799f00635SJacob Hegna 
110899f00635SJacob Hegna     if (JumpTableSize) {
110999f00635SJacob Hegna       int64_t JTCost =
111099f00635SJacob Hegna           static_cast<int64_t>(JumpTableSize) * InlineConstants::InstrCost +
111199f00635SJacob Hegna           JTCostMultiplier * InlineConstants::InstrCost;
111299f00635SJacob Hegna       increment(InlineCostFeatureIndex::JumpTablePenalty, JTCost);
111399f00635SJacob Hegna       return;
111499f00635SJacob Hegna     }
111599f00635SJacob Hegna 
111699f00635SJacob Hegna     if (NumCaseCluster <= 3) {
111799f00635SJacob Hegna       increment(InlineCostFeatureIndex::CaseClusterPenalty,
111899f00635SJacob Hegna                 NumCaseCluster * CaseClusterCostMultiplier *
111999f00635SJacob Hegna                     InlineConstants::InstrCost);
112099f00635SJacob Hegna       return;
112199f00635SJacob Hegna     }
112299f00635SJacob Hegna 
112399f00635SJacob Hegna     int64_t ExpectedNumberOfCompare =
112499f00635SJacob Hegna         getExpectedNumberOfCompare(NumCaseCluster);
112599f00635SJacob Hegna 
112699f00635SJacob Hegna     int64_t SwitchCost = ExpectedNumberOfCompare * SwitchCostMultiplier *
112799f00635SJacob Hegna                          InlineConstants::InstrCost;
112899f00635SJacob Hegna     increment(InlineCostFeatureIndex::SwitchPenalty, SwitchCost);
112999f00635SJacob Hegna   }
113099f00635SJacob Hegna 
113199f00635SJacob Hegna   void onMissedSimplification() override {
113299f00635SJacob Hegna     increment(InlineCostFeatureIndex::UnsimplifiedCommonInstructions,
113399f00635SJacob Hegna               InlineConstants::InstrCost);
113499f00635SJacob Hegna   }
113599f00635SJacob Hegna 
113699f00635SJacob Hegna   void onInitializeSROAArg(AllocaInst *Arg) override { SROACosts[Arg] = 0; }
113799f00635SJacob Hegna   void onAggregateSROAUse(AllocaInst *Arg) override {
113899f00635SJacob Hegna     SROACosts.find(Arg)->second += InlineConstants::InstrCost;
113999f00635SJacob Hegna     SROACostSavingOpportunities += InlineConstants::InstrCost;
114099f00635SJacob Hegna   }
114199f00635SJacob Hegna 
114299f00635SJacob Hegna   void onBlockAnalyzed(const BasicBlock *BB) override {
114399f00635SJacob Hegna     if (BB->getTerminator()->getNumSuccessors() > 1)
114499f00635SJacob Hegna       set(InlineCostFeatureIndex::IsMultipleBlocks, 1);
114599f00635SJacob Hegna     Threshold -= SingleBBBonus;
114699f00635SJacob Hegna   }
114799f00635SJacob Hegna 
114899f00635SJacob Hegna   InlineResult finalizeAnalysis() override {
114999f00635SJacob Hegna     auto *Caller = CandidateCall.getFunction();
115099f00635SJacob Hegna     if (Caller->hasMinSize()) {
115199f00635SJacob Hegna       DominatorTree DT(F);
115299f00635SJacob Hegna       LoopInfo LI(DT);
115399f00635SJacob Hegna       for (Loop *L : LI) {
115499f00635SJacob Hegna         // Ignore loops that will not be executed
115599f00635SJacob Hegna         if (DeadBlocks.count(L->getHeader()))
115699f00635SJacob Hegna           continue;
115799f00635SJacob Hegna         increment(InlineCostFeatureIndex::NumLoops,
115846c03668SPhilipp Krones                   InlineConstants::LoopPenalty);
115999f00635SJacob Hegna       }
116099f00635SJacob Hegna     }
116199f00635SJacob Hegna     set(InlineCostFeatureIndex::DeadBlocks, DeadBlocks.size());
116299f00635SJacob Hegna     set(InlineCostFeatureIndex::SimplifiedInstructions,
116399f00635SJacob Hegna         NumInstructionsSimplified);
116499f00635SJacob Hegna     set(InlineCostFeatureIndex::ConstantArgs, NumConstantArgs);
116599f00635SJacob Hegna     set(InlineCostFeatureIndex::ConstantOffsetPtrArgs,
116699f00635SJacob Hegna         NumConstantOffsetPtrArgs);
116799f00635SJacob Hegna     set(InlineCostFeatureIndex::SROASavings, SROACostSavingOpportunities);
116899f00635SJacob Hegna 
116999f00635SJacob Hegna     if (NumVectorInstructions <= NumInstructions / 10)
11701f3e90e1SJacob Hegna       Threshold -= VectorBonus;
117199f00635SJacob Hegna     else if (NumVectorInstructions <= NumInstructions / 2)
11721f3e90e1SJacob Hegna       Threshold -= VectorBonus / 2;
117399f00635SJacob Hegna 
117499f00635SJacob Hegna     set(InlineCostFeatureIndex::Threshold, Threshold);
117599f00635SJacob Hegna 
117699f00635SJacob Hegna     return InlineResult::success();
117799f00635SJacob Hegna   }
117899f00635SJacob Hegna 
117999f00635SJacob Hegna   bool shouldStop() override { return false; }
118099f00635SJacob Hegna 
118199f00635SJacob Hegna   void onLoadEliminationOpportunity() override {
118299f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoadElimination, 1);
118399f00635SJacob Hegna   }
118499f00635SJacob Hegna 
118599f00635SJacob Hegna   InlineResult onAnalysisStart() override {
118699f00635SJacob Hegna     increment(InlineCostFeatureIndex::CallSiteCost,
118799f00635SJacob Hegna               -1 * getCallsiteCost(this->CandidateCall, DL));
118899f00635SJacob Hegna 
118999f00635SJacob Hegna     set(InlineCostFeatureIndex::ColdCcPenalty,
119099f00635SJacob Hegna         (F.getCallingConv() == CallingConv::Cold));
119199f00635SJacob Hegna 
119299f00635SJacob Hegna     // FIXME: we shouldn't repeat this logic in both the Features and Cost
119399f00635SJacob Hegna     // analyzer - instead, we should abstract it to a common method in the
119499f00635SJacob Hegna     // CallAnalyzer
119599f00635SJacob Hegna     int SingleBBBonusPercent = 50;
119699f00635SJacob Hegna     int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
119799f00635SJacob Hegna     Threshold += TTI.adjustInliningThreshold(&CandidateCall);
119899f00635SJacob Hegna     Threshold *= TTI.getInliningThresholdMultiplier();
119999f00635SJacob Hegna     SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
120099f00635SJacob Hegna     VectorBonus = Threshold * VectorBonusPercent / 100;
120199f00635SJacob Hegna     Threshold += (SingleBBBonus + VectorBonus);
120299f00635SJacob Hegna 
120399f00635SJacob Hegna     return InlineResult::success();
120499f00635SJacob Hegna   }
120599f00635SJacob Hegna 
120699f00635SJacob Hegna public:
120799f00635SJacob Hegna   InlineCostFeaturesAnalyzer(
120899f00635SJacob Hegna       const TargetTransformInfo &TTI,
120999f00635SJacob Hegna       function_ref<AssumptionCache &(Function &)> &GetAssumptionCache,
121099f00635SJacob Hegna       function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
121199f00635SJacob Hegna       ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
121299f00635SJacob Hegna       CallBase &Call)
121399f00635SJacob Hegna       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI) {}
121499f00635SJacob Hegna 
121599f00635SJacob Hegna   const InlineCostFeatures &features() const { return Cost; }
121699f00635SJacob Hegna };
121799f00635SJacob Hegna 
12187adc3a2bSChandler Carruth } // namespace
12197adc3a2bSChandler Carruth 
12205f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument.
12217adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
12227adc3a2bSChandler Carruth   return SROAArgValues.count(V);
12237adc3a2bSChandler Carruth }
12247adc3a2bSChandler Carruth 
122506408758SMircea Trofin void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
122606408758SMircea Trofin   onDisableSROA(SROAArg);
12272e42cc7aSMircea Trofin   EnabledSROAAllocas.erase(SROAArg);
1228338a6016SMircea Trofin   disableLoadElimination();
1229338a6016SMircea Trofin }
1230c965fd94SKirill Naumov 
12317b639f50SJacob Hegna void InlineCostAnnotationWriter::emitInstructionAnnot(
12327b639f50SJacob Hegna     const Instruction *I, formatted_raw_ostream &OS) {
1233c965fd94SKirill Naumov   // The cost of inlining of the given instruction is printed always.
1234c965fd94SKirill Naumov   // The threshold delta is printed only when it is non-zero. It happens
1235c965fd94SKirill Naumov   // when we decided to give a bonus at a particular instruction.
12361022b5ebSKirill Naumov   Optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
12371022b5ebSKirill Naumov   if (!Record)
12381022b5ebSKirill Naumov     OS << "; No analysis for the instruction";
12391022b5ebSKirill Naumov   else {
12401022b5ebSKirill Naumov     OS << "; cost before = " << Record->CostBefore
12411022b5ebSKirill Naumov        << ", cost after = " << Record->CostAfter
12421022b5ebSKirill Naumov        << ", threshold before = " << Record->ThresholdBefore
12431022b5ebSKirill Naumov        << ", threshold after = " << Record->ThresholdAfter << ", ";
12441022b5ebSKirill Naumov     OS << "cost delta = " << Record->getCostDelta();
12451022b5ebSKirill Naumov     if (Record->hasThresholdChanged())
12461022b5ebSKirill Naumov       OS << ", threshold delta = " << Record->getThresholdDelta();
12470383253cSKirill Naumov   }
12487f094f7fSKirill Naumov   auto C = ICCA->getSimplifiedValue(const_cast<Instruction *>(I));
12497f094f7fSKirill Naumov   if (C) {
12507f094f7fSKirill Naumov     OS << ", simplified to ";
12517f094f7fSKirill Naumov     C.getValue()->print(OS, true);
12527f094f7fSKirill Naumov   }
1253c965fd94SKirill Naumov   OS << "\n";
1254c965fd94SKirill Naumov }
1255c965fd94SKirill Naumov 
12565f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it.
12577adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
125806408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
125906408758SMircea Trofin     disableSROAForArg(SROAArg);
1260338a6016SMircea Trofin   }
12617adc3a2bSChandler Carruth }
12627adc3a2bSChandler Carruth 
1263a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() {
1264a4461515SHaicheng Wu   if (EnableLoadElimination) {
126506408758SMircea Trofin     onDisableLoadElimination();
1266a4461515SHaicheng Wu     EnableLoadElimination = false;
1267a4461515SHaicheng Wu   }
1268a4461515SHaicheng Wu }
1269a4461515SHaicheng Wu 
12705f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible.
12717adc3a2bSChandler Carruth ///
12727adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
12737adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
12747adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
1275945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
12767adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
12777adc3a2bSChandler Carruth 
12787adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
12797adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
12807adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
12817adc3a2bSChandler Carruth     if (!OpC)
12827adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
12837adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
12847adc3a2bSChandler Carruth     if (!OpC)
12857adc3a2bSChandler Carruth       return false;
1286567556aaSChad Rosier     if (OpC->isZero())
1287567556aaSChad Rosier       continue;
12887adc3a2bSChandler Carruth 
12897adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
1290ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
12917adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
12927adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
12937adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
12947adc3a2bSChandler Carruth       continue;
12957adc3a2bSChandler Carruth     }
12967adc3a2bSChandler Carruth 
12977adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
12987adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
12997adc3a2bSChandler Carruth   }
13007adc3a2bSChandler Carruth   return true;
13017adc3a2bSChandler Carruth }
13027adc3a2bSChandler Carruth 
13035f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free.
1304201b191bSHaicheng Wu ///
1305201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
1306201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
130761c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
130861c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
130991aff1d8SNick Desaulniers   for (const Use &Op : GEP.indices())
131091aff1d8SNick Desaulniers     if (Constant *SimpleOp = SimplifiedValues.lookup(Op))
131161c1bd5aSEvgeny Astigeevich       Operands.push_back(SimpleOp);
1312201b191bSHaicheng Wu     else
131391aff1d8SNick Desaulniers       Operands.push_back(Op);
13143ccbd4f3SSander de Smalen   return TTI.getUserCost(&GEP, Operands,
13153ccbd4f3SSander de Smalen                          TargetTransformInfo::TCK_SizeAndLatency) ==
13163ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
1317201b191bSHaicheng Wu }
1318201b191bSHaicheng Wu 
13197adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
1320a3a798d4SArthur Eubanks   disableSROA(I.getOperand(0));
1321a3a798d4SArthur Eubanks 
13227adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
13230f153424SSanjay Patel   // alloca and handle that case.
13247adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
13250f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
13260f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1327090c108dSAmara Emerson       // Sometimes a dynamic alloca could be converted into a static alloca
1328090c108dSAmara Emerson       // after this constant prop, and become a huge static alloca on an
1329090c108dSAmara Emerson       // unconditional CFG path. Avoid inlining if this is going to happen above
1330090c108dSAmara Emerson       // a threshold.
1331090c108dSAmara Emerson       // FIXME: If the threshold is removed or lowered too much, we could end up
1332090c108dSAmara Emerson       // being too pessimistic and prevent inlining non-problematic code. This
1333090c108dSAmara Emerson       // could result in unintended perf regressions. A better overall strategy
1334090c108dSAmara Emerson       // is needed to track stack usage during inlining.
13357adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
133622eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
13377b639f50SJacob Hegna           AllocSize->getLimitedValue(),
13387b639f50SJacob Hegna           DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
1339a3a798d4SArthur Eubanks       if (AllocatedSize > InlineConstants::MaxSimplifiedDynamicAllocaToInline)
1340090c108dSAmara Emerson         HasDynamicAlloca = true;
1341090c108dSAmara Emerson       return false;
1342090c108dSAmara Emerson     }
13437adc3a2bSChandler Carruth   }
13447adc3a2bSChandler Carruth 
13457adc3a2bSChandler Carruth   // Accumulate the allocated size.
13467adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
13477adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
13485a956c85SMircea Trofin     AllocatedSize =
13492ccde3c9SCullen Rhodes         SaturatingAdd(DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
13507adc3a2bSChandler Carruth   }
13517adc3a2bSChandler Carruth 
13527adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
13537adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
13547adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
13557adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
1356a3a798d4SArthur Eubanks   if (!I.isStaticAlloca())
13577adc3a2bSChandler Carruth     HasDynamicAlloca = true;
1358a3a798d4SArthur Eubanks 
13597adc3a2bSChandler Carruth   return false;
13607adc3a2bSChandler Carruth }
13617adc3a2bSChandler Carruth 
13627adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
13637adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
13647adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
13657adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
13667adc3a2bSChandler Carruth 
13677adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
136877f32994SBjorn Pettersson   // FIXME: Pointer sizes may differ between different address spaces, so do we
136977f32994SBjorn Pettersson   // need to use correct address space in the call to getPointerSizeInBits here?
137077f32994SBjorn Pettersson   // Or could we skip the getPointerSizeInBits call completely? As far as I can
137177f32994SBjorn Pettersson   // see the ZeroOffset is used as a dummy value, so we can probably use any
137277f32994SBjorn Pettersson   // bit width for the ZeroOffset?
137377f32994SBjorn Pettersson   APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0));
13743739e14aSHaicheng Wu   bool CheckSROA = I.getType()->isPointerTy();
13753739e14aSHaicheng Wu 
13763739e14aSHaicheng Wu   // Track the constant or pointer with constant offset we've seen so far.
13773739e14aSHaicheng Wu   Constant *FirstC = nullptr;
13783739e14aSHaicheng Wu   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
13793739e14aSHaicheng Wu   Value *FirstV = nullptr;
13803739e14aSHaicheng Wu 
13813739e14aSHaicheng Wu   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
13823739e14aSHaicheng Wu     BasicBlock *Pred = I.getIncomingBlock(i);
13833739e14aSHaicheng Wu     // If the incoming block is dead, skip the incoming block.
13843739e14aSHaicheng Wu     if (DeadBlocks.count(Pred))
13853739e14aSHaicheng Wu       continue;
13863739e14aSHaicheng Wu     // If the parent block of phi is not the known successor of the incoming
13873739e14aSHaicheng Wu     // block, skip the incoming block.
13883739e14aSHaicheng Wu     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
13893739e14aSHaicheng Wu     if (KnownSuccessor && KnownSuccessor != I.getParent())
13903739e14aSHaicheng Wu       continue;
13913739e14aSHaicheng Wu 
13923739e14aSHaicheng Wu     Value *V = I.getIncomingValue(i);
13933739e14aSHaicheng Wu     // If the incoming value is this phi itself, skip the incoming value.
13943739e14aSHaicheng Wu     if (&I == V)
13953739e14aSHaicheng Wu       continue;
13963739e14aSHaicheng Wu 
13973739e14aSHaicheng Wu     Constant *C = dyn_cast<Constant>(V);
13983739e14aSHaicheng Wu     if (!C)
13993739e14aSHaicheng Wu       C = SimplifiedValues.lookup(V);
14003739e14aSHaicheng Wu 
14013739e14aSHaicheng Wu     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
14023739e14aSHaicheng Wu     if (!C && CheckSROA)
14033739e14aSHaicheng Wu       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
14043739e14aSHaicheng Wu 
14053739e14aSHaicheng Wu     if (!C && !BaseAndOffset.first)
14063739e14aSHaicheng Wu       // The incoming value is neither a constant nor a pointer with constant
14073739e14aSHaicheng Wu       // offset, exit early.
14083739e14aSHaicheng Wu       return true;
14093739e14aSHaicheng Wu 
14103739e14aSHaicheng Wu     if (FirstC) {
14113739e14aSHaicheng Wu       if (FirstC == C)
14123739e14aSHaicheng Wu         // If we've seen a constant incoming value before and it is the same
14133739e14aSHaicheng Wu         // constant we see this time, continue checking the next incoming value.
14143739e14aSHaicheng Wu         continue;
14153739e14aSHaicheng Wu       // Otherwise early exit because we either see a different constant or saw
14163739e14aSHaicheng Wu       // a constant before but we have a pointer with constant offset this time.
14173739e14aSHaicheng Wu       return true;
14183739e14aSHaicheng Wu     }
14193739e14aSHaicheng Wu 
14203739e14aSHaicheng Wu     if (FirstV) {
14213739e14aSHaicheng Wu       // The same logic as above, but check pointer with constant offset here.
14223739e14aSHaicheng Wu       if (FirstBaseAndOffset == BaseAndOffset)
14233739e14aSHaicheng Wu         continue;
14243739e14aSHaicheng Wu       return true;
14253739e14aSHaicheng Wu     }
14263739e14aSHaicheng Wu 
14273739e14aSHaicheng Wu     if (C) {
14283739e14aSHaicheng Wu       // This is the 1st time we've seen a constant, record it.
14293739e14aSHaicheng Wu       FirstC = C;
14303739e14aSHaicheng Wu       continue;
14313739e14aSHaicheng Wu     }
14323739e14aSHaicheng Wu 
14333739e14aSHaicheng Wu     // The remaining case is that this is the 1st time we've seen a pointer with
14343739e14aSHaicheng Wu     // constant offset, record it.
14353739e14aSHaicheng Wu     FirstV = V;
14363739e14aSHaicheng Wu     FirstBaseAndOffset = BaseAndOffset;
14373739e14aSHaicheng Wu   }
14383739e14aSHaicheng Wu 
14393739e14aSHaicheng Wu   // Check if we can map phi to a constant.
14403739e14aSHaicheng Wu   if (FirstC) {
14413739e14aSHaicheng Wu     SimplifiedValues[&I] = FirstC;
14423739e14aSHaicheng Wu     return true;
14433739e14aSHaicheng Wu   }
14443739e14aSHaicheng Wu 
14453739e14aSHaicheng Wu   // Check if we can map phi to a pointer with constant offset.
14463739e14aSHaicheng Wu   if (FirstBaseAndOffset.first) {
14473739e14aSHaicheng Wu     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
14483739e14aSHaicheng Wu 
144906408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
14503739e14aSHaicheng Wu       SROAArgValues[&I] = SROAArg;
14513739e14aSHaicheng Wu   }
14523739e14aSHaicheng Wu 
14537adc3a2bSChandler Carruth   return true;
14547adc3a2bSChandler Carruth }
14557adc3a2bSChandler Carruth 
14565f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers.
1457d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs.
1458d3558b5dSEvgeny Astigeevich ///
1459d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded.
1460d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1461d3558b5dSEvgeny Astigeevich   // Check if we have a base + offset for the pointer.
1462d3558b5dSEvgeny Astigeevich   std::pair<Value *, APInt> BaseAndOffset =
1463d3558b5dSEvgeny Astigeevich       ConstantOffsetPtrs.lookup(I.getPointerOperand());
1464d3558b5dSEvgeny Astigeevich   if (!BaseAndOffset.first)
1465d3558b5dSEvgeny Astigeevich     return false;
1466d3558b5dSEvgeny Astigeevich 
1467d3558b5dSEvgeny Astigeevich   // Check if the offset of this GEP is constant, and if so accumulate it
1468d3558b5dSEvgeny Astigeevich   // into Offset.
1469d3558b5dSEvgeny Astigeevich   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1470d3558b5dSEvgeny Astigeevich     return false;
1471d3558b5dSEvgeny Astigeevich 
1472d3558b5dSEvgeny Astigeevich   // Add the result as a new mapping to Base + Offset.
1473d3558b5dSEvgeny Astigeevich   ConstantOffsetPtrs[&I] = BaseAndOffset;
1474d3558b5dSEvgeny Astigeevich 
1475d3558b5dSEvgeny Astigeevich   return true;
1476d3558b5dSEvgeny Astigeevich }
1477d3558b5dSEvgeny Astigeevich 
14787adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
147906408758SMircea Trofin   auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
14807adc3a2bSChandler Carruth 
1481a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
1482a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
148391aff1d8SNick Desaulniers     for (const Use &Op : GEP.indices())
148491aff1d8SNick Desaulniers       if (!isa<Constant>(Op) && !SimplifiedValues.lookup(Op))
1485a8b9cdc9SEaswaran Raman         return false;
1486a8b9cdc9SEaswaran Raman     return true;
1487a8b9cdc9SEaswaran Raman   };
1488a8b9cdc9SEaswaran Raman 
1489d48c7859SKirill Naumov   if (!DisableGEPConstOperand)
1490d48c7859SKirill Naumov     if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1491d48c7859SKirill Naumov           SmallVector<Constant *, 2> Indices;
1492d48c7859SKirill Naumov           for (unsigned int Index = 1; Index < COps.size(); ++Index)
1493d48c7859SKirill Naumov             Indices.push_back(COps[Index]);
14947b639f50SJacob Hegna           return ConstantExpr::getGetElementPtr(
14957b639f50SJacob Hegna               I.getSourceElementType(), COps[0], Indices, I.isInBounds());
1496d48c7859SKirill Naumov         }))
1497d48c7859SKirill Naumov       return true;
1498d48c7859SKirill Naumov 
1499d3558b5dSEvgeny Astigeevich   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
150006408758SMircea Trofin     if (SROAArg)
15017adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
15027adc3a2bSChandler Carruth 
15037adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
15047adc3a2bSChandler Carruth     return true;
15057adc3a2bSChandler Carruth   }
15067adc3a2bSChandler Carruth 
15077adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
150806408758SMircea Trofin   if (SROAArg)
150906408758SMircea Trofin     disableSROAForArg(SROAArg);
1510201b191bSHaicheng Wu   return isGEPFree(I);
15117adc3a2bSChandler Carruth }
15127adc3a2bSChandler Carruth 
1513617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
1514617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the
1515617f6364SEaswaran Raman /// instruction when all the operands are constants.
1516617f6364SEaswaran Raman template <typename Callable>
1517617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
1518617f6364SEaswaran Raman   SmallVector<Constant *, 2> COps;
1519617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
1520617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
15217adc3a2bSChandler Carruth     if (!COp)
1522617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
1523617f6364SEaswaran Raman     if (!COp)
1524617f6364SEaswaran Raman       return false;
1525617f6364SEaswaran Raman     COps.push_back(COp);
1526617f6364SEaswaran Raman   }
1527617f6364SEaswaran Raman   auto *C = Evaluate(COps);
1528617f6364SEaswaran Raman   if (!C)
1529617f6364SEaswaran Raman     return false;
15307adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
15317adc3a2bSChandler Carruth   return true;
15327adc3a2bSChandler Carruth }
15337adc3a2bSChandler Carruth 
1534617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1535617f6364SEaswaran Raman   // Propagate constants through bitcasts.
1536617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1537617f6364SEaswaran Raman         return ConstantExpr::getBitCast(COps[0], I.getType());
1538617f6364SEaswaran Raman       }))
1539617f6364SEaswaran Raman     return true;
1540617f6364SEaswaran Raman 
15417adc3a2bSChandler Carruth   // Track base/offsets through casts
1542567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
1543567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
15447adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
15457adc3a2bSChandler Carruth   if (BaseAndOffset.first)
15467adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
15477adc3a2bSChandler Carruth 
15487adc3a2bSChandler Carruth   // Also look for SROA candidates here.
154906408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
15507adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
15517adc3a2bSChandler Carruth 
15527adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
15537adc3a2bSChandler Carruth   return true;
15547adc3a2bSChandler Carruth }
15557adc3a2bSChandler Carruth 
15567adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
15577adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1558617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1559617f6364SEaswaran Raman         return ConstantExpr::getPtrToInt(COps[0], I.getType());
1560617f6364SEaswaran Raman       }))
15617adc3a2bSChandler Carruth     return true;
15627adc3a2bSChandler Carruth 
15637adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
15647adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
15657adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
156677f32994SBjorn Pettersson   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1567faf848acSMikael Holmen   if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1568567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
1569567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
15707adc3a2bSChandler Carruth     if (BaseAndOffset.first)
15717adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
15727adc3a2bSChandler Carruth   }
15737adc3a2bSChandler Carruth 
15747adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
15757adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
15767adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
15777adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
15787adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
15797adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
15807adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
158106408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
15827adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
15837adc3a2bSChandler Carruth 
15843ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
15853ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
15867adc3a2bSChandler Carruth }
15877adc3a2bSChandler Carruth 
15887adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
15897adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1590617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1591617f6364SEaswaran Raman         return ConstantExpr::getIntToPtr(COps[0], I.getType());
1592617f6364SEaswaran Raman       }))
15937adc3a2bSChandler Carruth     return true;
15947adc3a2bSChandler Carruth 
15957adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
15967adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
15977adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
15987adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
159977f32994SBjorn Pettersson   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
16007adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
16017adc3a2bSChandler Carruth     if (BaseAndOffset.first)
16027adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
16037adc3a2bSChandler Carruth   }
16047adc3a2bSChandler Carruth 
16057adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
160606408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(Op))
16077adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
16087adc3a2bSChandler Carruth 
16093ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
16103ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
16117adc3a2bSChandler Carruth }
16127adc3a2bSChandler Carruth 
16137adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
1614ab53c5e5SCraig Topper   // Propagate constants through casts.
1615617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1616617f6364SEaswaran Raman         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
1617617f6364SEaswaran Raman       }))
16187adc3a2bSChandler Carruth     return true;
16197adc3a2bSChandler Carruth 
162010563e16SEric Christopher   // Disable SROA in the face of arbitrary casts we don't explicitly list
162110563e16SEric Christopher   // elsewhere.
16227adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
16237adc3a2bSChandler Carruth 
162439ed9a60SEli Friedman   // If this is a floating-point cast, and the target says this operation
162539ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
162639ed9a60SEli Friedman   // as such.
162739ed9a60SEli Friedman   switch (I.getOpcode()) {
162839ed9a60SEli Friedman   case Instruction::FPTrunc:
162939ed9a60SEli Friedman   case Instruction::FPExt:
163039ed9a60SEli Friedman   case Instruction::UIToFP:
163139ed9a60SEli Friedman   case Instruction::SIToFP:
163239ed9a60SEli Friedman   case Instruction::FPToUI:
163339ed9a60SEli Friedman   case Instruction::FPToSI:
163439ed9a60SEli Friedman     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
163506408758SMircea Trofin       onCallPenalty();
16364dc0b1acSReid Kleckner     break;
163739ed9a60SEli Friedman   default:
163839ed9a60SEli Friedman     break;
163939ed9a60SEli Friedman   }
164039ed9a60SEli Friedman 
16413ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
16423ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
16437adc3a2bSChandler Carruth }
16447adc3a2bSChandler Carruth 
16457adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1646652168a9SFedor Sergeev   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
16477adc3a2bSChandler Carruth }
16487adc3a2bSChandler Carruth 
16497adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
16507adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
16517adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
16527adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
16537adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
16547adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
16557adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
16567adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
16577adc3a2bSChandler Carruth       return true;
16587adc3a2bSChandler Carruth 
16597adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
16607adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
16617adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
16627adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
16637adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
16647adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
16657adc3a2bSChandler Carruth     // SROA firing.
16667adc3a2bSChandler Carruth     return true;
16677adc3a2bSChandler Carruth 
16687adc3a2bSChandler Carruth   return false;
16697adc3a2bSChandler Carruth }
16707adc3a2bSChandler Carruth 
1671652168a9SFedor Sergeev bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
16729a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
16739a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
16749a3fc17aSEaswaran Raman   // unless there is literally zero cost.
16759a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
16769a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
16779a3fc17aSEaswaran Raman   // beneficial :
16789a3fc17aSEaswaran Raman   // main() {
16799a3fc17aSEaswaran Raman   //   hot_call_1();
16809a3fc17aSEaswaran Raman   //   ...
16819a3fc17aSEaswaran Raman   //   hot_call_N()
16829a3fc17aSEaswaran Raman   //   exit(0);
16839a3fc17aSEaswaran Raman   // }
16849a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
16859a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
16869a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
1687652168a9SFedor Sergeev   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
16889a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
16899a3fc17aSEaswaran Raman       return false;
1690652168a9SFedor Sergeev   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
16919a3fc17aSEaswaran Raman     return false;
16929a3fc17aSEaswaran Raman 
16939a3fc17aSEaswaran Raman   return true;
16949a3fc17aSEaswaran Raman }
16959a3fc17aSEaswaran Raman 
169606408758SMircea Trofin bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1697652168a9SFedor Sergeev                                             BlockFrequencyInfo *CallerBFI) {
1698c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
1699c5fa6358SEaswaran Raman   // determined based on that.
1700bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary())
1701ec73ae11SMircea Trofin     return PSI->isColdCallSite(Call, CallerBFI);
1702bba762a1SChandler Carruth 
1703bba762a1SChandler Carruth   // Otherwise we need BFI to be available.
1704c5fa6358SEaswaran Raman   if (!CallerBFI)
1705c5fa6358SEaswaran Raman     return false;
1706c5fa6358SEaswaran Raman 
1707bba762a1SChandler Carruth   // Determine if the callsite is cold relative to caller's entry. We could
1708bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1709bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1710bba762a1SChandler Carruth   // profiles.
1711c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
1712652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1713c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1714c5fa6358SEaswaran Raman   auto CallerEntryFreq =
1715652168a9SFedor Sergeev       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1716c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
1717c5fa6358SEaswaran Raman }
1718c5fa6358SEaswaran Raman 
1719974d4eeaSEaswaran Raman Optional<int>
172006408758SMircea Trofin InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1721974d4eeaSEaswaran Raman                                                 BlockFrequencyInfo *CallerBFI) {
1722bba762a1SChandler Carruth 
1723974d4eeaSEaswaran Raman   // If global profile summary is available, then callsite's hotness is
1724974d4eeaSEaswaran Raman   // determined based on that.
1725ec73ae11SMircea Trofin   if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1726bba762a1SChandler Carruth     return Params.HotCallSiteThreshold;
1727974d4eeaSEaswaran Raman 
1728bba762a1SChandler Carruth   // Otherwise we need BFI to be available and to have a locally hot callsite
1729bba762a1SChandler Carruth   // threshold.
1730bba762a1SChandler Carruth   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1731974d4eeaSEaswaran Raman     return None;
1732974d4eeaSEaswaran Raman 
1733bba762a1SChandler Carruth   // Determine if the callsite is hot relative to caller's entry. We could
1734bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1735bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1736bba762a1SChandler Carruth   // profiles.
1737652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1738974d4eeaSEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
1739974d4eeaSEaswaran Raman   auto CallerEntryFreq = CallerBFI->getEntryFreq();
1740974d4eeaSEaswaran Raman   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
1741bba762a1SChandler Carruth     return Params.LocallyHotCallSiteThreshold;
1742bba762a1SChandler Carruth 
1743bba762a1SChandler Carruth   // Otherwise treat it normally.
1744974d4eeaSEaswaran Raman   return None;
1745974d4eeaSEaswaran Raman }
1746974d4eeaSEaswaran Raman 
174706408758SMircea Trofin void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
17489a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
1749652168a9SFedor Sergeev   if (!allowSizeGrowth(Call)) {
17509a3fc17aSEaswaran Raman     Threshold = 0;
17519a3fc17aSEaswaran Raman     return;
17529a3fc17aSEaswaran Raman   }
17539a3fc17aSEaswaran Raman 
1754652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
17551c57cc2bSEaswaran Raman 
17561c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
17571c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
17581c57cc2bSEaswaran Raman     return B ? std::min(A, B.getValue()) : A;
17591c57cc2bSEaswaran Raman   };
17601c57cc2bSEaswaran Raman 
17610d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
17620d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
17630d58fcacSEaswaran Raman     return B ? std::max(A, B.getValue()) : A;
17640d58fcacSEaswaran Raman   };
17650d58fcacSEaswaran Raman 
176651b809bfSEaswaran Raman   // Various bonus percentages. These are multiplied by Threshold to get the
176751b809bfSEaswaran Raman   // bonus values.
176851b809bfSEaswaran Raman   // SingleBBBonus: This bonus is applied if the callee has a single reachable
176951b809bfSEaswaran Raman   // basic block at the given callsite context. This is speculatively applied
177051b809bfSEaswaran Raman   // and withdrawn if more than one basic block is seen.
177151b809bfSEaswaran Raman   //
177251b809bfSEaswaran Raman   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
177351b809bfSEaswaran Raman   // of the last call to a static function as inlining such functions is
177451b809bfSEaswaran Raman   // guaranteed to reduce code size.
177551b809bfSEaswaran Raman   //
177651b809bfSEaswaran Raman   // These bonus percentages may be set to 0 based on properties of the caller
177751b809bfSEaswaran Raman   // and the callsite.
177851b809bfSEaswaran Raman   int SingleBBBonusPercent = 50;
1779d912a9baSDaniil Fukalov   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
178002647f73SJordan Rupprecht   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
178151b809bfSEaswaran Raman 
178251b809bfSEaswaran Raman   // Lambda to set all the above bonus and bonus percentages to 0.
178351b809bfSEaswaran Raman   auto DisallowAllBonuses = [&]() {
178451b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
178551b809bfSEaswaran Raman     VectorBonusPercent = 0;
178651b809bfSEaswaran Raman     LastCallToStaticBonus = 0;
178751b809bfSEaswaran Raman   };
178851b809bfSEaswaran Raman 
17891c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
17901c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
179185bd3978SEvandro Menezes   if (Caller->hasMinSize()) {
17921c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
179351b809bfSEaswaran Raman     // For minsize, we want to disable the single BB bonus and the vector
179451b809bfSEaswaran Raman     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
179551b809bfSEaswaran Raman     // a static function will, at the minimum, eliminate the parameter setup and
179651b809bfSEaswaran Raman     // call/return instructions.
179751b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
179851b809bfSEaswaran Raman     VectorBonusPercent = 0;
179985bd3978SEvandro Menezes   } else if (Caller->hasOptSize())
18001c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
1801f4bb2f0dSEaswaran Raman 
1802e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
1803e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
180485bd3978SEvandro Menezes   if (!Caller->hasMinSize()) {
1805e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
18060d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1807bba762a1SChandler Carruth 
18083cd1479cSEaswaran Raman     // FIXME: After switching to the new passmanager, simplify the logic below
1809bba762a1SChandler Carruth     // by checking only the callsite hotness/coldness as we will reliably
1810bba762a1SChandler Carruth     // have local profile information.
18113cd1479cSEaswaran Raman     //
1812bba762a1SChandler Carruth     // Callsite hotness and coldness can be determined if sample profile is
1813bba762a1SChandler Carruth     // used (which adds hotness metadata to calls) or if caller's
1814bba762a1SChandler Carruth     // BlockFrequencyInfo is available.
181508e2386dSMircea Trofin     BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
1816652168a9SFedor Sergeev     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
181785bd3978SEvandro Menezes     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
1818d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
1819974d4eeaSEaswaran Raman       // FIXME: This should update the threshold only if it exceeds the
1820974d4eeaSEaswaran Raman       // current threshold, but AutoFDO + ThinLTO currently relies on this
1821974d4eeaSEaswaran Raman       // behavior to prevent inlining of hot callsites during ThinLTO
1822974d4eeaSEaswaran Raman       // compile phase.
1823974d4eeaSEaswaran Raman       Threshold = HotCallSiteThreshold.getValue();
1824652168a9SFedor Sergeev     } else if (isColdCallSite(Call, CallerBFI)) {
1825d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
182651b809bfSEaswaran Raman       // Do not apply bonuses for a cold callsite including the
182751b809bfSEaswaran Raman       // LastCallToStatic bonus. While this bonus might result in code size
182851b809bfSEaswaran Raman       // reduction, it can cause the size of a non-cold caller to increase
182951b809bfSEaswaran Raman       // preventing it from being inlined.
183051b809bfSEaswaran Raman       DisallowAllBonuses();
18313cd1479cSEaswaran Raman       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
1832bba762a1SChandler Carruth     } else if (PSI) {
1833bba762a1SChandler Carruth       // Use callee's global profile information only if we have no way of
1834bba762a1SChandler Carruth       // determining this via callsite information.
18353cd1479cSEaswaran Raman       if (PSI->isFunctionEntryHot(&Callee)) {
1836d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Hot callee.\n");
1837e08b139dSEaswaran Raman         // If callsite hotness can not be determined, we may still know
1838e08b139dSEaswaran Raman         // that the callee is hot and treat it as a weaker hint for threshold
1839e08b139dSEaswaran Raman         // increase.
1840e08b139dSEaswaran Raman         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1841e08b139dSEaswaran Raman       } else if (PSI->isFunctionEntryCold(&Callee)) {
1842d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Cold callee.\n");
184351b809bfSEaswaran Raman         // Do not apply bonuses for a cold callee including the
184451b809bfSEaswaran Raman         // LastCallToStatic bonus. While this bonus might result in code size
184551b809bfSEaswaran Raman         // reduction, it can cause the size of a non-cold caller to increase
184651b809bfSEaswaran Raman         // preventing it from being inlined.
184751b809bfSEaswaran Raman         DisallowAllBonuses();
18481c57cc2bSEaswaran Raman         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
1849e08b139dSEaswaran Raman       }
1850e08b139dSEaswaran Raman     }
1851e08b139dSEaswaran Raman   }
18528650a4daSJustin Lebar 
1853b7b99b07SStanislav Mekhanoshin   Threshold += TTI.adjustInliningThreshold(&Call);
1854b7b99b07SStanislav Mekhanoshin 
185502647f73SJordan Rupprecht   // Finally, take the target-specific inlining threshold multiplier into
185602647f73SJordan Rupprecht   // account.
18578650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
185851b809bfSEaswaran Raman 
185951b809bfSEaswaran Raman   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
186051b809bfSEaswaran Raman   VectorBonus = Threshold * VectorBonusPercent / 100;
186151b809bfSEaswaran Raman 
186202647f73SJordan Rupprecht   bool OnlyOneCallAndLocalLinkage =
186302647f73SJordan Rupprecht       F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction();
186402647f73SJordan Rupprecht   // If there is only one call of the function, and it has internal linkage,
186502647f73SJordan Rupprecht   // the cost of inlining it drops dramatically. It may seem odd to update
186602647f73SJordan Rupprecht   // Cost in updateThreshold, but the bonus depends on the logic in this method.
186702647f73SJordan Rupprecht   if (OnlyOneCallAndLocalLinkage)
186802647f73SJordan Rupprecht     Cost -= LastCallToStaticBonus;
1869f4bb2f0dSEaswaran Raman }
1870f4bb2f0dSEaswaran Raman 
18717adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
18727adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
18737adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
1874617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1875617f6364SEaswaran Raman         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
1876617f6364SEaswaran Raman       }))
18777adc3a2bSChandler Carruth     return true;
18787adc3a2bSChandler Carruth 
18797adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
18807adc3a2bSChandler Carruth     return false;
18817adc3a2bSChandler Carruth 
18827adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
18837adc3a2bSChandler Carruth   // a common base.
18847adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
18857adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
18867adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
18877adc3a2bSChandler Carruth   if (LHSBase) {
18887adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
18897adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
18907adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
18917adc3a2bSChandler Carruth       // offsets.
18927adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
18937adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
18947adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
18957adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
18967adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
18977adc3a2bSChandler Carruth         return true;
18987adc3a2bSChandler Carruth       }
18997adc3a2bSChandler Carruth     }
19007adc3a2bSChandler Carruth   }
19017adc3a2bSChandler Carruth 
19027adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
19037adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
19047adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
19057adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
19067adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
19077adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
19087adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
19097adc3a2bSChandler Carruth     return true;
19107adc3a2bSChandler Carruth   }
191106408758SMircea Trofin   return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
19127adc3a2bSChandler Carruth }
19137adc3a2bSChandler Carruth 
19147adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
19157adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
19167adc3a2bSChandler Carruth   // constant-related pointers.
19177adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
19187adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
19197adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
19207adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
19217adc3a2bSChandler Carruth   if (LHSBase) {
19227adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
19237adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
19247adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
19257adc3a2bSChandler Carruth       // offsets.
19267adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
19277adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
19287adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
19297adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
19307adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
19317adc3a2bSChandler Carruth         return true;
19327adc3a2bSChandler Carruth       }
19337adc3a2bSChandler Carruth     }
19347adc3a2bSChandler Carruth   }
19357adc3a2bSChandler Carruth 
19367adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
19377adc3a2bSChandler Carruth   // instructions.
19387adc3a2bSChandler Carruth   return Base::visitSub(I);
19397adc3a2bSChandler Carruth }
19407adc3a2bSChandler Carruth 
19417adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
19427adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
19436d14dfe8SHaicheng Wu   Constant *CLHS = dyn_cast<Constant>(LHS);
19446d14dfe8SHaicheng Wu   if (!CLHS)
19456d14dfe8SHaicheng Wu     CLHS = SimplifiedValues.lookup(LHS);
19466d14dfe8SHaicheng Wu   Constant *CRHS = dyn_cast<Constant>(RHS);
19476d14dfe8SHaicheng Wu   if (!CRHS)
19486d14dfe8SHaicheng Wu     CRHS = SimplifiedValues.lookup(RHS);
19496d14dfe8SHaicheng Wu 
19507adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
19517adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
19525a956c85SMircea Trofin     SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
19535a956c85SMircea Trofin                             FI->getFastMathFlags(), DL);
19547adc3a2bSChandler Carruth   else
19556d14dfe8SHaicheng Wu     SimpleV =
19566d14dfe8SHaicheng Wu         SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
19577adc3a2bSChandler Carruth 
19586d14dfe8SHaicheng Wu   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
19596d14dfe8SHaicheng Wu     SimplifiedValues[&I] = C;
19606d14dfe8SHaicheng Wu 
19616d14dfe8SHaicheng Wu   if (SimpleV)
19627adc3a2bSChandler Carruth     return true;
19637adc3a2bSChandler Carruth 
19647adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
19657adc3a2bSChandler Carruth   disableSROA(LHS);
19667adc3a2bSChandler Carruth   disableSROA(RHS);
19677adc3a2bSChandler Carruth 
196839ed9a60SEli Friedman   // If the instruction is floating point, and the target says this operation
196939ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
19707cebf0afSCraig Topper   // as such. Unless it's fneg which can be implemented with an xor.
19717cebf0afSCraig Topper   using namespace llvm::PatternMatch;
197239ed9a60SEli Friedman   if (I.getType()->isFloatingPointTy() &&
19737cebf0afSCraig Topper       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
19747cebf0afSCraig Topper       !match(&I, m_FNeg(m_Value())))
197506408758SMircea Trofin     onCallPenalty();
197639ed9a60SEli Friedman 
19777adc3a2bSChandler Carruth   return false;
19787adc3a2bSChandler Carruth }
19797adc3a2bSChandler Carruth 
19806cda33baSCraig Topper bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
19816cda33baSCraig Topper   Value *Op = I.getOperand(0);
19826cda33baSCraig Topper   Constant *COp = dyn_cast<Constant>(Op);
19836cda33baSCraig Topper   if (!COp)
19846cda33baSCraig Topper     COp = SimplifiedValues.lookup(Op);
19856cda33baSCraig Topper 
19865a956c85SMircea Trofin   Value *SimpleV = SimplifyFNegInst(
19875a956c85SMircea Trofin       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
19886cda33baSCraig Topper 
19896cda33baSCraig Topper   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
19906cda33baSCraig Topper     SimplifiedValues[&I] = C;
19916cda33baSCraig Topper 
19926cda33baSCraig Topper   if (SimpleV)
19936cda33baSCraig Topper     return true;
19946cda33baSCraig Topper 
19956cda33baSCraig Topper   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
19966cda33baSCraig Topper   disableSROA(Op);
19976cda33baSCraig Topper 
19986cda33baSCraig Topper   return false;
19996cda33baSCraig Topper }
20006cda33baSCraig Topper 
20017adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
200206408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
20037adc3a2bSChandler Carruth     return true;
20047adc3a2bSChandler Carruth 
2005a4461515SHaicheng Wu   // If the data is already loaded from this address and hasn't been clobbered
2006a4461515SHaicheng Wu   // by any stores or calls, this load is likely to be redundant and can be
2007a4461515SHaicheng Wu   // eliminated.
2008a4461515SHaicheng Wu   if (EnableLoadElimination &&
2009b3689cabSHaicheng Wu       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
201006408758SMircea Trofin     onLoadEliminationOpportunity();
2011a4461515SHaicheng Wu     return true;
2012a4461515SHaicheng Wu   }
2013a4461515SHaicheng Wu 
20147adc3a2bSChandler Carruth   return false;
20157adc3a2bSChandler Carruth }
20167adc3a2bSChandler Carruth 
20177adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
201806408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
20197adc3a2bSChandler Carruth     return true;
20207adc3a2bSChandler Carruth 
2021a4461515SHaicheng Wu   // The store can potentially clobber loads and prevent repeated loads from
2022a4461515SHaicheng Wu   // being eliminated.
2023a4461515SHaicheng Wu   // FIXME:
2024a4461515SHaicheng Wu   // 1. We can probably keep an initial set of eliminatable loads substracted
2025a4461515SHaicheng Wu   // from the cost even when we finally see a store. We just need to disable
2026a4461515SHaicheng Wu   // *further* accumulation of elimination savings.
2027a4461515SHaicheng Wu   // 2. We should probably at some point thread MemorySSA for the callee into
2028a4461515SHaicheng Wu   // this and then use that to actually compute *really* precise savings.
2029a4461515SHaicheng Wu   disableLoadElimination();
20307adc3a2bSChandler Carruth   return false;
20317adc3a2bSChandler Carruth }
20327adc3a2bSChandler Carruth 
20337adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
20347adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
2035617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
2036617f6364SEaswaran Raman         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
2037617f6364SEaswaran Raman       }))
20387adc3a2bSChandler Carruth     return true;
20397adc3a2bSChandler Carruth 
2040ba5b015bSRoman Lebedev   // SROA can't look through these, but they may be free.
2041ba5b015bSRoman Lebedev   return Base::visitExtractValue(I);
20427adc3a2bSChandler Carruth }
20437adc3a2bSChandler Carruth 
20447adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
20457adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
2046617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
2047617f6364SEaswaran Raman         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
2048617f6364SEaswaran Raman                                             /*InsertedValueOperand*/ COps[1],
2049617f6364SEaswaran Raman                                             I.getIndices());
2050617f6364SEaswaran Raman       }))
20517adc3a2bSChandler Carruth     return true;
20527adc3a2bSChandler Carruth 
2053ba5b015bSRoman Lebedev   // SROA can't look through these, but they may be free.
2054ba5b015bSRoman Lebedev   return Base::visitInsertValue(I);
20557adc3a2bSChandler Carruth }
20567adc3a2bSChandler Carruth 
20575f8f34e4SAdrian Prantl /// Try to simplify a call site.
20587adc3a2bSChandler Carruth ///
20597adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
20607adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
20617adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
20627adc3a2bSChandler Carruth /// free.
2063652168a9SFedor Sergeev bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
20647adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
20657adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
20667adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
20677adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
2068652168a9SFedor Sergeev   if (!canConstantFoldCallTo(&Call, F))
20697adc3a2bSChandler Carruth     return false;
20707adc3a2bSChandler Carruth 
20717adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
20727adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
2073652168a9SFedor Sergeev   ConstantArgs.reserve(Call.arg_size());
2074652168a9SFedor Sergeev   for (Value *I : Call.args()) {
2075652168a9SFedor Sergeev     Constant *C = dyn_cast<Constant>(I);
20767adc3a2bSChandler Carruth     if (!C)
2077652168a9SFedor Sergeev       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
20787adc3a2bSChandler Carruth     if (!C)
20797adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
20807adc3a2bSChandler Carruth 
20817adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
20827adc3a2bSChandler Carruth   }
2083652168a9SFedor Sergeev   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2084652168a9SFedor Sergeev     SimplifiedValues[&Call] = C;
20857adc3a2bSChandler Carruth     return true;
20867adc3a2bSChandler Carruth   }
20877adc3a2bSChandler Carruth 
20887adc3a2bSChandler Carruth   return false;
20897adc3a2bSChandler Carruth }
20907adc3a2bSChandler Carruth 
2091652168a9SFedor Sergeev bool CallAnalyzer::visitCallBase(CallBase &Call) {
20925c97507eSDaniil Suchkov   if (!onCallBaseVisitStart(Call))
20935c97507eSDaniil Suchkov     return true;
20945c97507eSDaniil Suchkov 
2095652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
20967adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
20977adc3a2bSChandler Carruth     // This aborts the entire analysis.
20987adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
20997adc3a2bSChandler Carruth     return false;
21007adc3a2bSChandler Carruth   }
2101652168a9SFedor Sergeev   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
21027adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
21037adc3a2bSChandler Carruth 
2104825debe8SEhud Katz   Value *Callee = Call.getCalledOperand();
2105825debe8SEhud Katz   Function *F = dyn_cast_or_null<Function>(Callee);
2106825debe8SEhud Katz   bool IsIndirectCall = !F;
2107825debe8SEhud Katz   if (IsIndirectCall) {
2108825debe8SEhud Katz     // Check if this happens to be an indirect function call to a known function
2109825debe8SEhud Katz     // in this inline context. If not, we've done all we can.
2110825debe8SEhud Katz     F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
2111825debe8SEhud Katz     if (!F) {
211206408758SMircea Trofin       onCallArgumentSetup(Call);
2113825debe8SEhud Katz 
2114825debe8SEhud Katz       if (!Call.onlyReadsMemory())
2115825debe8SEhud Katz         disableLoadElimination();
2116825debe8SEhud Katz       return Base::visitCallBase(Call);
2117825debe8SEhud Katz     }
2118825debe8SEhud Katz   }
2119825debe8SEhud Katz 
2120825debe8SEhud Katz   assert(F && "Expected a call to a known function");
2121825debe8SEhud Katz 
21227adc3a2bSChandler Carruth   // When we have a concrete function, first try to simplify it directly.
2123652168a9SFedor Sergeev   if (simplifyCallSite(F, Call))
21247adc3a2bSChandler Carruth     return true;
21257adc3a2bSChandler Carruth 
21267adc3a2bSChandler Carruth   // Next check if it is an intrinsic we know about.
21277adc3a2bSChandler Carruth   // FIXME: Lift this into part of the InstVisitor.
2128652168a9SFedor Sergeev   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
21297adc3a2bSChandler Carruth     switch (II->getIntrinsicID()) {
21307adc3a2bSChandler Carruth     default:
2131652168a9SFedor Sergeev       if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
2132a4461515SHaicheng Wu         disableLoadElimination();
2133652168a9SFedor Sergeev       return Base::visitCallBase(Call);
21347adc3a2bSChandler Carruth 
21357dd8dbf4SPeter Collingbourne     case Intrinsic::load_relative:
213606408758SMircea Trofin       onLoadRelativeIntrinsic();
21377dd8dbf4SPeter Collingbourne       return false;
21387dd8dbf4SPeter Collingbourne 
21397adc3a2bSChandler Carruth     case Intrinsic::memset:
21407adc3a2bSChandler Carruth     case Intrinsic::memcpy:
21417adc3a2bSChandler Carruth     case Intrinsic::memmove:
2142a4461515SHaicheng Wu       disableLoadElimination();
21437adc3a2bSChandler Carruth       // SROA can usually chew through these intrinsics, but they aren't free.
21447adc3a2bSChandler Carruth       return false;
21454296ea72SVitaly Buka     case Intrinsic::icall_branch_funnel:
21467adc3a2bSChandler Carruth     case Intrinsic::localescape:
21474296ea72SVitaly Buka       HasUninlineableIntrinsic = true;
21487adc3a2bSChandler Carruth       return false;
214980788d80SFlorian Hahn     case Intrinsic::vastart:
215077beee41SSameer AbuAsal       InitsVargArgs = true;
215180788d80SFlorian Hahn       return false;
2152269b335bSArthur Eubanks     case Intrinsic::launder_invariant_group:
2153269b335bSArthur Eubanks     case Intrinsic::strip_invariant_group:
2154269b335bSArthur Eubanks       if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2155269b335bSArthur Eubanks         SROAArgValues[II] = SROAArg;
2156269b335bSArthur Eubanks       return true;
21577adc3a2bSChandler Carruth     }
21587adc3a2bSChandler Carruth   }
21597adc3a2bSChandler Carruth 
2160652168a9SFedor Sergeev   if (F == Call.getFunction()) {
21617adc3a2bSChandler Carruth     // This flag will fully abort the analysis, so don't bother with anything
21627adc3a2bSChandler Carruth     // else.
21637adc3a2bSChandler Carruth     IsRecursiveCall = true;
2164*f7fff46aSWenlei He     if (!AllowRecursiveCall)
21657adc3a2bSChandler Carruth       return false;
21667adc3a2bSChandler Carruth   }
21677adc3a2bSChandler Carruth 
21687adc3a2bSChandler Carruth   if (TTI.isLoweredToCall(F)) {
216906408758SMircea Trofin     onLoweredCall(F, Call, IsIndirectCall);
2170825debe8SEhud Katz   }
21717adc3a2bSChandler Carruth 
2172825debe8SEhud Katz   if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2173a4461515SHaicheng Wu     disableLoadElimination();
2174652168a9SFedor Sergeev   return Base::visitCallBase(Call);
21757adc3a2bSChandler Carruth }
21767adc3a2bSChandler Carruth 
21777adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
21787adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
21797adc3a2bSChandler Carruth   bool Free = !HasReturn;
21807adc3a2bSChandler Carruth   HasReturn = true;
21817adc3a2bSChandler Carruth   return Free;
21827adc3a2bSChandler Carruth }
21837adc3a2bSChandler Carruth 
21847adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
21857adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
21867adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
21877adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
21887adc3a2bSChandler Carruth   // which will fold away are also free.
21897adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
21907adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
21917adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
21927adc3a2bSChandler Carruth }
21937adc3a2bSChandler Carruth 
21943ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
21953ec848bcSHaicheng Wu   bool CheckSROA = SI.getType()->isPointerTy();
21963ec848bcSHaicheng Wu   Value *TrueVal = SI.getTrueValue();
21973ec848bcSHaicheng Wu   Value *FalseVal = SI.getFalseValue();
21983ec848bcSHaicheng Wu 
21993ec848bcSHaicheng Wu   Constant *TrueC = dyn_cast<Constant>(TrueVal);
22003ec848bcSHaicheng Wu   if (!TrueC)
22013ec848bcSHaicheng Wu     TrueC = SimplifiedValues.lookup(TrueVal);
22023ec848bcSHaicheng Wu   Constant *FalseC = dyn_cast<Constant>(FalseVal);
22033ec848bcSHaicheng Wu   if (!FalseC)
22043ec848bcSHaicheng Wu     FalseC = SimplifiedValues.lookup(FalseVal);
22053ec848bcSHaicheng Wu   Constant *CondC =
22063ec848bcSHaicheng Wu       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
22073ec848bcSHaicheng Wu 
22083ec848bcSHaicheng Wu   if (!CondC) {
22093ec848bcSHaicheng Wu     // Select C, X, X => X
22103ec848bcSHaicheng Wu     if (TrueC == FalseC && TrueC) {
22113ec848bcSHaicheng Wu       SimplifiedValues[&SI] = TrueC;
22123ec848bcSHaicheng Wu       return true;
22133ec848bcSHaicheng Wu     }
22143ec848bcSHaicheng Wu 
22153ec848bcSHaicheng Wu     if (!CheckSROA)
22163ec848bcSHaicheng Wu       return Base::visitSelectInst(SI);
22173ec848bcSHaicheng Wu 
22183ec848bcSHaicheng Wu     std::pair<Value *, APInt> TrueBaseAndOffset =
22193ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(TrueVal);
22203ec848bcSHaicheng Wu     std::pair<Value *, APInt> FalseBaseAndOffset =
22213ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(FalseVal);
22223ec848bcSHaicheng Wu     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
22233ec848bcSHaicheng Wu       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
22243ec848bcSHaicheng Wu 
222506408758SMircea Trofin       if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
22263ec848bcSHaicheng Wu         SROAArgValues[&SI] = SROAArg;
22273ec848bcSHaicheng Wu       return true;
22283ec848bcSHaicheng Wu     }
22293ec848bcSHaicheng Wu 
22303ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
22313ec848bcSHaicheng Wu   }
22323ec848bcSHaicheng Wu 
22333ec848bcSHaicheng Wu   // Select condition is a constant.
22347b639f50SJacob Hegna   Value *SelectedV = CondC->isAllOnesValue()  ? TrueVal
22357b639f50SJacob Hegna                      : (CondC->isNullValue()) ? FalseVal
22367b639f50SJacob Hegna                                               : nullptr;
22373ec848bcSHaicheng Wu   if (!SelectedV) {
22383ec848bcSHaicheng Wu     // Condition is a vector constant that is not all 1s or all 0s.  If all
22393ec848bcSHaicheng Wu     // operands are constants, ConstantExpr::getSelect() can handle the cases
22403ec848bcSHaicheng Wu     // such as select vectors.
22413ec848bcSHaicheng Wu     if (TrueC && FalseC) {
22423ec848bcSHaicheng Wu       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
22433ec848bcSHaicheng Wu         SimplifiedValues[&SI] = C;
22443ec848bcSHaicheng Wu         return true;
22453ec848bcSHaicheng Wu       }
22463ec848bcSHaicheng Wu     }
22473ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
22483ec848bcSHaicheng Wu   }
22493ec848bcSHaicheng Wu 
22503ec848bcSHaicheng Wu   // Condition is either all 1s or all 0s. SI can be simplified.
22513ec848bcSHaicheng Wu   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
22523ec848bcSHaicheng Wu     SimplifiedValues[&SI] = SelectedC;
22533ec848bcSHaicheng Wu     return true;
22543ec848bcSHaicheng Wu   }
22553ec848bcSHaicheng Wu 
22563ec848bcSHaicheng Wu   if (!CheckSROA)
22573ec848bcSHaicheng Wu     return true;
22583ec848bcSHaicheng Wu 
22593ec848bcSHaicheng Wu   std::pair<Value *, APInt> BaseAndOffset =
22603ec848bcSHaicheng Wu       ConstantOffsetPtrs.lookup(SelectedV);
22613ec848bcSHaicheng Wu   if (BaseAndOffset.first) {
22623ec848bcSHaicheng Wu     ConstantOffsetPtrs[&SI] = BaseAndOffset;
22633ec848bcSHaicheng Wu 
226406408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
22653ec848bcSHaicheng Wu       SROAArgValues[&SI] = SROAArg;
22663ec848bcSHaicheng Wu   }
22673ec848bcSHaicheng Wu 
22683ec848bcSHaicheng Wu   return true;
22693ec848bcSHaicheng Wu }
22703ec848bcSHaicheng Wu 
22717adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
22727adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
22737adc3a2bSChandler Carruth   // branches.
22747adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
22757adc3a2bSChandler Carruth     return true;
22767adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
22777adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
22787adc3a2bSChandler Carruth       return true;
22797adc3a2bSChandler Carruth 
22807ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
2281919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
2282919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
2283919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
2284919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
2285919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
22862960d41eSJun Bum Lim   //
22872960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
2288472462c4SBjorn Pettersson   // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
22892960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
22902960d41eSJun Bum Lim   // does not (yet) fire.
2291919f9e8dSJun Bum Lim 
2292919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
229308e2386dSMircea Trofin   BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2294919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
22950d987e41SHiroshi Yamauchi       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2296919f9e8dSJun Bum Lim 
229706408758SMircea Trofin   onFinalizeSwitch(JumpTableSize, NumCaseCluster);
2298919f9e8dSJun Bum Lim   return false;
2299919f9e8dSJun Bum Lim }
2300919f9e8dSJun Bum Lim 
23017adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
23027adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
23037adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
23047adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
23057adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
23067adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
23077adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
23087adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
23097adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
23107adc3a2bSChandler Carruth   HasIndirectBr = true;
23117adc3a2bSChandler Carruth   return false;
23127adc3a2bSChandler Carruth }
23137adc3a2bSChandler Carruth 
23147adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
23157adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
23167adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
23177adc3a2bSChandler Carruth   return false;
23187adc3a2bSChandler Carruth }
23197adc3a2bSChandler Carruth 
23207adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
23217adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
23227adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
23237adc3a2bSChandler Carruth   return false;
23247adc3a2bSChandler Carruth }
23257adc3a2bSChandler Carruth 
23267adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
23277adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
23288220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
23297adc3a2bSChandler Carruth   return false;
23307adc3a2bSChandler Carruth }
23317adc3a2bSChandler Carruth 
23327adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
23337adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
23347adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
23357adc3a2bSChandler Carruth   // code size.
23367adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
23377adc3a2bSChandler Carruth }
23387adc3a2bSChandler Carruth 
23397adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
23407adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
23417adc3a2bSChandler Carruth   // handled by SROA, etc.
23423ccbd4f3SSander de Smalen   if (TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
23433ccbd4f3SSander de Smalen       TargetTransformInfo::TCC_Free)
23447adc3a2bSChandler Carruth     return true;
23457adc3a2bSChandler Carruth 
23467adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
23477adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
234891aff1d8SNick Desaulniers   for (const Use &Op : I.operands())
234991aff1d8SNick Desaulniers     disableSROA(Op);
23507adc3a2bSChandler Carruth 
23517adc3a2bSChandler Carruth   return false;
23527adc3a2bSChandler Carruth }
23537adc3a2bSChandler Carruth 
23545f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost.
23557adc3a2bSChandler Carruth ///
23567adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
23577adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
23587adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
23597adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
23607adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
2361c0aa4b75SDavid Bolvansky InlineResult
2362c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB,
23637adc3a2bSChandler Carruth                            SmallPtrSetImpl<const Value *> &EphValues) {
236491aff1d8SNick Desaulniers   for (Instruction &I : *BB) {
23657adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
23667adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
23677adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
23687adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
23697adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
23707adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
23717adc3a2bSChandler Carruth     // hack around it here.
23727adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
23737adc3a2bSChandler Carruth       continue;
23747adc3a2bSChandler Carruth 
2375f3c44569SHongtao Yu     // Skip pseudo-probes.
2376f3c44569SHongtao Yu     if (isa<PseudoProbeInst>(I))
2377f3c44569SHongtao Yu       continue;
2378f3c44569SHongtao Yu 
23797adc3a2bSChandler Carruth     // Skip ephemeral values.
238091aff1d8SNick Desaulniers     if (EphValues.count(&I))
23817adc3a2bSChandler Carruth       continue;
23827adc3a2bSChandler Carruth 
23837adc3a2bSChandler Carruth     ++NumInstructions;
238491aff1d8SNick Desaulniers     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
23857adc3a2bSChandler Carruth       ++NumVectorInstructions;
23867adc3a2bSChandler Carruth 
23877adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
23887adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
23897adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
23907adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
23917adc3a2bSChandler Carruth     // cost should count against inlining.
239291aff1d8SNick Desaulniers     onInstructionAnalysisStart(&I);
2393c965fd94SKirill Naumov 
239491aff1d8SNick Desaulniers     if (Base::visit(&I))
23957adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
23967adc3a2bSChandler Carruth     else
239714a16faeSMircea Trofin       onMissedSimplification();
23987adc3a2bSChandler Carruth 
239991aff1d8SNick Desaulniers     onInstructionAnalysisFinish(&I);
24000812c5beSHaicheng Wu     using namespace ore;
24017adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
24025466597fSMircea Trofin     InlineResult IR = InlineResult::success();
2403*f7fff46aSWenlei He     if (IsRecursiveCall && !AllowRecursiveCall)
24045466597fSMircea Trofin       IR = InlineResult::failure("recursive");
2405c0aa4b75SDavid Bolvansky     else if (ExposesReturnsTwice)
24065466597fSMircea Trofin       IR = InlineResult::failure("exposes returns twice");
2407c0aa4b75SDavid Bolvansky     else if (HasDynamicAlloca)
24085466597fSMircea Trofin       IR = InlineResult::failure("dynamic alloca");
2409c0aa4b75SDavid Bolvansky     else if (HasIndirectBr)
24105466597fSMircea Trofin       IR = InlineResult::failure("indirect branch");
2411c0aa4b75SDavid Bolvansky     else if (HasUninlineableIntrinsic)
24125466597fSMircea Trofin       IR = InlineResult::failure("uninlinable intrinsic");
241377beee41SSameer AbuAsal     else if (InitsVargArgs)
24145466597fSMircea Trofin       IR = InlineResult::failure("varargs");
24155466597fSMircea Trofin     if (!IR.isSuccess()) {
24160812c5beSHaicheng Wu       if (ORE)
24179590658fSVivek Pandya         ORE->emit([&]() {
24189590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2419652168a9SFedor Sergeev                                           &CandidateCall)
2420c0aa4b75SDavid Bolvansky                  << NV("Callee", &F) << " has uninlinable pattern ("
24215466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2422c0aa4b75SDavid Bolvansky                  << ") and cost is not fully computed";
24239590658fSVivek Pandya         });
2424c0aa4b75SDavid Bolvansky       return IR;
24250812c5beSHaicheng Wu     }
24267adc3a2bSChandler Carruth 
24277adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
24287adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
24297adc3a2bSChandler Carruth     // the caller stack usage dramatically.
24307adc3a2bSChandler Carruth     if (IsCallerRecursive &&
24310812c5beSHaicheng Wu         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
24325466597fSMircea Trofin       auto IR =
24335466597fSMircea Trofin           InlineResult::failure("recursive and allocates too much stack space");
24340812c5beSHaicheng Wu       if (ORE)
24359590658fSVivek Pandya         ORE->emit([&]() {
24369590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2437652168a9SFedor Sergeev                                           &CandidateCall)
24385466597fSMircea Trofin                  << NV("Callee", &F) << " is "
24395466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2440c0aa4b75SDavid Bolvansky                  << ". Cost is not fully computed";
24419590658fSVivek Pandya         });
2442c0aa4b75SDavid Bolvansky       return IR;
24430812c5beSHaicheng Wu     }
24447adc3a2bSChandler Carruth 
244506408758SMircea Trofin     if (shouldStop())
24465466597fSMircea Trofin       return InlineResult::failure(
24475466597fSMircea Trofin           "Call site analysis is not favorable to inlining.");
24487adc3a2bSChandler Carruth   }
24497adc3a2bSChandler Carruth 
24505466597fSMircea Trofin   return InlineResult::success();
24517adc3a2bSChandler Carruth }
24527adc3a2bSChandler Carruth 
24535f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V.
24547adc3a2bSChandler Carruth ///
24557adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
24567adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
24577adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
24587adc3a2bSChandler Carruth /// no constant offsets applied.
24597adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
24607adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
24617adc3a2bSChandler Carruth     return nullptr;
24627adc3a2bSChandler Carruth 
246377f32994SBjorn Pettersson   unsigned AS = V->getType()->getPointerAddressSpace();
2464945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
24657adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
24667adc3a2bSChandler Carruth 
24677adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
24687adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
24697adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
24707adc3a2bSChandler Carruth   Visited.insert(V);
24717adc3a2bSChandler Carruth   do {
24727adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
24737adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
24747adc3a2bSChandler Carruth         return nullptr;
24757adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
24767adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
24777adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
24787adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
24795ce32728SSanjoy Das       if (GA->isInterposable())
24807adc3a2bSChandler Carruth         break;
24817adc3a2bSChandler Carruth       V = GA->getAliasee();
24827adc3a2bSChandler Carruth     } else {
24837adc3a2bSChandler Carruth       break;
24847adc3a2bSChandler Carruth     }
24857adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
24867adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
24877adc3a2bSChandler Carruth 
248897572775SNicola Zaghen   Type *IdxPtrTy = DL.getIndexType(V->getType());
248997572775SNicola Zaghen   return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
24907adc3a2bSChandler Carruth }
24917adc3a2bSChandler Carruth 
24925f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining.
24933739e14aSHaicheng Wu ///
24943739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p
24953739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have
24963739e14aSHaicheng Wu /// no live incoming CFG edges.  If one block is found to be dead, we can
24973739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead
24983739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not.
24993739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
25003739e14aSHaicheng Wu   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
250102a2bb2fSHiroshi Inoue     // A CFG edge is dead if the predecessor is dead or the predecessor has a
25023739e14aSHaicheng Wu     // known successor which is not the one under exam.
25033739e14aSHaicheng Wu     return (DeadBlocks.count(Pred) ||
25043739e14aSHaicheng Wu             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
25053739e14aSHaicheng Wu   };
25063739e14aSHaicheng Wu 
25073739e14aSHaicheng Wu   auto IsNewlyDead = [&](BasicBlock *BB) {
25083739e14aSHaicheng Wu     // If all the edges to a block are dead, the block is also dead.
25093739e14aSHaicheng Wu     return (!DeadBlocks.count(BB) &&
25103739e14aSHaicheng Wu             llvm::all_of(predecessors(BB),
25113739e14aSHaicheng Wu                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
25123739e14aSHaicheng Wu   };
25133739e14aSHaicheng Wu 
25143739e14aSHaicheng Wu   for (BasicBlock *Succ : successors(CurrBB)) {
25153739e14aSHaicheng Wu     if (Succ == NextBB || !IsNewlyDead(Succ))
25163739e14aSHaicheng Wu       continue;
25173739e14aSHaicheng Wu     SmallVector<BasicBlock *, 4> NewDead;
25183739e14aSHaicheng Wu     NewDead.push_back(Succ);
25193739e14aSHaicheng Wu     while (!NewDead.empty()) {
25203739e14aSHaicheng Wu       BasicBlock *Dead = NewDead.pop_back_val();
25213739e14aSHaicheng Wu       if (DeadBlocks.insert(Dead))
25223739e14aSHaicheng Wu         // Continue growing the dead block lists.
25233739e14aSHaicheng Wu         for (BasicBlock *S : successors(Dead))
25243739e14aSHaicheng Wu           if (IsNewlyDead(S))
25253739e14aSHaicheng Wu             NewDead.push_back(S);
25263739e14aSHaicheng Wu     }
25273739e14aSHaicheng Wu   }
25283739e14aSHaicheng Wu }
25293739e14aSHaicheng Wu 
25305f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining.
25317adc3a2bSChandler Carruth ///
25327adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
25337adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
25347adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
25357adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
25367adc3a2bSChandler Carruth /// some artifact of the routine.
253793ac81ccSMircea Trofin InlineResult CallAnalyzer::analyze() {
25387adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
25397adc3a2bSChandler Carruth 
254006408758SMircea Trofin   auto Result = onAnalysisStart();
25415466597fSMircea Trofin   if (!Result.isSuccess())
254206408758SMircea Trofin     return Result;
25437adc3a2bSChandler Carruth 
25447adc3a2bSChandler Carruth   if (F.empty())
25455466597fSMircea Trofin     return InlineResult::success();
25467adc3a2bSChandler Carruth 
254793ac81ccSMircea Trofin   Function *Caller = CandidateCall.getFunction();
25487adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
25497adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
2550652168a9SFedor Sergeev     CallBase *Call = dyn_cast<CallBase>(U);
2551652168a9SFedor Sergeev     if (Call && Call->getFunction() == Caller) {
25527adc3a2bSChandler Carruth       IsCallerRecursive = true;
25537adc3a2bSChandler Carruth       break;
25547adc3a2bSChandler Carruth     }
25557adc3a2bSChandler Carruth   }
25567adc3a2bSChandler Carruth 
25577adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
25587adc3a2bSChandler Carruth   // arguments with known important simplifications.
255993ac81ccSMircea Trofin   auto CAI = CandidateCall.arg_begin();
256091aff1d8SNick Desaulniers   for (Argument &FAI : F.args()) {
256193ac81ccSMircea Trofin     assert(CAI != CandidateCall.arg_end());
25627adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
256391aff1d8SNick Desaulniers       SimplifiedValues[&FAI] = C;
25647adc3a2bSChandler Carruth 
25657adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
25667adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
256791aff1d8SNick Desaulniers       ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
25687adc3a2bSChandler Carruth 
25697adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
257006408758SMircea Trofin       if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
257191aff1d8SNick Desaulniers         SROAArgValues[&FAI] = SROAArg;
257206408758SMircea Trofin         onInitializeSROAArg(SROAArg);
25732e42cc7aSMircea Trofin         EnabledSROAAllocas.insert(SROAArg);
25747adc3a2bSChandler Carruth       }
25757adc3a2bSChandler Carruth     }
257691aff1d8SNick Desaulniers     ++CAI;
25777adc3a2bSChandler Carruth   }
25787adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
25797adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
25807adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
25817adc3a2bSChandler Carruth 
25827adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
25837adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
25847adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
25857adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
2586aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
25877adc3a2bSChandler Carruth 
25887adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
25897adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
25907adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
25917adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
25927adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
25937adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
25947adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
25957adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
2596567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
2597567556aaSChad Rosier       BBSetVector;
25987adc3a2bSChandler Carruth   BBSetVector BBWorklist;
25997adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
260006408758SMircea Trofin 
26017adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
26027adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
260306408758SMircea Trofin     if (shouldStop())
26047adc3a2bSChandler Carruth       break;
26057adc3a2bSChandler Carruth 
26067adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
26077adc3a2bSChandler Carruth     if (BB->empty())
26087adc3a2bSChandler Carruth       continue;
26097adc3a2bSChandler Carruth 
26109895c701SKazu Hirata     onBlockStart(BB);
26119895c701SKazu Hirata 
2612639b29b1SNick Desaulniers     // Disallow inlining a blockaddress with uses other than strictly callbr.
2613639b29b1SNick Desaulniers     // A blockaddress only has defined behavior for an indirect branch in the
2614639b29b1SNick Desaulniers     // same function, and we do not currently support inlining indirect
2615639b29b1SNick Desaulniers     // branches.  But, the inliner may not see an indirect branch that ends up
2616639b29b1SNick Desaulniers     // being dead code at a particular call site. If the blockaddress escapes
2617639b29b1SNick Desaulniers     // the function, e.g., via a global variable, inlining may lead to an
2618639b29b1SNick Desaulniers     // invalid cross-function reference.
2619639b29b1SNick Desaulniers     // FIXME: pr/39560: continue relaxing this overt restriction.
26206a84cd3bSNick Desaulniers     if (BB->hasAddressTaken())
2621639b29b1SNick Desaulniers       for (User *U : BlockAddress::get(&*BB)->users())
2622639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
26235466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
26247adc3a2bSChandler Carruth 
26257adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
26267adc3a2bSChandler Carruth     // returns false, and we can bail on out.
2627c0aa4b75SDavid Bolvansky     InlineResult IR = analyzeBlock(BB, EphValues);
26285466597fSMircea Trofin     if (!IR.isSuccess())
2629c0aa4b75SDavid Bolvansky       return IR;
26307adc3a2bSChandler Carruth 
2631edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
26327adc3a2bSChandler Carruth 
26337adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
26347adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
26357adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
26367adc3a2bSChandler Carruth       if (BI->isConditional()) {
26377adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
2638567556aaSChad Rosier         if (ConstantInt *SimpleCond =
2639567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
26403739e14aSHaicheng Wu           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
26413739e14aSHaicheng Wu           BBWorklist.insert(NextBB);
26423739e14aSHaicheng Wu           KnownSuccessors[BB] = NextBB;
26433739e14aSHaicheng Wu           findDeadBlocks(BB, NextBB);
26447adc3a2bSChandler Carruth           continue;
26457adc3a2bSChandler Carruth         }
26467adc3a2bSChandler Carruth       }
26477adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
26487adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
2649567556aaSChad Rosier       if (ConstantInt *SimpleCond =
2650567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
26513739e14aSHaicheng Wu         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
26523739e14aSHaicheng Wu         BBWorklist.insert(NextBB);
26533739e14aSHaicheng Wu         KnownSuccessors[BB] = NextBB;
26543739e14aSHaicheng Wu         findDeadBlocks(BB, NextBB);
26557adc3a2bSChandler Carruth         continue;
26567adc3a2bSChandler Carruth       }
26577adc3a2bSChandler Carruth     }
26587adc3a2bSChandler Carruth 
26597adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
26607adc3a2bSChandler Carruth     // them.
26617adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
26627adc3a2bSChandler Carruth          ++TIdx)
26637adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
26647adc3a2bSChandler Carruth 
266506408758SMircea Trofin     onBlockAnalyzed(BB);
26667adc3a2bSChandler Carruth   }
26677adc3a2bSChandler Carruth 
266893ac81ccSMircea Trofin   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
266993ac81ccSMircea Trofin                                     &F == CandidateCall.getCalledFunction();
26707adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
26717adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
26727adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
26737adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
26745466597fSMircea Trofin     return InlineResult::failure("noduplicate");
26757adc3a2bSChandler Carruth 
267606408758SMircea Trofin   return finalizeAnalysis();
26777adc3a2bSChandler Carruth }
26787adc3a2bSChandler Carruth 
2679ca899bf9SKirill Naumov void InlineCostCallAnalyzer::print() {
26807adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
26811022b5ebSKirill Naumov   if (PrintInstructionComments)
2682c965fd94SKirill Naumov     F.print(dbgs(), &Writer);
26837adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
26847adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
26857adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
26867adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
26877adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
26887adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
26897adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
26907adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
26917adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
2692a4461515SHaicheng Wu   DEBUG_PRINT_STAT(LoadEliminationCost);
26937adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
26947adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
26957adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
26967adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
26977adc3a2bSChandler Carruth }
2698ca899bf9SKirill Naumov 
2699ca899bf9SKirill Naumov #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2700ca899bf9SKirill Naumov /// Dump stats about this call's analysis.
27017b639f50SJacob Hegna LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(); }
27027adc3a2bSChandler Carruth #endif
27037adc3a2bSChandler Carruth 
27045f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee
27057adc3a2bSChandler Carruth ///        that prevent inlining.
2706f9ca75f1STeresa Johnson static bool functionsHaveCompatibleAttributes(
2707f9ca75f1STeresa Johnson     Function *Caller, Function *Callee, TargetTransformInfo &TTI,
2708f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
2709f9ca75f1STeresa Johnson   // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
2710f9ca75f1STeresa Johnson   // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
2711f9ca75f1STeresa Johnson   // object, and always returns the same object (which is overwritten on each
2712f9ca75f1STeresa Johnson   // GetTLI call). Therefore we copy the first result.
2713f9ca75f1STeresa Johnson   auto CalleeTLI = GetTLI(*Callee);
27147adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
2715f9ca75f1STeresa Johnson          GetTLI(*Caller).areInlineCompatible(CalleeTLI,
2716ed03d948SMehdi Amini                                              InlineCallerSupersetNoBuiltin) &&
27171cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
27187adc3a2bSChandler Carruth }
27197adc3a2bSChandler Carruth 
2720652168a9SFedor Sergeev int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
2721351d9b01SXinliang David Li   int Cost = 0;
2722652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
2723652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2724351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
2725351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
2726652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
272707a9df59SArthur Eubanks       unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
272877f32994SBjorn Pettersson       unsigned AS = PTy->getAddressSpace();
272977f32994SBjorn Pettersson       unsigned PointerSize = DL.getPointerSizeInBits(AS);
2730351d9b01SXinliang David Li       // Ceiling division.
2731351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2732351d9b01SXinliang David Li 
2733351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
2734351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
2735351d9b01SXinliang David Li       // one load and one store per word copied.
2736351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
2737351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
2738351d9b01SXinliang David Li       // DataLayout.
2739351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
2740351d9b01SXinliang David Li 
2741351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
2742351d9b01SXinliang David Li     } else {
2743351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
2744351d9b01SXinliang David Li       // argument.
2745351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
2746351d9b01SXinliang David Li     }
2747351d9b01SXinliang David Li   }
2748351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
274946c03668SPhilipp Krones   Cost += InlineConstants::InstrCost + CallPenalty;
2750351d9b01SXinliang David Li   return Cost;
2751351d9b01SXinliang David Li }
2752351d9b01SXinliang David Li 
2753ab6a6837SSean Silva InlineCost llvm::getInlineCost(
2754652168a9SFedor Sergeev     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
275508e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2756f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
275708e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
27580812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2759652168a9SFedor Sergeev   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
276008e2386dSMircea Trofin                        GetAssumptionCache, GetTLI, GetBFI, PSI, ORE);
2761b9f7120eSEaswaran Raman }
2762b9f7120eSEaswaran Raman 
2763011a07c0SMircea Trofin Optional<int> llvm::getInliningCostEstimate(
27648a4013edSMircea Trofin     CallBase &Call, TargetTransformInfo &CalleeTTI,
276508e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
276608e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
27678a4013edSMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
27688a4013edSMircea Trofin   const InlineParams Params = {/* DefaultThreshold*/ 0,
27698a4013edSMircea Trofin                                /*HintThreshold*/ {},
27708a4013edSMircea Trofin                                /*ColdThreshold*/ {},
27718a4013edSMircea Trofin                                /*OptSizeThreshold*/ {},
27728a4013edSMircea Trofin                                /*OptMinSizeThreshold*/ {},
27738a4013edSMircea Trofin                                /*HotCallSiteThreshold*/ {},
27748a4013edSMircea Trofin                                /*LocallyHotCallSiteThreshold*/ {},
27758a4013edSMircea Trofin                                /*ColdCallSiteThreshold*/ {},
2776347a599eSKazu Hirata                                /*ComputeFullInlineCost*/ true,
2777347a599eSKazu Hirata                                /*EnableDeferral*/ true};
27788a4013edSMircea Trofin 
277908e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
278008e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE, true,
27818a4013edSMircea Trofin                             /*IgnoreThreshold*/ true);
27828a4013edSMircea Trofin   auto R = CA.analyze();
27838a4013edSMircea Trofin   if (!R.isSuccess())
27848a4013edSMircea Trofin     return None;
27858a4013edSMircea Trofin   return CA.getCost();
27868a4013edSMircea Trofin }
27878a4013edSMircea Trofin 
278899f00635SJacob Hegna Optional<InlineCostFeatures> llvm::getInliningCostFeatures(
278999f00635SJacob Hegna     CallBase &Call, TargetTransformInfo &CalleeTTI,
279099f00635SJacob Hegna     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
279199f00635SJacob Hegna     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
279299f00635SJacob Hegna     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
279399f00635SJacob Hegna   InlineCostFeaturesAnalyzer CFA(CalleeTTI, GetAssumptionCache, GetBFI, PSI,
279499f00635SJacob Hegna                                  ORE, *Call.getCalledFunction(), Call);
279599f00635SJacob Hegna   auto R = CFA.analyze();
279699f00635SJacob Hegna   if (!R.isSuccess())
279799f00635SJacob Hegna     return None;
279899f00635SJacob Hegna   return CFA.features();
279999f00635SJacob Hegna }
280099f00635SJacob Hegna 
2801201498c6SMircea Trofin Optional<InlineResult> llvm::getAttributeBasedInliningDecision(
2802201498c6SMircea Trofin     CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
2803201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
2804f4bb2f0dSEaswaran Raman 
28057adc3a2bSChandler Carruth   // Cannot inline indirect calls.
28067adc3a2bSChandler Carruth   if (!Callee)
2807201498c6SMircea Trofin     return InlineResult::failure("indirect call");
28087adc3a2bSChandler Carruth 
280931e60b91SXun Li   // When callee coroutine function is inlined into caller coroutine function
281031e60b91SXun Li   // before coro-split pass,
281131e60b91SXun Li   // coro-early pass can not handle this quiet well.
281231e60b91SXun Li   // So we won't inline the coroutine function if it have not been unsplited
281331e60b91SXun Li   if (Callee->isPresplitCoroutine())
281431e60b91SXun Li     return InlineResult::failure("unsplited coroutine call");
281531e60b91SXun Li 
28163851496eSBjorn Pettersson   // Never inline calls with byval arguments that does not have the alloca
28173851496eSBjorn Pettersson   // address space. Since byval arguments can be replaced with a copy to an
28183851496eSBjorn Pettersson   // alloca, the inlined code would need to be adjusted to handle that the
28193851496eSBjorn Pettersson   // argument is in the alloca address space (so it is a little bit complicated
28203851496eSBjorn Pettersson   // to solve).
28213851496eSBjorn Pettersson   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2822652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2823652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2824652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
28253851496eSBjorn Pettersson       if (PTy->getAddressSpace() != AllocaAS)
2826201498c6SMircea Trofin         return InlineResult::failure("byval arguments without alloca"
2827c0aa4b75SDavid Bolvansky                                      " address space");
28283851496eSBjorn Pettersson     }
28293851496eSBjorn Pettersson 
28307adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
28317adc3a2bSChandler Carruth   // whenever possible.
2832652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
283315b17d0aSYevgeny Rouban     auto IsViable = isInlineViable(*Callee);
28345466597fSMircea Trofin     if (IsViable.isSuccess())
2835201498c6SMircea Trofin       return InlineResult::success();
2836201498c6SMircea Trofin     return InlineResult::failure(IsViable.getFailureReason());
28377adc3a2bSChandler Carruth   }
28387adc3a2bSChandler Carruth 
28397adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
28407adc3a2bSChandler Carruth   // always-inline attribute).
2841652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
2842f9ca75f1STeresa Johnson   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI, GetTLI))
2843201498c6SMircea Trofin     return InlineResult::failure("conflicting attributes");
28447adc3a2bSChandler Carruth 
28457adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
284685bd3978SEvandro Menezes   if (Caller->hasOptNone())
2847201498c6SMircea Trofin     return InlineResult::failure("optnone attribute");
28487adc3a2bSChandler Carruth 
284977eeac3dSManoj Gupta   // Don't inline a function that treats null pointer as valid into a caller
285077eeac3dSManoj Gupta   // that does not have this attribute.
285177eeac3dSManoj Gupta   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2852201498c6SMircea Trofin     return InlineResult::failure("nullptr definitions incompatible");
285377eeac3dSManoj Gupta 
2854c0aa4b75SDavid Bolvansky   // Don't inline functions which can be interposed at link-time.
2855c0aa4b75SDavid Bolvansky   if (Callee->isInterposable())
2856201498c6SMircea Trofin     return InlineResult::failure("interposable");
2857c0aa4b75SDavid Bolvansky 
2858c0aa4b75SDavid Bolvansky   // Don't inline functions marked noinline.
2859c0aa4b75SDavid Bolvansky   if (Callee->hasFnAttribute(Attribute::NoInline))
2860201498c6SMircea Trofin     return InlineResult::failure("noinline function attribute");
2861c0aa4b75SDavid Bolvansky 
2862c0aa4b75SDavid Bolvansky   // Don't inline call sites marked noinline.
2863652168a9SFedor Sergeev   if (Call.isNoInline())
2864201498c6SMircea Trofin     return InlineResult::failure("noinline call site attribute");
2865201498c6SMircea Trofin 
2866bc044a88SNick Desaulniers   // Don't inline functions if one does not have any stack protector attribute
2867bc044a88SNick Desaulniers   // but the other does.
2868bc044a88SNick Desaulniers   if (Caller->hasStackProtectorFnAttr() && !Callee->hasStackProtectorFnAttr())
2869bc044a88SNick Desaulniers     return InlineResult::failure(
2870bc044a88SNick Desaulniers         "stack protected caller but callee requested no stack protector");
2871bc044a88SNick Desaulniers   if (Callee->hasStackProtectorFnAttr() && !Caller->hasStackProtectorFnAttr())
2872bc044a88SNick Desaulniers     return InlineResult::failure(
2873bc044a88SNick Desaulniers         "stack protected callee but caller requested no stack protector");
2874bc044a88SNick Desaulniers 
2875201498c6SMircea Trofin   return None;
2876201498c6SMircea Trofin }
2877201498c6SMircea Trofin 
2878201498c6SMircea Trofin InlineCost llvm::getInlineCost(
2879201498c6SMircea Trofin     CallBase &Call, Function *Callee, const InlineParams &Params,
2880201498c6SMircea Trofin     TargetTransformInfo &CalleeTTI,
288108e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2882201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
288308e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2884201498c6SMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2885201498c6SMircea Trofin 
2886201498c6SMircea Trofin   auto UserDecision =
2887201498c6SMircea Trofin       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
2888201498c6SMircea Trofin 
2889201498c6SMircea Trofin   if (UserDecision.hasValue()) {
2890201498c6SMircea Trofin     if (UserDecision->isSuccess())
2891201498c6SMircea Trofin       return llvm::InlineCost::getAlways("always inline attribute");
2892201498c6SMircea Trofin     return llvm::InlineCost::getNever(UserDecision->getFailureReason());
2893201498c6SMircea Trofin   }
28947adc3a2bSChandler Carruth 
2895d34e60caSNicola Zaghen   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
2896201498c6SMircea Trofin                           << "... (caller:" << Call.getCaller()->getName()
2897201498c6SMircea Trofin                           << ")\n");
28987adc3a2bSChandler Carruth 
289908e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
290008e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE);
290193ac81ccSMircea Trofin   InlineResult ShouldInline = CA.analyze();
29027adc3a2bSChandler Carruth 
2903d34e60caSNicola Zaghen   LLVM_DEBUG(CA.dump());
29047adc3a2bSChandler Carruth 
29056869e6c1SWenlei He   // Always make cost benefit based decision explicit.
29066869e6c1SWenlei He   // We use always/never here since threshold is not meaningful,
29076869e6c1SWenlei He   // as it's not what drives cost-benefit analysis.
29086869e6c1SWenlei He   if (CA.wasDecidedByCostBenefit()) {
29096869e6c1SWenlei He     if (ShouldInline.isSuccess())
29104bdfea2cSLiqiang Tao       return InlineCost::getAlways("benefit over cost",
29114bdfea2cSLiqiang Tao                                    CA.getCostBenefitPair());
29126869e6c1SWenlei He     else
29134bdfea2cSLiqiang Tao       return InlineCost::getNever("cost over benefit", CA.getCostBenefitPair());
29146869e6c1SWenlei He   }
29156869e6c1SWenlei He 
29167adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
29175466597fSMircea Trofin   if (!ShouldInline.isSuccess() && CA.getCost() < CA.getThreshold())
29185466597fSMircea Trofin     return InlineCost::getNever(ShouldInline.getFailureReason());
29195466597fSMircea Trofin   if (ShouldInline.isSuccess() && CA.getCost() >= CA.getThreshold())
2920c0aa4b75SDavid Bolvansky     return InlineCost::getAlways("empty function");
29217adc3a2bSChandler Carruth 
29227adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
29237adc3a2bSChandler Carruth }
29247adc3a2bSChandler Carruth 
292515b17d0aSYevgeny Rouban InlineResult llvm::isInlineViable(Function &F) {
29267adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
292791aff1d8SNick Desaulniers   for (BasicBlock &BB : F) {
2928639b29b1SNick Desaulniers     // Disallow inlining of functions which contain indirect branches.
292991aff1d8SNick Desaulniers     if (isa<IndirectBrInst>(BB.getTerminator()))
29305466597fSMircea Trofin       return InlineResult::failure("contains indirect branches");
293115b17d0aSYevgeny Rouban 
2932639b29b1SNick Desaulniers     // Disallow inlining of blockaddresses which are used by non-callbr
2933639b29b1SNick Desaulniers     // instructions.
293491aff1d8SNick Desaulniers     if (BB.hasAddressTaken())
293591aff1d8SNick Desaulniers       for (User *U : BlockAddress::get(&BB)->users())
2936639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
29375466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
29387adc3a2bSChandler Carruth 
293991aff1d8SNick Desaulniers     for (auto &II : BB) {
2940652168a9SFedor Sergeev       CallBase *Call = dyn_cast<CallBase>(&II);
2941652168a9SFedor Sergeev       if (!Call)
29427adc3a2bSChandler Carruth         continue;
29437adc3a2bSChandler Carruth 
29447adc3a2bSChandler Carruth       // Disallow recursive calls.
2945bc044a88SNick Desaulniers       Function *Callee = Call->getCalledFunction();
2946bc044a88SNick Desaulniers       if (&F == Callee)
29475466597fSMircea Trofin         return InlineResult::failure("recursive call");
29487adc3a2bSChandler Carruth 
29497adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
29507adc3a2bSChandler Carruth       // attributed as such.
2951652168a9SFedor Sergeev       if (!ReturnsTwice && isa<CallInst>(Call) &&
2952652168a9SFedor Sergeev           cast<CallInst>(Call)->canReturnTwice())
29535466597fSMircea Trofin         return InlineResult::failure("exposes returns-twice attribute");
29547adc3a2bSChandler Carruth 
2955bc044a88SNick Desaulniers       if (Callee)
2956bc044a88SNick Desaulniers         switch (Callee->getIntrinsicID()) {
29571636651eSFlorian Hahn         default:
29581636651eSFlorian Hahn           break;
295906408758SMircea Trofin         case llvm::Intrinsic::icall_branch_funnel:
29604296ea72SVitaly Buka           // Disallow inlining of @llvm.icall.branch.funnel because current
29614296ea72SVitaly Buka           // backend can't separate call targets from call arguments.
29625466597fSMircea Trofin           return InlineResult::failure(
29635466597fSMircea Trofin               "disallowed inlining of @llvm.icall.branch.funnel");
296406408758SMircea Trofin         case llvm::Intrinsic::localescape:
29657adc3a2bSChandler Carruth           // Disallow inlining functions that call @llvm.localescape. Doing this
29667adc3a2bSChandler Carruth           // correctly would require major changes to the inliner.
29675466597fSMircea Trofin           return InlineResult::failure(
29685466597fSMircea Trofin               "disallowed inlining of @llvm.localescape");
29691636651eSFlorian Hahn         case llvm::Intrinsic::vastart:
297006408758SMircea Trofin           // Disallow inlining of functions that initialize VarArgs with
297106408758SMircea Trofin           // va_start.
29725466597fSMircea Trofin           return InlineResult::failure(
29735466597fSMircea Trofin               "contains VarArgs initialized with va_start");
29747adc3a2bSChandler Carruth         }
29757adc3a2bSChandler Carruth     }
29761636651eSFlorian Hahn   }
29777adc3a2bSChandler Carruth 
29785466597fSMircea Trofin   return InlineResult::success();
29797adc3a2bSChandler Carruth }
29801c57cc2bSEaswaran Raman 
29811c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
29821c57cc2bSEaswaran Raman // parameters.
29831c57cc2bSEaswaran Raman 
29841c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
29851c57cc2bSEaswaran Raman   InlineParams Params;
29861c57cc2bSEaswaran Raman 
29871c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
29881c57cc2bSEaswaran Raman   // derived from one or more of:
29891c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
29901c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
29911c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
29921c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
29931c57cc2bSEaswaran Raman   //  irrespective of anything else.
29941c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
29951c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
29961c57cc2bSEaswaran Raman   else
29971c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
29981c57cc2bSEaswaran Raman 
29991c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
30001c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
30011c57cc2bSEaswaran Raman 
30021c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
30031c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
30041c57cc2bSEaswaran Raman 
3005974d4eeaSEaswaran Raman   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
3006974d4eeaSEaswaran Raman   // populate LocallyHotCallSiteThreshold. Later, we populate
3007974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
3008974d4eeaSEaswaran Raman   // we know that optimization level is O3 (in the getInlineParams variant that
3009974d4eeaSEaswaran Raman   // takes the opt and size levels).
3010974d4eeaSEaswaran Raman   // FIXME: Remove this check (and make the assignment unconditional) after
3011974d4eeaSEaswaran Raman   // addressing size regression issues at O2.
3012974d4eeaSEaswaran Raman   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
3013974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
3014974d4eeaSEaswaran Raman 
30155a956c85SMircea Trofin   // Set the ColdCallSiteThreshold knob from the
30165a956c85SMircea Trofin   // -inline-cold-callsite-threshold.
301712585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
301812585b01SEaswaran Raman 
30191c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
30201c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
30211c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
30221c57cc2bSEaswaran Raman   // minsize attributes.
30231c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
30241c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
30251c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
30261c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
30271c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
30281c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
30291c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
30301c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
30311c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
30321c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
30331c57cc2bSEaswaran Raman   }
30341c57cc2bSEaswaran Raman   return Params;
30351c57cc2bSEaswaran Raman }
30361c57cc2bSEaswaran Raman 
30371c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
30387f37a802STeresa Johnson   return getInlineParams(DefaultThreshold);
30391c57cc2bSEaswaran Raman }
30401c57cc2bSEaswaran Raman 
30411c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
30421c57cc2bSEaswaran Raman // size opt level.
30431c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
30441c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
30451c57cc2bSEaswaran Raman   if (OptLevel > 2)
30461c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
30471c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
30481c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
30491c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
30501c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
30517f37a802STeresa Johnson   return DefaultThreshold;
30521c57cc2bSEaswaran Raman }
30531c57cc2bSEaswaran Raman 
30541c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
3055974d4eeaSEaswaran Raman   auto Params =
3056974d4eeaSEaswaran Raman       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
3057974d4eeaSEaswaran Raman   // At O3, use the value of -locally-hot-callsite-threshold option to populate
3058974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
3059974d4eeaSEaswaran Raman   // when it is specified explicitly.
3060974d4eeaSEaswaran Raman   if (OptLevel > 2)
3061974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
3062974d4eeaSEaswaran Raman   return Params;
30631c57cc2bSEaswaran Raman }
30646a5d7d49SKirill Naumov 
30656a5d7d49SKirill Naumov PreservedAnalyses
30666a5d7d49SKirill Naumov InlineCostAnnotationPrinterPass::run(Function &F,
30676a5d7d49SKirill Naumov                                      FunctionAnalysisManager &FAM) {
30686a5d7d49SKirill Naumov   PrintInstructionComments = true;
30697b639f50SJacob Hegna   std::function<AssumptionCache &(Function &)> GetAssumptionCache =
30707b639f50SJacob Hegna       [&](Function &F) -> AssumptionCache & {
30716a5d7d49SKirill Naumov     return FAM.getResult<AssumptionAnalysis>(F);
30726a5d7d49SKirill Naumov   };
30736a5d7d49SKirill Naumov   Module *M = F.getParent();
30746a5d7d49SKirill Naumov   ProfileSummaryInfo PSI(*M);
30756a5d7d49SKirill Naumov   DataLayout DL(M);
30766a5d7d49SKirill Naumov   TargetTransformInfo TTI(DL);
30776a5d7d49SKirill Naumov   // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
30786a5d7d49SKirill Naumov   // In the current implementation, the type of InlineParams doesn't matter as
30796a5d7d49SKirill Naumov   // the pass serves only for verification of inliner's decisions.
30806a5d7d49SKirill Naumov   // We can add a flag which determines InlineParams for this run. Right now,
30816a5d7d49SKirill Naumov   // the default InlineParams are used.
30826a5d7d49SKirill Naumov   const InlineParams Params = llvm::getInlineParams();
30836a5d7d49SKirill Naumov   for (BasicBlock &BB : F) {
30846a5d7d49SKirill Naumov     for (Instruction &I : BB) {
30856a5d7d49SKirill Naumov       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
30866a5d7d49SKirill Naumov         Function *CalledFunction = CI->getCalledFunction();
30876a5d7d49SKirill Naumov         if (!CalledFunction || CalledFunction->isDeclaration())
30886a5d7d49SKirill Naumov           continue;
30896a5d7d49SKirill Naumov         OptimizationRemarkEmitter ORE(CalledFunction);
30906a5d7d49SKirill Naumov         InlineCostCallAnalyzer ICCA(*CalledFunction, *CI, Params, TTI,
30916a5d7d49SKirill Naumov                                     GetAssumptionCache, nullptr, &PSI, &ORE);
30926a5d7d49SKirill Naumov         ICCA.analyze();
30936a5d7d49SKirill Naumov         OS << "      Analyzing call of " << CalledFunction->getName()
30946a5d7d49SKirill Naumov            << "... (caller:" << CI->getCaller()->getName() << ")\n";
30956a5d7d49SKirill Naumov         ICCA.print();
30966a5d7d49SKirill Naumov       }
30976a5d7d49SKirill Naumov     }
30986a5d7d49SKirill Naumov   }
30996a5d7d49SKirill Naumov   return PreservedAnalyses::all();
31006a5d7d49SKirill Naumov }
3101