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"
217adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
227adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h"
237adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
24ba9f245bSDavid Green #include "llvm/Analysis/LoopInfo.h"
2571c3a551Sserge-sans-paille #include "llvm/Analysis/OptimizationRemarkEmitter.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"
45c50e6f59SWolfgang Pieb #include <limits>
467adc3a2bSChandler Carruth 
477adc3a2bSChandler Carruth using namespace llvm;
487adc3a2bSChandler Carruth 
497adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost"
507adc3a2bSChandler Carruth 
517adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
527adc3a2bSChandler Carruth 
537f37a802STeresa Johnson static cl::opt<int>
547f37a802STeresa Johnson     DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225),
557f37a802STeresa Johnson                      cl::desc("Default amount of inlining to perform"));
567f37a802STeresa Johnson 
57a4aa97d5SAnna Thomas // We introduce this option since there is a minor compile-time win by avoiding
58a4aa97d5SAnna Thomas // addition of TTI attributes (target-features in particular) to inline
59a4aa97d5SAnna Thomas // candidates when they are guaranteed to be the same as top level methods in
60a4aa97d5SAnna Thomas // some use cases. If we avoid adding the attribute, we need an option to avoid
61a4aa97d5SAnna Thomas // checking these attributes.
62a4aa97d5SAnna Thomas static cl::opt<bool> IgnoreTTIInlineCompatible(
63a4aa97d5SAnna Thomas     "ignore-tti-inline-compatible", cl::Hidden, cl::init(false),
64a4aa97d5SAnna Thomas     cl::desc("Ignore TTI attributes compatibility check between callee/caller "
65a4aa97d5SAnna Thomas              "during inline cost calculation"));
66a4aa97d5SAnna Thomas 
671022b5ebSKirill Naumov static cl::opt<bool> PrintInstructionComments(
681022b5ebSKirill Naumov     "print-instruction-comments", cl::Hidden, cl::init(false),
691022b5ebSKirill Naumov     cl::desc("Prints comments for instruction based on inline cost analysis"));
70c965fd94SKirill Naumov 
711c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold(
72557efc9aSFangrui Song     "inline-threshold", cl::Hidden, cl::init(225),
73f4bb2f0dSEaswaran Raman     cl::desc("Control the amount of inlining to perform (default = 225)"));
74f4bb2f0dSEaswaran Raman 
75f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold(
76557efc9aSFangrui Song     "inlinehint-threshold", cl::Hidden, cl::init(325),
77f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with inline hint"));
78f4bb2f0dSEaswaran Raman 
7912585b01SEaswaran Raman static cl::opt<int>
8012585b01SEaswaran Raman     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
8136c7d79dSFangrui Song                           cl::init(45),
8212585b01SEaswaran Raman                           cl::desc("Threshold for inlining cold callsites"));
8312585b01SEaswaran Raman 
849895c701SKazu Hirata static cl::opt<bool> InlineEnableCostBenefitAnalysis(
859895c701SKazu Hirata     "inline-enable-cost-benefit-analysis", cl::Hidden, cl::init(false),
869895c701SKazu Hirata     cl::desc("Enable the cost-benefit analysis for the inliner"));
879895c701SKazu Hirata 
889895c701SKazu Hirata static cl::opt<int> InlineSavingsMultiplier(
89557efc9aSFangrui Song     "inline-savings-multiplier", cl::Hidden, cl::init(8),
909895c701SKazu Hirata     cl::desc("Multiplier to multiply cycle savings by during inlining"));
919895c701SKazu Hirata 
929895c701SKazu Hirata static cl::opt<int>
939895c701SKazu Hirata     InlineSizeAllowance("inline-size-allowance", cl::Hidden, cl::init(100),
949895c701SKazu Hirata                         cl::desc("The maximum size of a callee that get's "
959895c701SKazu Hirata                                  "inlined without sufficient cycle savings"));
969895c701SKazu Hirata 
97f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based
98f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and
99f4bb2f0dSEaswaran Raman // BFI.
100f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold(
101557efc9aSFangrui Song     "inlinecold-threshold", cl::Hidden, cl::init(45),
102f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with cold attribute"));
103f4bb2f0dSEaswaran Raman 
104de39cb93SDehao Chen static cl::opt<int>
105de39cb93SDehao Chen     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
106de39cb93SDehao Chen                          cl::desc("Threshold for hot callsites "));
107de39cb93SDehao Chen 
108974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold(
109557efc9aSFangrui Song     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525),
110974d4eeaSEaswaran Raman     cl::desc("Threshold for locally hot callsites "));
111974d4eeaSEaswaran Raman 
112c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq(
113557efc9aSFangrui Song     "cold-callsite-rel-freq", cl::Hidden, cl::init(2),
11402a2bb2fSHiroshi Inoue     cl::desc("Maximum block frequency, expressed as a percentage of caller's "
115c5fa6358SEaswaran Raman              "entry frequency, for a callsite to be cold in the absence of "
116c5fa6358SEaswaran Raman              "profile information."));
117c5fa6358SEaswaran Raman 
118974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq(
119557efc9aSFangrui Song     "hot-callsite-rel-freq", cl::Hidden, cl::init(60),
120ff77cc75SEaswaran Raman     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
121974d4eeaSEaswaran Raman              "entry frequency, for a callsite to be hot in the absence of "
122974d4eeaSEaswaran Raman              "profile information."));
123974d4eeaSEaswaran Raman 
12446c03668SPhilipp Krones static cl::opt<int> CallPenalty(
12546c03668SPhilipp Krones     "inline-call-penalty", cl::Hidden, cl::init(25),
12646c03668SPhilipp Krones     cl::desc("Call penalty that is applied per callsite when inlining"));
12746c03668SPhilipp Krones 
128c50e6f59SWolfgang Pieb static cl::opt<size_t>
129c50e6f59SWolfgang Pieb     StackSizeThreshold("inline-max-stacksize", cl::Hidden,
130c50e6f59SWolfgang Pieb                        cl::init(std::numeric_limits<size_t>::max()),
131c50e6f59SWolfgang Pieb                        cl::desc("Do not inline functions with a stack size "
132c50e6f59SWolfgang Pieb                                 "that exceeds the specified limit"));
133c50e6f59SWolfgang Pieb 
134a78f436cSWenlei He static cl::opt<size_t>
135a78f436cSWenlei He     RecurStackSizeThreshold("recursive-inline-max-stacksize", cl::Hidden,
136a78f436cSWenlei He                        cl::init(InlineConstants::TotalAllocaSizeRecursiveCaller),
137a78f436cSWenlei He                        cl::desc("Do not inline recursive functions with a stack "
138a78f436cSWenlei He                                 "size that exceeds the specified limit"));
139a78f436cSWenlei He 
1404924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost(
141557efc9aSFangrui Song     "inline-cost-full", cl::Hidden,
1420812c5beSHaicheng Wu     cl::desc("Compute the full inline cost of a call site even when the cost "
1430812c5beSHaicheng Wu              "exceeds the threshold."));
1440812c5beSHaicheng Wu 
145ed03d948SMehdi Amini static cl::opt<bool> InlineCallerSupersetNoBuiltin(
146ed03d948SMehdi Amini     "inline-caller-superset-nobuiltin", cl::Hidden, cl::init(true),
147ed03d948SMehdi Amini     cl::desc("Allow inlining when caller has a superset of callee's nobuiltin "
148f9ca75f1STeresa Johnson              "attributes."));
149f9ca75f1STeresa Johnson 
150d48c7859SKirill Naumov static cl::opt<bool> DisableGEPConstOperand(
151d48c7859SKirill Naumov     "disable-gep-const-evaluation", cl::Hidden, cl::init(false),
152d48c7859SKirill Naumov     cl::desc("Disables evaluation of GetElementPtr with constant operands"));
153d48c7859SKirill Naumov 
15453e5e586SArthur Eubanks namespace llvm {
getStringFnAttrAsInt(CallBase & CB,StringRef AttrKind)1555c97507eSDaniil Suchkov Optional<int> getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind) {
156e90bce8fSAugie Fackler   Attribute Attr = CB.getFnAttr(AttrKind);
1575c97507eSDaniil Suchkov   int AttrValue;
1585c97507eSDaniil Suchkov   if (Attr.getValueAsString().getAsInteger(10, AttrValue))
1595c97507eSDaniil Suchkov     return None;
1605c97507eSDaniil Suchkov   return AttrValue;
1615c97507eSDaniil Suchkov }
16253e5e586SArthur Eubanks } // namespace llvm
16353e5e586SArthur Eubanks 
16453e5e586SArthur Eubanks namespace {
16553e5e586SArthur Eubanks class InlineCostCallAnalyzer;
1665c97507eSDaniil Suchkov 
167c965fd94SKirill Naumov // This struct is used to store information about inline cost of a
168c965fd94SKirill Naumov // particular instruction
169c965fd94SKirill Naumov struct InstructionCostDetail {
170b4924f01SMircea Trofin   int CostBefore = 0;
171b4924f01SMircea Trofin   int CostAfter = 0;
172b4924f01SMircea Trofin   int ThresholdBefore = 0;
173b4924f01SMircea Trofin   int ThresholdAfter = 0;
174b4924f01SMircea Trofin 
getThresholdDelta__anon9893a50b0111::InstructionCostDetail175b4924f01SMircea Trofin   int getThresholdDelta() const { return ThresholdAfter - ThresholdBefore; }
176b4924f01SMircea Trofin 
getCostDelta__anon9893a50b0111::InstructionCostDetail177b4924f01SMircea Trofin   int getCostDelta() const { return CostAfter - CostBefore; }
178b4924f01SMircea Trofin 
hasThresholdChanged__anon9893a50b0111::InstructionCostDetail179b4924f01SMircea Trofin   bool hasThresholdChanged() const { return ThresholdAfter != ThresholdBefore; }
180c965fd94SKirill Naumov };
181c965fd94SKirill Naumov 
1821022b5ebSKirill Naumov class InlineCostAnnotationWriter : public AssemblyAnnotationWriter {
1831022b5ebSKirill Naumov private:
1841022b5ebSKirill Naumov   InlineCostCallAnalyzer *const ICCA;
185c965fd94SKirill Naumov 
1861022b5ebSKirill Naumov public:
InlineCostAnnotationWriter(InlineCostCallAnalyzer * ICCA)1871022b5ebSKirill Naumov   InlineCostAnnotationWriter(InlineCostCallAnalyzer *ICCA) : ICCA(ICCA) {}
188*b5188591SKazu Hirata   void emitInstructionAnnot(const Instruction *I,
1891022b5ebSKirill Naumov                             formatted_raw_ostream &OS) override;
190c965fd94SKirill Naumov };
191c965fd94SKirill Naumov 
19208e2386dSMircea Trofin /// Carry out call site analysis, in order to evaluate inlinability.
19308e2386dSMircea Trofin /// NOTE: the type is currently used as implementation detail of functions such
19408e2386dSMircea Trofin /// as llvm::getInlineCost. Note the function_ref constructor parameters - the
19508e2386dSMircea Trofin /// expectation is that they come from the outer scope, from the wrapper
19608e2386dSMircea Trofin /// functions. If we want to support constructing CallAnalyzer objects where
19708e2386dSMircea Trofin /// lambdas are provided inline at construction, or where the object needs to
19808e2386dSMircea Trofin /// otherwise survive past the scope of the provided functions, we need to
19908e2386dSMircea Trofin /// revisit the argument types.
2007adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
2017adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
2027adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
2037adc3a2bSChandler Carruth 
20406408758SMircea Trofin protected:
2053a3cb929SKazu Hirata   virtual ~CallAnalyzer() = default;
2067adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
2077adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
2087adc3a2bSChandler Carruth 
209aec2fa35SDaniel Jasper   /// Getter for the cache of @llvm.assume intrinsics.
21008e2386dSMircea Trofin   function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
211aec2fa35SDaniel Jasper 
21212585b01SEaswaran Raman   /// Getter for BlockFrequencyInfo
21308e2386dSMircea Trofin   function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
21412585b01SEaswaran Raman 
21571069cf6SEaswaran Raman   /// Profile summary information.
21671069cf6SEaswaran Raman   ProfileSummaryInfo *PSI;
21771069cf6SEaswaran Raman 
218f3d122cdSPiotr Padlewski   /// The called function.
2197adc3a2bSChandler Carruth   Function &F;
2207adc3a2bSChandler Carruth 
22185be8ca8SEric Christopher   // Cache the DataLayout since we use it a lot.
22285be8ca8SEric Christopher   const DataLayout &DL;
22385be8ca8SEric Christopher 
2240812c5beSHaicheng Wu   /// The OptimizationRemarkEmitter available for this compilation.
2250812c5beSHaicheng Wu   OptimizationRemarkEmitter *ORE;
2260812c5beSHaicheng Wu 
227f3d122cdSPiotr Padlewski   /// The candidate callsite being analyzed. Please do not use this to do
228f3d122cdSPiotr Padlewski   /// analysis in the caller function; we want the inline cost query to be
229f3d122cdSPiotr Padlewski   /// easily cacheable. Instead, use the cover function paramHasAttr.
230652168a9SFedor Sergeev   CallBase &CandidateCall;
2317adc3a2bSChandler Carruth 
23206408758SMircea Trofin   /// Extension points for handling callsite features.
2339895c701SKazu Hirata   // Called before a basic block was analyzed.
onBlockStart(const BasicBlock * BB)2349895c701SKazu Hirata   virtual void onBlockStart(const BasicBlock *BB) {}
2359895c701SKazu Hirata 
23606408758SMircea Trofin   /// Called after a basic block was analyzed.
onBlockAnalyzed(const BasicBlock * BB)23706408758SMircea Trofin   virtual void onBlockAnalyzed(const BasicBlock *BB) {}
2381c57cc2bSEaswaran Raman 
239c965fd94SKirill Naumov   /// Called before an instruction was analyzed
onInstructionAnalysisStart(const Instruction * I)240c965fd94SKirill Naumov   virtual void onInstructionAnalysisStart(const Instruction *I) {}
241c965fd94SKirill Naumov 
242c965fd94SKirill Naumov   /// Called after an instruction was analyzed
onInstructionAnalysisFinish(const Instruction * I)243c965fd94SKirill Naumov   virtual void onInstructionAnalysisFinish(const Instruction *I) {}
244c965fd94SKirill Naumov 
24506408758SMircea Trofin   /// Called at the end of the analysis of the callsite. Return the outcome of
24606408758SMircea Trofin   /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
24706408758SMircea Trofin   /// the reason it can't.
finalizeAnalysis()2485466597fSMircea Trofin   virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
24906408758SMircea Trofin   /// Called when we're about to start processing a basic block, and every time
25006408758SMircea Trofin   /// we are done processing an instruction. Return true if there is no point in
25106408758SMircea Trofin   /// continuing the analysis (e.g. we've determined already the call site is
25206408758SMircea Trofin   /// too expensive to inline)
shouldStop()25306408758SMircea Trofin   virtual bool shouldStop() { return false; }
254eeae45dcSFedor Sergeev 
25506408758SMircea Trofin   /// Called before the analysis of the callee body starts (with callsite
25606408758SMircea Trofin   /// contexts propagated).  It checks callsite-specific information. Return a
25706408758SMircea Trofin   /// reason analysis can't continue if that's the case, or 'true' if it may
25806408758SMircea Trofin   /// continue.
onAnalysisStart()2595466597fSMircea Trofin   virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
26006408758SMircea Trofin   /// Called if the analysis engine decides SROA cannot be done for the given
26106408758SMircea Trofin   /// alloca.
onDisableSROA(AllocaInst * Arg)26206408758SMircea Trofin   virtual void onDisableSROA(AllocaInst *Arg) {}
26306408758SMircea Trofin 
26406408758SMircea Trofin   /// Called the analysis engine determines load elimination won't happen.
onDisableLoadElimination()26506408758SMircea Trofin   virtual void onDisableLoadElimination() {}
26606408758SMircea Trofin 
2675c97507eSDaniil Suchkov   /// Called when we visit a CallBase, before the analysis starts. Return false
2685c97507eSDaniil Suchkov   /// to stop further processing of the instruction.
onCallBaseVisitStart(CallBase & Call)2695c97507eSDaniil Suchkov   virtual bool onCallBaseVisitStart(CallBase &Call) { return true; }
2705c97507eSDaniil Suchkov 
27106408758SMircea Trofin   /// Called to account for a call.
onCallPenalty()27206408758SMircea Trofin   virtual void onCallPenalty() {}
27306408758SMircea Trofin 
27406408758SMircea Trofin   /// Called to account for the expectation the inlining would result in a load
27506408758SMircea Trofin   /// elimination.
onLoadEliminationOpportunity()27606408758SMircea Trofin   virtual void onLoadEliminationOpportunity() {}
27706408758SMircea Trofin 
27806408758SMircea Trofin   /// Called to account for the cost of argument setup for the Call in the
27906408758SMircea Trofin   /// callee's body (not the callsite currently under analysis).
onCallArgumentSetup(const CallBase & Call)28006408758SMircea Trofin   virtual void onCallArgumentSetup(const CallBase &Call) {}
28106408758SMircea Trofin 
28206408758SMircea Trofin   /// Called to account for a load relative intrinsic.
onLoadRelativeIntrinsic()28306408758SMircea Trofin   virtual void onLoadRelativeIntrinsic() {}
28406408758SMircea Trofin 
28506408758SMircea Trofin   /// Called to account for a lowered call.
onLoweredCall(Function * F,CallBase & Call,bool IsIndirectCall)28606408758SMircea Trofin   virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
28706408758SMircea Trofin   }
28806408758SMircea Trofin 
28906408758SMircea Trofin   /// Account for a jump table of given size. Return false to stop further
29006408758SMircea Trofin   /// processing the switch instruction
onJumpTable(unsigned JumpTableSize)29106408758SMircea Trofin   virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
29206408758SMircea Trofin 
29306408758SMircea Trofin   /// Account for a case cluster of given size. Return false to stop further
29406408758SMircea Trofin   /// processing of the instruction.
onCaseCluster(unsigned NumCaseCluster)29506408758SMircea Trofin   virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
29606408758SMircea Trofin 
29706408758SMircea Trofin   /// Called at the end of processing a switch instruction, with the given
29806408758SMircea Trofin   /// number of case clusters.
onFinalizeSwitch(unsigned JumpTableSize,unsigned NumCaseCluster)29906408758SMircea Trofin   virtual void onFinalizeSwitch(unsigned JumpTableSize,
30006408758SMircea Trofin                                 unsigned NumCaseCluster) {}
30106408758SMircea Trofin 
30206408758SMircea Trofin   /// Called to account for any other instruction not specifically accounted
30306408758SMircea Trofin   /// for.
onMissedSimplification()30414a16faeSMircea Trofin   virtual void onMissedSimplification() {}
30506408758SMircea Trofin 
30606408758SMircea Trofin   /// Start accounting potential benefits due to SROA for the given alloca.
onInitializeSROAArg(AllocaInst * Arg)30706408758SMircea Trofin   virtual void onInitializeSROAArg(AllocaInst *Arg) {}
30806408758SMircea Trofin 
30906408758SMircea Trofin   /// Account SROA savings for the AllocaInst value.
onAggregateSROAUse(AllocaInst * V)31006408758SMircea Trofin   virtual void onAggregateSROAUse(AllocaInst *V) {}
31106408758SMircea Trofin 
handleSROA(Value * V,bool DoNotDisable)31206408758SMircea Trofin   bool handleSROA(Value *V, bool DoNotDisable) {
31306408758SMircea Trofin     // Check for SROA candidates in comparisons.
31406408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
31506408758SMircea Trofin       if (DoNotDisable) {
31606408758SMircea Trofin         onAggregateSROAUse(SROAArg);
31706408758SMircea Trofin         return true;
31806408758SMircea Trofin       }
31906408758SMircea Trofin       disableSROAForArg(SROAArg);
32006408758SMircea Trofin     }
32106408758SMircea Trofin     return false;
32206408758SMircea Trofin   }
3237adc3a2bSChandler Carruth 
324eeae45dcSFedor Sergeev   bool IsCallerRecursive = false;
325eeae45dcSFedor Sergeev   bool IsRecursiveCall = false;
326eeae45dcSFedor Sergeev   bool ExposesReturnsTwice = false;
327eeae45dcSFedor Sergeev   bool HasDynamicAlloca = false;
328eeae45dcSFedor Sergeev   bool ContainsNoDuplicateCall = false;
329eeae45dcSFedor Sergeev   bool HasReturn = false;
330eeae45dcSFedor Sergeev   bool HasIndirectBr = false;
331eeae45dcSFedor Sergeev   bool HasUninlineableIntrinsic = false;
332eeae45dcSFedor Sergeev   bool InitsVargArgs = false;
3337adc3a2bSChandler Carruth 
3347adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
335eeae45dcSFedor Sergeev   uint64_t AllocatedSize = 0;
336eeae45dcSFedor Sergeev   unsigned NumInstructions = 0;
337eeae45dcSFedor Sergeev   unsigned NumVectorInstructions = 0;
338eeae45dcSFedor Sergeev 
339f3d122cdSPiotr Padlewski   /// While we walk the potentially-inlined instructions, we build up and
340f3d122cdSPiotr Padlewski   /// maintain a mapping of simplified values specific to this callsite. The
341f3d122cdSPiotr Padlewski   /// idea is to propagate any special information we have about arguments to
342f3d122cdSPiotr Padlewski   /// this call through the inlinable section of the function, and account for
343f3d122cdSPiotr Padlewski   /// likely simplifications post-inlining. The most important aspect we track
344f3d122cdSPiotr Padlewski   /// is CFG altering simplifications -- when we prove a basic block dead, that
345f3d122cdSPiotr Padlewski   /// can cause dramatic shifts in the cost of inlining a function.
3467adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
3477adc3a2bSChandler Carruth 
348f3d122cdSPiotr Padlewski   /// Keep track of the values which map back (through function arguments) to
349f3d122cdSPiotr Padlewski   /// allocas on the caller stack which could be simplified through SROA.
35006408758SMircea Trofin   DenseMap<Value *, AllocaInst *> SROAArgValues;
351338a6016SMircea Trofin 
35206408758SMircea Trofin   /// Keep track of Allocas for which we believe we may get SROA optimization.
3532e42cc7aSMircea Trofin   DenseSet<AllocaInst *> EnabledSROAAllocas;
3547adc3a2bSChandler Carruth 
355f3d122cdSPiotr Padlewski   /// Keep track of values which map to a pointer base and constant offset.
3567adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
3577adc3a2bSChandler Carruth 
3583739e14aSHaicheng Wu   /// Keep track of dead blocks due to the constant arguments.
3593c53d3a7SNikita Popov   SmallPtrSet<BasicBlock *, 16> DeadBlocks;
3603739e14aSHaicheng Wu 
3613739e14aSHaicheng Wu   /// The mapping of the blocks to their known unique successors due to the
3623739e14aSHaicheng Wu   /// constant arguments.
3633739e14aSHaicheng Wu   DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
3643739e14aSHaicheng Wu 
365a4461515SHaicheng Wu   /// Model the elimination of repeated loads that is expected to happen
366a4461515SHaicheng Wu   /// whenever we simplify away the stores that would otherwise cause them to be
367a4461515SHaicheng Wu   /// loads.
368b752eb88SKazu Hirata   bool EnableLoadElimination = true;
369f7fff46aSWenlei He 
370f7fff46aSWenlei He   /// Whether we allow inlining for recursive call.
371b752eb88SKazu Hirata   bool AllowRecursiveCall = false;
372f7fff46aSWenlei He 
373a4461515SHaicheng Wu   SmallPtrSet<Value *, 16> LoadAddrSet;
37406408758SMircea Trofin 
getSROAArgForValueOrNull(Value * V) const37506408758SMircea Trofin   AllocaInst *getSROAArgForValueOrNull(Value *V) const {
37606408758SMircea Trofin     auto It = SROAArgValues.find(V);
3772e42cc7aSMircea Trofin     if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
37806408758SMircea Trofin       return nullptr;
37906408758SMircea Trofin     return It->second;
38006408758SMircea Trofin   }
381a4461515SHaicheng Wu 
3827adc3a2bSChandler Carruth   // Custom simplification helper routines.
3837adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
38406408758SMircea Trofin   void disableSROAForArg(AllocaInst *SROAArg);
3857adc3a2bSChandler Carruth   void disableSROA(Value *V);
3863739e14aSHaicheng Wu   void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
387a4461515SHaicheng Wu   void disableLoadElimination();
388201b191bSHaicheng Wu   bool isGEPFree(GetElementPtrInst &GEP);
389d3558b5dSEvgeny Astigeevich   bool canFoldInboundsGEP(GetElementPtrInst &I);
3907adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
391652168a9SFedor Sergeev   bool simplifyCallSite(Function *F, CallBase &Call);
39254fcde42SNikita Popov   bool simplifyInstruction(Instruction &I);
3939697f935SNick Desaulniers   bool simplifyIntrinsicCallIsConstant(CallBase &CB);
3947adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
3957adc3a2bSChandler Carruth 
3967adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
3977adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
3987adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
3997adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
4007adc3a2bSChandler Carruth   /// itself.
4017adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
4027adc3a2bSChandler Carruth 
4037adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
4047adc3a2bSChandler Carruth   /// inlined through this particular callsite.
4057adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
4067adc3a2bSChandler Carruth 
407652168a9SFedor Sergeev   /// Return true if size growth is allowed when inlining the callee at \p Call.
408652168a9SFedor Sergeev   bool allowSizeGrowth(CallBase &Call);
4099a3fc17aSEaswaran Raman 
4107adc3a2bSChandler Carruth   // Custom analysis routines.
411c0aa4b75SDavid Bolvansky   InlineResult analyzeBlock(BasicBlock *BB,
412c0aa4b75SDavid Bolvansky                             SmallPtrSetImpl<const Value *> &EphValues);
4137adc3a2bSChandler Carruth 
4147adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
4157adc3a2bSChandler Carruth   // them by declaring but not defining them here.
416567556aaSChad Rosier   void visit(Module *);
417567556aaSChad Rosier   void visit(Module &);
418567556aaSChad Rosier   void visit(Function *);
419567556aaSChad Rosier   void visit(Function &);
420567556aaSChad Rosier   void visit(BasicBlock *);
421567556aaSChad Rosier   void visit(BasicBlock &);
4227adc3a2bSChandler Carruth 
4237adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
4247adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
4257adc3a2bSChandler Carruth 
4267adc3a2bSChandler Carruth   // Our visit overrides.
4277adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
4287adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
4297adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
4307adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
4317adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
4327adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
4337adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
4347adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
4357adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
4367adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
4376cda33baSCraig Topper   bool visitFNeg(UnaryOperator &I);
4387adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
4397adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
4407adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
4417adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
442652168a9SFedor Sergeev   bool visitCallBase(CallBase &Call);
4437adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
4447adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
4453ec848bcSHaicheng Wu   bool visitSelectInst(SelectInst &SI);
4467adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
4477adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
4487adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
4497adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
4507adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
4517adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
4527adc3a2bSChandler Carruth 
4537adc3a2bSChandler Carruth public:
CallAnalyzer(Function & Callee,CallBase & Call,const TargetTransformInfo & TTI,function_ref<AssumptionCache & (Function &)> GetAssumptionCache,function_ref<BlockFrequencyInfo & (Function &)> GetBFI=nullptr,ProfileSummaryInfo * PSI=nullptr,OptimizationRemarkEmitter * ORE=nullptr)4547b639f50SJacob Hegna   CallAnalyzer(Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
45508e2386dSMircea Trofin                function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
45608e2386dSMircea Trofin                function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
45708e2386dSMircea Trofin                ProfileSummaryInfo *PSI = nullptr,
45808e2386dSMircea Trofin                OptimizationRemarkEmitter *ORE = nullptr)
45912585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
4600812c5beSHaicheng Wu         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
461b752eb88SKazu Hirata         CandidateCall(Call) {}
4627adc3a2bSChandler Carruth 
46393ac81ccSMircea Trofin   InlineResult analyze();
4647adc3a2bSChandler Carruth 
getSimplifiedValue(Instruction * I)4657f094f7fSKirill Naumov   Optional<Constant *> getSimplifiedValue(Instruction *I) {
4667f094f7fSKirill Naumov     if (SimplifiedValues.find(I) != SimplifiedValues.end())
4677f094f7fSKirill Naumov       return SimplifiedValues[I];
4687f094f7fSKirill Naumov     return None;
4697f094f7fSKirill Naumov   }
4707f094f7fSKirill Naumov 
4717adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
4727adc3a2bSChandler Carruth   // out when debugging.
473eeae45dcSFedor Sergeev   unsigned NumConstantArgs = 0;
474eeae45dcSFedor Sergeev   unsigned NumConstantOffsetPtrArgs = 0;
475eeae45dcSFedor Sergeev   unsigned NumAllocaArgs = 0;
476eeae45dcSFedor Sergeev   unsigned NumConstantPtrCmps = 0;
477eeae45dcSFedor Sergeev   unsigned NumConstantPtrDiffs = 0;
478eeae45dcSFedor Sergeev   unsigned NumInstructionsSimplified = 0;
47976aab66dSMircea Trofin 
48076aab66dSMircea Trofin   void dump();
48176aab66dSMircea Trofin };
482338a6016SMircea Trofin 
48399f00635SJacob Hegna // Considering forming a binary search, we should find the number of nodes
48499f00635SJacob Hegna // which is same as the number of comparisons when lowered. For a given
48599f00635SJacob Hegna // number of clusters, n, we can define a recursive function, f(n), to find
48699f00635SJacob Hegna // the number of nodes in the tree. The recursion is :
48799f00635SJacob Hegna // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
48899f00635SJacob Hegna // and f(n) = n, when n <= 3.
48999f00635SJacob Hegna // This will lead a binary tree where the leaf should be either f(2) or f(3)
49099f00635SJacob Hegna // when n > 3.  So, the number of comparisons from leaves should be n, while
49199f00635SJacob Hegna // the number of non-leaf should be :
49299f00635SJacob Hegna //   2^(log2(n) - 1) - 1
49399f00635SJacob Hegna //   = 2^log2(n) * 2^-1 - 1
49499f00635SJacob Hegna //   = n / 2 - 1.
49599f00635SJacob Hegna // Considering comparisons from leaf and non-leaf nodes, we can estimate the
49699f00635SJacob Hegna // number of comparisons in a simple closed form :
49799f00635SJacob Hegna //   n + n / 2 - 1 = n * 3 / 2 - 1
getExpectedNumberOfCompare(int NumCaseCluster)49899f00635SJacob Hegna int64_t getExpectedNumberOfCompare(int NumCaseCluster) {
49999f00635SJacob Hegna   return 3 * static_cast<int64_t>(NumCaseCluster) / 2 - 1;
50099f00635SJacob Hegna }
50199f00635SJacob Hegna 
50206408758SMircea Trofin /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
50306408758SMircea Trofin /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
50406408758SMircea Trofin class InlineCostCallAnalyzer final : public CallAnalyzer {
50506408758SMircea Trofin   const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
50606408758SMircea Trofin   const bool ComputeFullInlineCost;
50706408758SMircea Trofin   int LoadEliminationCost = 0;
50806408758SMircea Trofin   /// Bonus to be applied when percentage of vector instructions in callee is
50906408758SMircea Trofin   /// high (see more details in updateThreshold).
51006408758SMircea Trofin   int VectorBonus = 0;
51106408758SMircea Trofin   /// Bonus to be applied when the callee has only one reachable basic block.
51206408758SMircea Trofin   int SingleBBBonus = 0;
51306408758SMircea Trofin 
51406408758SMircea Trofin   /// Tunable parameters that control the analysis.
51506408758SMircea Trofin   const InlineParams &Params;
51606408758SMircea Trofin 
5171022b5ebSKirill Naumov   // This DenseMap stores the delta change in cost and threshold after
5181022b5ebSKirill Naumov   // accounting for the given instruction. The map is filled only with the
5191022b5ebSKirill Naumov   // flag PrintInstructionComments on.
5201022b5ebSKirill Naumov   DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
5211022b5ebSKirill Naumov 
52206408758SMircea Trofin   /// Upper bound for the inlining cost. Bonuses are being applied to account
52306408758SMircea Trofin   /// for speculative "expected profit" of the inlining decision.
52406408758SMircea Trofin   int Threshold = 0;
52506408758SMircea Trofin 
52606408758SMircea Trofin   /// Attempt to evaluate indirect calls to boost its inline cost.
52706408758SMircea Trofin   const bool BoostIndirectCalls;
52806408758SMircea Trofin 
5298a4013edSMircea Trofin   /// Ignore the threshold when finalizing analysis.
5308a4013edSMircea Trofin   const bool IgnoreThreshold;
5318a4013edSMircea Trofin 
5329895c701SKazu Hirata   // True if the cost-benefit-analysis-based inliner is enabled.
5339895c701SKazu Hirata   const bool CostBenefitAnalysisEnabled;
5349895c701SKazu Hirata 
53506408758SMircea Trofin   /// Inlining cost measured in abstract units, accounts for all the
53606408758SMircea Trofin   /// instructions expected to be executed for a given function invocation.
53706408758SMircea Trofin   /// Instructions that are statically proven to be dead based on call-site
53806408758SMircea Trofin   /// arguments are not counted here.
53906408758SMircea Trofin   int Cost = 0;
54006408758SMircea Trofin 
5419895c701SKazu Hirata   // The cumulative cost at the beginning of the basic block being analyzed.  At
5429895c701SKazu Hirata   // the end of analyzing each basic block, "Cost - CostAtBBStart" represents
5439895c701SKazu Hirata   // the size of that basic block.
5449895c701SKazu Hirata   int CostAtBBStart = 0;
5459895c701SKazu Hirata 
5469895c701SKazu Hirata   // The static size of live but cold basic blocks.  This is "static" in the
5479895c701SKazu Hirata   // sense that it's not weighted by profile counts at all.
5489895c701SKazu Hirata   int ColdSize = 0;
5499895c701SKazu Hirata 
5503f96f7b3SArtur Pilipenko   // Whether inlining is decided by cost-threshold analysis.
5513f96f7b3SArtur Pilipenko   bool DecidedByCostThreshold = false;
5523f96f7b3SArtur Pilipenko 
5536869e6c1SWenlei He   // Whether inlining is decided by cost-benefit analysis.
5546869e6c1SWenlei He   bool DecidedByCostBenefit = false;
5556869e6c1SWenlei He 
5564bdfea2cSLiqiang Tao   // The cost-benefit pair computed by cost-benefit analysis.
5574bdfea2cSLiqiang Tao   Optional<CostBenefitPair> CostBenefit = None;
5584bdfea2cSLiqiang Tao 
55906408758SMircea Trofin   bool SingleBB = true;
56006408758SMircea Trofin 
56106408758SMircea Trofin   unsigned SROACostSavings = 0;
56206408758SMircea Trofin   unsigned SROACostSavingsLost = 0;
56306408758SMircea Trofin 
56406408758SMircea Trofin   /// The mapping of caller Alloca values to their accumulated cost savings. If
56506408758SMircea Trofin   /// we have to disable SROA for one of the allocas, this tells us how much
56606408758SMircea Trofin   /// cost must be added.
56706408758SMircea Trofin   DenseMap<AllocaInst *, int> SROAArgCosts;
56806408758SMircea Trofin 
56906408758SMircea Trofin   /// Return true if \p Call is a cold callsite.
57006408758SMircea Trofin   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
57106408758SMircea Trofin 
57206408758SMircea Trofin   /// Update Threshold based on callsite properties such as callee
57306408758SMircea Trofin   /// attributes and callee hotness for PGO builds. The Callee is explicitly
57406408758SMircea Trofin   /// passed to support analyzing indirect calls whose target is inferred by
57506408758SMircea Trofin   /// analysis.
57606408758SMircea Trofin   void updateThreshold(CallBase &Call, Function &Callee);
57706408758SMircea Trofin   /// Return a higher threshold if \p Call is a hot callsite.
57806408758SMircea Trofin   Optional<int> getHotCallSiteThreshold(CallBase &Call,
57906408758SMircea Trofin                                         BlockFrequencyInfo *CallerBFI);
58006408758SMircea Trofin 
58106408758SMircea Trofin   /// Handle a capped 'int' increment for Cost.
addCost(int64_t Inc,int64_t UpperBound=INT_MAX)58206408758SMircea Trofin   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
58306408758SMircea Trofin     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
584cfc4def8SJacob Hegna     Cost = std::min<int>(UpperBound, Cost + Inc);
58506408758SMircea Trofin   }
58606408758SMircea Trofin 
onDisableSROA(AllocaInst * Arg)58706408758SMircea Trofin   void onDisableSROA(AllocaInst *Arg) override {
58806408758SMircea Trofin     auto CostIt = SROAArgCosts.find(Arg);
58906408758SMircea Trofin     if (CostIt == SROAArgCosts.end())
59006408758SMircea Trofin       return;
59106408758SMircea Trofin     addCost(CostIt->second);
59206408758SMircea Trofin     SROACostSavings -= CostIt->second;
59306408758SMircea Trofin     SROACostSavingsLost += CostIt->second;
59406408758SMircea Trofin     SROAArgCosts.erase(CostIt);
59506408758SMircea Trofin   }
59606408758SMircea Trofin 
onDisableLoadElimination()59706408758SMircea Trofin   void onDisableLoadElimination() override {
59806408758SMircea Trofin     addCost(LoadEliminationCost);
59906408758SMircea Trofin     LoadEliminationCost = 0;
60006408758SMircea Trofin   }
6015c97507eSDaniil Suchkov 
onCallBaseVisitStart(CallBase & Call)6025c97507eSDaniil Suchkov   bool onCallBaseVisitStart(CallBase &Call) override {
6035c97507eSDaniil Suchkov     if (Optional<int> AttrCallThresholdBonus =
6045c97507eSDaniil Suchkov             getStringFnAttrAsInt(Call, "call-threshold-bonus"))
6055c97507eSDaniil Suchkov       Threshold += *AttrCallThresholdBonus;
6065c97507eSDaniil Suchkov 
6075c97507eSDaniil Suchkov     if (Optional<int> AttrCallCost =
6085c97507eSDaniil Suchkov             getStringFnAttrAsInt(Call, "call-inline-cost")) {
6095c97507eSDaniil Suchkov       addCost(*AttrCallCost);
6105c97507eSDaniil Suchkov       // Prevent further processing of the call since we want to override its
6115c97507eSDaniil Suchkov       // inline cost, not just add to it.
6125c97507eSDaniil Suchkov       return false;
6135c97507eSDaniil Suchkov     }
6145c97507eSDaniil Suchkov     return true;
6155c97507eSDaniil Suchkov   }
6165c97507eSDaniil Suchkov 
onCallPenalty()61746c03668SPhilipp Krones   void onCallPenalty() override { addCost(CallPenalty); }
onCallArgumentSetup(const CallBase & Call)61806408758SMircea Trofin   void onCallArgumentSetup(const CallBase &Call) override {
61906408758SMircea Trofin     // Pay the price of the argument setup. We account for the average 1
62006408758SMircea Trofin     // instruction per call argument setup here.
62106408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
62206408758SMircea Trofin   }
onLoadRelativeIntrinsic()62306408758SMircea Trofin   void onLoadRelativeIntrinsic() override {
62406408758SMircea Trofin     // This is normally lowered to 4 LLVM instructions.
62506408758SMircea Trofin     addCost(3 * InlineConstants::InstrCost);
62606408758SMircea Trofin   }
onLoweredCall(Function * F,CallBase & Call,bool IsIndirectCall)62706408758SMircea Trofin   void onLoweredCall(Function *F, CallBase &Call,
62806408758SMircea Trofin                      bool IsIndirectCall) override {
62906408758SMircea Trofin     // We account for the average 1 instruction per call argument setup here.
63006408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
63106408758SMircea Trofin 
63206408758SMircea Trofin     // If we have a constant that we are calling as a function, we can peer
63306408758SMircea Trofin     // through it and see the function target. This happens not infrequently
63406408758SMircea Trofin     // during devirtualization and so we want to give it a hefty bonus for
63506408758SMircea Trofin     // inlining, but cap that bonus in the event that inlining wouldn't pan out.
63606408758SMircea Trofin     // Pretend to inline the function, with a custom threshold.
63706408758SMircea Trofin     if (IsIndirectCall && BoostIndirectCalls) {
63806408758SMircea Trofin       auto IndirectCallParams = Params;
63906408758SMircea Trofin       IndirectCallParams.DefaultThreshold =
64006408758SMircea Trofin           InlineConstants::IndirectCallThreshold;
64106408758SMircea Trofin       /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
64206408758SMircea Trofin       /// to instantiate the derived class.
64308e2386dSMircea Trofin       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
64408e2386dSMircea Trofin                                 GetAssumptionCache, GetBFI, PSI, ORE, false);
6455466597fSMircea Trofin       if (CA.analyze().isSuccess()) {
64606408758SMircea Trofin         // We were able to inline the indirect call! Subtract the cost from the
64706408758SMircea Trofin         // threshold to get the bonus we want to apply, but don't go below zero.
64806408758SMircea Trofin         Cost -= std::max(0, CA.getThreshold() - CA.getCost());
64906408758SMircea Trofin       }
65006408758SMircea Trofin     } else
65106408758SMircea Trofin       // Otherwise simply add the cost for merely making the call.
65246c03668SPhilipp Krones       addCost(CallPenalty);
65306408758SMircea Trofin   }
65406408758SMircea Trofin 
onFinalizeSwitch(unsigned JumpTableSize,unsigned NumCaseCluster)65506408758SMircea Trofin   void onFinalizeSwitch(unsigned JumpTableSize,
65606408758SMircea Trofin                         unsigned NumCaseCluster) override {
65706408758SMircea Trofin     // If suitable for a jump table, consider the cost for the table size and
65806408758SMircea Trofin     // branch to destination.
65906408758SMircea Trofin     // Maximum valid cost increased in this function.
66006408758SMircea Trofin     if (JumpTableSize) {
661cfc4def8SJacob Hegna       int64_t JTCost =
662cfc4def8SJacob Hegna           static_cast<int64_t>(JumpTableSize) * InlineConstants::InstrCost +
66306408758SMircea Trofin           4 * InlineConstants::InstrCost;
66406408758SMircea Trofin 
665cfc4def8SJacob Hegna       addCost(JTCost, static_cast<int64_t>(CostUpperBound));
66606408758SMircea Trofin       return;
66706408758SMircea Trofin     }
66899f00635SJacob Hegna 
66906408758SMircea Trofin     if (NumCaseCluster <= 3) {
67006408758SMircea Trofin       // Suppose a comparison includes one compare and one conditional branch.
67106408758SMircea Trofin       addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
67206408758SMircea Trofin       return;
67306408758SMircea Trofin     }
67406408758SMircea Trofin 
67599f00635SJacob Hegna     int64_t ExpectedNumberOfCompare =
67699f00635SJacob Hegna         getExpectedNumberOfCompare(NumCaseCluster);
67706408758SMircea Trofin     int64_t SwitchCost =
67806408758SMircea Trofin         ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
67906408758SMircea Trofin 
680cfc4def8SJacob Hegna     addCost(SwitchCost, static_cast<int64_t>(CostUpperBound));
68106408758SMircea Trofin   }
onMissedSimplification()68214a16faeSMircea Trofin   void onMissedSimplification() override {
68306408758SMircea Trofin     addCost(InlineConstants::InstrCost);
68406408758SMircea Trofin   }
68506408758SMircea Trofin 
onInitializeSROAArg(AllocaInst * Arg)68606408758SMircea Trofin   void onInitializeSROAArg(AllocaInst *Arg) override {
68706408758SMircea Trofin     assert(Arg != nullptr &&
68806408758SMircea Trofin            "Should not initialize SROA costs for null value.");
68906408758SMircea Trofin     SROAArgCosts[Arg] = 0;
69006408758SMircea Trofin   }
69106408758SMircea Trofin 
onAggregateSROAUse(AllocaInst * SROAArg)69206408758SMircea Trofin   void onAggregateSROAUse(AllocaInst *SROAArg) override {
69306408758SMircea Trofin     auto CostIt = SROAArgCosts.find(SROAArg);
69406408758SMircea Trofin     assert(CostIt != SROAArgCosts.end() &&
69506408758SMircea Trofin            "expected this argument to have a cost");
69606408758SMircea Trofin     CostIt->second += InlineConstants::InstrCost;
69706408758SMircea Trofin     SROACostSavings += InlineConstants::InstrCost;
69806408758SMircea Trofin   }
69906408758SMircea Trofin 
onBlockStart(const BasicBlock * BB)7009895c701SKazu Hirata   void onBlockStart(const BasicBlock *BB) override { CostAtBBStart = Cost; }
7019895c701SKazu Hirata 
onBlockAnalyzed(const BasicBlock * BB)70206408758SMircea Trofin   void onBlockAnalyzed(const BasicBlock *BB) override {
7039895c701SKazu Hirata     if (CostBenefitAnalysisEnabled) {
7049895c701SKazu Hirata       // Keep track of the static size of live but cold basic blocks.  For now,
7059895c701SKazu Hirata       // we define a cold basic block to be one that's never executed.
7069895c701SKazu Hirata       assert(GetBFI && "GetBFI must be available");
7079895c701SKazu Hirata       BlockFrequencyInfo *BFI = &(GetBFI(F));
7089895c701SKazu Hirata       assert(BFI && "BFI must be available");
7099895c701SKazu Hirata       auto ProfileCount = BFI->getBlockProfileCount(BB);
710a7938c74SKazu Hirata       assert(ProfileCount);
711611ffcf4SKazu Hirata       if (ProfileCount.value() == 0)
7129895c701SKazu Hirata         ColdSize += Cost - CostAtBBStart;
7139895c701SKazu Hirata     }
7149895c701SKazu Hirata 
71506408758SMircea Trofin     auto *TI = BB->getTerminator();
71606408758SMircea Trofin     // If we had any successors at this point, than post-inlining is likely to
71706408758SMircea Trofin     // have them as well. Note that we assume any basic blocks which existed
71806408758SMircea Trofin     // due to branches or switches which folded above will also fold after
71906408758SMircea Trofin     // inlining.
72006408758SMircea Trofin     if (SingleBB && TI->getNumSuccessors() > 1) {
72106408758SMircea Trofin       // Take off the bonus we applied to the threshold.
72206408758SMircea Trofin       Threshold -= SingleBBBonus;
72306408758SMircea Trofin       SingleBB = false;
72406408758SMircea Trofin     }
72506408758SMircea Trofin   }
7265466597fSMircea Trofin 
onInstructionAnalysisStart(const Instruction * I)727c965fd94SKirill Naumov   void onInstructionAnalysisStart(const Instruction *I) override {
728c965fd94SKirill Naumov     // This function is called to store the initial cost of inlining before
729c965fd94SKirill Naumov     // the given instruction was assessed.
7301022b5ebSKirill Naumov     if (!PrintInstructionComments)
731c965fd94SKirill Naumov       return;
7321022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostBefore = Cost;
7331022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdBefore = Threshold;
734c965fd94SKirill Naumov   }
735c965fd94SKirill Naumov 
onInstructionAnalysisFinish(const Instruction * I)736c965fd94SKirill Naumov   void onInstructionAnalysisFinish(const Instruction *I) override {
737c965fd94SKirill Naumov     // This function is called to find new values of cost and threshold after
738c965fd94SKirill Naumov     // the instruction has been assessed.
7391022b5ebSKirill Naumov     if (!PrintInstructionComments)
740c965fd94SKirill Naumov       return;
7411022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostAfter = Cost;
7421022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdAfter = Threshold;
743c965fd94SKirill Naumov   }
744c965fd94SKirill Naumov 
isCostBenefitAnalysisEnabled()7459895c701SKazu Hirata   bool isCostBenefitAnalysisEnabled() {
7469895c701SKazu Hirata     if (!PSI || !PSI->hasProfileSummary())
7479895c701SKazu Hirata       return false;
7489895c701SKazu Hirata 
7499895c701SKazu Hirata     if (!GetBFI)
7509895c701SKazu Hirata       return false;
7519895c701SKazu Hirata 
7529d375a40SKazu Hirata     if (InlineEnableCostBenefitAnalysis.getNumOccurrences()) {
7539d375a40SKazu Hirata       // Honor the explicit request from the user.
7549d375a40SKazu Hirata       if (!InlineEnableCostBenefitAnalysis)
7559d375a40SKazu Hirata         return false;
7569d375a40SKazu Hirata     } else {
7579d375a40SKazu Hirata       // Otherwise, require instrumentation profile.
7589d375a40SKazu Hirata       if (!PSI->hasInstrumentationProfile())
7599d375a40SKazu Hirata         return false;
7609d375a40SKazu Hirata     }
7619d375a40SKazu Hirata 
7629895c701SKazu Hirata     auto *Caller = CandidateCall.getParent()->getParent();
7639895c701SKazu Hirata     if (!Caller->getEntryCount())
7649895c701SKazu Hirata       return false;
7659895c701SKazu Hirata 
7669895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*Caller));
7679895c701SKazu Hirata     if (!CallerBFI)
7689895c701SKazu Hirata       return false;
7699895c701SKazu Hirata 
7709895c701SKazu Hirata     // For now, limit to hot call site.
7719895c701SKazu Hirata     if (!PSI->isHotCallSite(CandidateCall, CallerBFI))
7729895c701SKazu Hirata       return false;
7739895c701SKazu Hirata 
7743c775d93SKazu Hirata     // Make sure we have a nonzero entry count.
7753c775d93SKazu Hirata     auto EntryCount = F.getEntryCount();
776a32c2c38SMircea Trofin     if (!EntryCount || !EntryCount->getCount())
7779895c701SKazu Hirata       return false;
7789895c701SKazu Hirata 
7799895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
7809895c701SKazu Hirata     if (!CalleeBFI)
7819895c701SKazu Hirata       return false;
7829895c701SKazu Hirata 
7839895c701SKazu Hirata     return true;
7849895c701SKazu Hirata   }
7859895c701SKazu Hirata 
7869895c701SKazu Hirata   // Determine whether we should inline the given call site, taking into account
7879895c701SKazu Hirata   // both the size cost and the cycle savings.  Return None if we don't have
7889895c701SKazu Hirata   // suficient profiling information to determine.
costBenefitAnalysis()7899895c701SKazu Hirata   Optional<bool> costBenefitAnalysis() {
7909895c701SKazu Hirata     if (!CostBenefitAnalysisEnabled)
7919895c701SKazu Hirata       return None;
7929895c701SKazu Hirata 
7939895c701SKazu Hirata     // buildInlinerPipeline in the pass builder sets HotCallSiteThreshold to 0
7949895c701SKazu Hirata     // for the prelink phase of the AutoFDO + ThinLTO build.  Honor the logic by
7959895c701SKazu Hirata     // falling back to the cost-based metric.
7969895c701SKazu Hirata     // TODO: Improve this hacky condition.
7979895c701SKazu Hirata     if (Threshold == 0)
7989895c701SKazu Hirata       return None;
7999895c701SKazu Hirata 
8009895c701SKazu Hirata     assert(GetBFI);
8019895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
8029895c701SKazu Hirata     assert(CalleeBFI);
8039895c701SKazu Hirata 
8049895c701SKazu Hirata     // The cycle savings expressed as the sum of InlineConstants::InstrCost
8059895c701SKazu Hirata     // multiplied by the estimated dynamic count of each instruction we can
8069895c701SKazu Hirata     // avoid.  Savings come from the call site cost, such as argument setup and
8079895c701SKazu Hirata     // the call instruction, as well as the instructions that are folded.
8089895c701SKazu Hirata     //
8099895c701SKazu Hirata     // We use 128-bit APInt here to avoid potential overflow.  This variable
8109895c701SKazu Hirata     // should stay well below 10^^24 (or 2^^80) in practice.  This "worst" case
8119895c701SKazu Hirata     // assumes that we can avoid or fold a billion instructions, each with a
8129895c701SKazu Hirata     // profile count of 10^^15 -- roughly the number of cycles for a 24-hour
8139895c701SKazu Hirata     // period on a 4GHz machine.
8149895c701SKazu Hirata     APInt CycleSavings(128, 0);
8159895c701SKazu Hirata 
8169895c701SKazu Hirata     for (auto &BB : F) {
8179895c701SKazu Hirata       APInt CurrentSavings(128, 0);
8189895c701SKazu Hirata       for (auto &I : BB) {
8199895c701SKazu Hirata         if (BranchInst *BI = dyn_cast<BranchInst>(&I)) {
8209895c701SKazu Hirata           // Count a conditional branch as savings if it becomes unconditional.
8219895c701SKazu Hirata           if (BI->isConditional() &&
822d243cbf8SKazu Hirata               isa_and_nonnull<ConstantInt>(
8239895c701SKazu Hirata                   SimplifiedValues.lookup(BI->getCondition()))) {
8249895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
8259895c701SKazu Hirata           }
8269895c701SKazu Hirata         } else if (Value *V = dyn_cast<Value>(&I)) {
8279895c701SKazu Hirata           // Count an instruction as savings if we can fold it.
8289895c701SKazu Hirata           if (SimplifiedValues.count(V)) {
8299895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
8309895c701SKazu Hirata           }
8319895c701SKazu Hirata         }
8329895c701SKazu Hirata       }
8339895c701SKazu Hirata 
8349895c701SKazu Hirata       auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
835a7938c74SKazu Hirata       assert(ProfileCount);
836611ffcf4SKazu Hirata       CurrentSavings *= ProfileCount.value();
8379895c701SKazu Hirata       CycleSavings += CurrentSavings;
8389895c701SKazu Hirata     }
8399895c701SKazu Hirata 
8409895c701SKazu Hirata     // Compute the cycle savings per call.
8419895c701SKazu Hirata     auto EntryProfileCount = F.getEntryCount();
842a7938c74SKazu Hirata     assert(EntryProfileCount && EntryProfileCount->getCount());
843a32c2c38SMircea Trofin     auto EntryCount = EntryProfileCount->getCount();
8449895c701SKazu Hirata     CycleSavings += EntryCount / 2;
8459895c701SKazu Hirata     CycleSavings = CycleSavings.udiv(EntryCount);
8469895c701SKazu Hirata 
8479895c701SKazu Hirata     // Compute the total savings for the call site.
8489895c701SKazu Hirata     auto *CallerBB = CandidateCall.getParent();
8499895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*(CallerBB->getParent())));
8509895c701SKazu Hirata     CycleSavings += getCallsiteCost(this->CandidateCall, DL);
8517a47ee51SKazu Hirata     CycleSavings *= *CallerBFI->getBlockProfileCount(CallerBB);
8529895c701SKazu Hirata 
8539895c701SKazu Hirata     // Remove the cost of the cold basic blocks.
8549895c701SKazu Hirata     int Size = Cost - ColdSize;
8559895c701SKazu Hirata 
8569895c701SKazu Hirata     // Allow tiny callees to be inlined regardless of whether they meet the
8579895c701SKazu Hirata     // savings threshold.
8589895c701SKazu Hirata     Size = Size > InlineSizeAllowance ? Size - InlineSizeAllowance : 1;
8599895c701SKazu Hirata 
8604bdfea2cSLiqiang Tao     CostBenefit.emplace(APInt(128, Size), CycleSavings);
8614bdfea2cSLiqiang Tao 
8629895c701SKazu Hirata     // Return true if the savings justify the cost of inlining.  Specifically,
8639895c701SKazu Hirata     // we evaluate the following inequality:
8649895c701SKazu Hirata     //
8659895c701SKazu Hirata     //  CycleSavings      PSI->getOrCompHotCountThreshold()
8669895c701SKazu Hirata     // -------------- >= -----------------------------------
8679895c701SKazu Hirata     //       Size              InlineSavingsMultiplier
8689895c701SKazu Hirata     //
8699895c701SKazu Hirata     // Note that the left hand side is specific to a call site.  The right hand
8709895c701SKazu Hirata     // side is a constant for the entire executable.
8719895c701SKazu Hirata     APInt LHS = CycleSavings;
8729895c701SKazu Hirata     LHS *= InlineSavingsMultiplier;
8739895c701SKazu Hirata     APInt RHS(128, PSI->getOrCompHotCountThreshold());
8749895c701SKazu Hirata     RHS *= Size;
8759895c701SKazu Hirata     return LHS.uge(RHS);
8769895c701SKazu Hirata   }
8779895c701SKazu Hirata 
finalizeAnalysis()87806408758SMircea Trofin   InlineResult finalizeAnalysis() override {
87906408758SMircea Trofin     // Loops generally act a lot like calls in that they act like barriers to
88006408758SMircea Trofin     // movement, require a certain amount of setup, etc. So when optimising for
88106408758SMircea Trofin     // size, we penalise any call sites that perform loops. We do this after all
88206408758SMircea Trofin     // other costs here, so will likely only be dealing with relatively small
88306408758SMircea Trofin     // functions (and hence DT and LI will hopefully be cheap).
88406408758SMircea Trofin     auto *Caller = CandidateCall.getFunction();
88506408758SMircea Trofin     if (Caller->hasMinSize()) {
88606408758SMircea Trofin       DominatorTree DT(F);
88706408758SMircea Trofin       LoopInfo LI(DT);
88806408758SMircea Trofin       int NumLoops = 0;
88906408758SMircea Trofin       for (Loop *L : LI) {
89006408758SMircea Trofin         // Ignore loops that will not be executed
89106408758SMircea Trofin         if (DeadBlocks.count(L->getHeader()))
89206408758SMircea Trofin           continue;
89306408758SMircea Trofin         NumLoops++;
89406408758SMircea Trofin       }
89546c03668SPhilipp Krones       addCost(NumLoops * InlineConstants::LoopPenalty);
89606408758SMircea Trofin     }
89706408758SMircea Trofin 
89806408758SMircea Trofin     // We applied the maximum possible vector bonus at the beginning. Now,
89906408758SMircea Trofin     // subtract the excess bonus, if any, from the Threshold before
90006408758SMircea Trofin     // comparing against Cost.
90106408758SMircea Trofin     if (NumVectorInstructions <= NumInstructions / 10)
90206408758SMircea Trofin       Threshold -= VectorBonus;
90306408758SMircea Trofin     else if (NumVectorInstructions <= NumInstructions / 2)
90406408758SMircea Trofin       Threshold -= VectorBonus / 2;
90506408758SMircea Trofin 
9065c97507eSDaniil Suchkov     if (Optional<int> AttrCost =
9075c97507eSDaniil Suchkov             getStringFnAttrAsInt(CandidateCall, "function-inline-cost"))
9085c97507eSDaniil Suchkov       Cost = *AttrCost;
9095c97507eSDaniil Suchkov 
91053e5e586SArthur Eubanks     if (Optional<int> AttrCostMult = getStringFnAttrAsInt(
91153e5e586SArthur Eubanks             CandidateCall,
91253e5e586SArthur Eubanks             InlineConstants::FunctionInlineCostMultiplierAttributeName))
91353e5e586SArthur Eubanks       Cost *= *AttrCostMult;
91453e5e586SArthur Eubanks 
9155c97507eSDaniil Suchkov     if (Optional<int> AttrThreshold =
9165c97507eSDaniil Suchkov             getStringFnAttrAsInt(CandidateCall, "function-inline-threshold"))
9175c97507eSDaniil Suchkov       Threshold = *AttrThreshold;
9185c97507eSDaniil Suchkov 
9199895c701SKazu Hirata     if (auto Result = costBenefitAnalysis()) {
9206869e6c1SWenlei He       DecidedByCostBenefit = true;
9217a47ee51SKazu Hirata       if (*Result)
9229895c701SKazu Hirata         return InlineResult::success();
9239895c701SKazu Hirata       else
9249895c701SKazu Hirata         return InlineResult::failure("Cost over threshold.");
9259895c701SKazu Hirata     }
9269895c701SKazu Hirata 
9273f96f7b3SArtur Pilipenko     if (IgnoreThreshold)
9285466597fSMircea Trofin       return InlineResult::success();
9293f96f7b3SArtur Pilipenko 
9303f96f7b3SArtur Pilipenko     DecidedByCostThreshold = true;
9313f96f7b3SArtur Pilipenko     return Cost < std::max(1, Threshold)
9323f96f7b3SArtur Pilipenko                ? InlineResult::success()
9333f96f7b3SArtur Pilipenko                : InlineResult::failure("Cost over threshold.");
93406408758SMircea Trofin   }
9353f96f7b3SArtur Pilipenko 
shouldStop()93606408758SMircea Trofin   bool shouldStop() override {
9373f96f7b3SArtur Pilipenko     if (IgnoreThreshold || ComputeFullInlineCost)
9383f96f7b3SArtur Pilipenko       return false;
93906408758SMircea Trofin     // Bail out the moment we cross the threshold. This means we'll under-count
94006408758SMircea Trofin     // the cost, but only when undercounting doesn't matter.
9413f96f7b3SArtur Pilipenko     if (Cost < Threshold)
9423f96f7b3SArtur Pilipenko       return false;
9433f96f7b3SArtur Pilipenko     DecidedByCostThreshold = true;
9443f96f7b3SArtur Pilipenko     return true;
94506408758SMircea Trofin   }
94606408758SMircea Trofin 
onLoadEliminationOpportunity()94706408758SMircea Trofin   void onLoadEliminationOpportunity() override {
94806408758SMircea Trofin     LoadEliminationCost += InlineConstants::InstrCost;
94906408758SMircea Trofin   }
95006408758SMircea Trofin 
onAnalysisStart()95106408758SMircea Trofin   InlineResult onAnalysisStart() override {
95206408758SMircea Trofin     // Perform some tweaks to the cost and threshold based on the direct
95306408758SMircea Trofin     // callsite information.
95406408758SMircea Trofin 
95506408758SMircea Trofin     // We want to more aggressively inline vector-dense kernels, so up the
95606408758SMircea Trofin     // threshold, and we'll lower it if the % of vector instructions gets too
95706408758SMircea Trofin     // low. Note that these bonuses are some what arbitrary and evolved over
95806408758SMircea Trofin     // time by accident as much as because they are principled bonuses.
95906408758SMircea Trofin     //
96006408758SMircea Trofin     // FIXME: It would be nice to remove all such bonuses. At least it would be
96106408758SMircea Trofin     // nice to base the bonus values on something more scientific.
96206408758SMircea Trofin     assert(NumInstructions == 0);
96306408758SMircea Trofin     assert(NumVectorInstructions == 0);
96406408758SMircea Trofin 
96506408758SMircea Trofin     // Update the threshold based on callsite properties
96606408758SMircea Trofin     updateThreshold(CandidateCall, F);
96706408758SMircea Trofin 
96806408758SMircea Trofin     // While Threshold depends on commandline options that can take negative
96906408758SMircea Trofin     // values, we want to enforce the invariant that the computed threshold and
97006408758SMircea Trofin     // bonuses are non-negative.
97106408758SMircea Trofin     assert(Threshold >= 0);
97206408758SMircea Trofin     assert(SingleBBBonus >= 0);
97306408758SMircea Trofin     assert(VectorBonus >= 0);
97406408758SMircea Trofin 
97506408758SMircea Trofin     // Speculatively apply all possible bonuses to Threshold. If cost exceeds
97606408758SMircea Trofin     // this Threshold any time, and cost cannot decrease, we can stop processing
97706408758SMircea Trofin     // the rest of the function body.
97806408758SMircea Trofin     Threshold += (SingleBBBonus + VectorBonus);
97906408758SMircea Trofin 
98006408758SMircea Trofin     // Give out bonuses for the callsite, as the instructions setting them up
98106408758SMircea Trofin     // will be gone after inlining.
98206408758SMircea Trofin     addCost(-getCallsiteCost(this->CandidateCall, DL));
98306408758SMircea Trofin 
98406408758SMircea Trofin     // If this function uses the coldcc calling convention, prefer not to inline
98506408758SMircea Trofin     // it.
98606408758SMircea Trofin     if (F.getCallingConv() == CallingConv::Cold)
98706408758SMircea Trofin       Cost += InlineConstants::ColdccPenalty;
98806408758SMircea Trofin 
989b7e7f4e1SDawid Jurczak     LLVM_DEBUG(dbgs() << "      Initial cost: " << Cost << "\n");
990b7e7f4e1SDawid Jurczak 
99106408758SMircea Trofin     // Check if we're done. This can happen due to bonuses and penalties.
99206408758SMircea Trofin     if (Cost >= Threshold && !ComputeFullInlineCost)
9935466597fSMircea Trofin       return InlineResult::failure("high cost");
99406408758SMircea Trofin 
9955466597fSMircea Trofin     return InlineResult::success();
99606408758SMircea Trofin   }
99706408758SMircea Trofin 
99806408758SMircea Trofin public:
InlineCostCallAnalyzer(Function & Callee,CallBase & Call,const InlineParams & Params,const TargetTransformInfo & TTI,function_ref<AssumptionCache & (Function &)> GetAssumptionCache,function_ref<BlockFrequencyInfo & (Function &)> GetBFI=nullptr,ProfileSummaryInfo * PSI=nullptr,OptimizationRemarkEmitter * ORE=nullptr,bool BoostIndirect=true,bool IgnoreThreshold=false)99906408758SMircea Trofin   InlineCostCallAnalyzer(
100008e2386dSMircea Trofin       Function &Callee, CallBase &Call, const InlineParams &Params,
100106408758SMircea Trofin       const TargetTransformInfo &TTI,
100208e2386dSMircea Trofin       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
100308e2386dSMircea Trofin       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
100408e2386dSMircea Trofin       ProfileSummaryInfo *PSI = nullptr,
100508e2386dSMircea Trofin       OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
10068a4013edSMircea Trofin       bool IgnoreThreshold = false)
100708e2386dSMircea Trofin       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI, ORE),
100806408758SMircea Trofin         ComputeFullInlineCost(OptComputeFullInlineCost ||
100965cd3cbbSKazu Hirata                               Params.ComputeFullInlineCost || ORE ||
101065cd3cbbSKazu Hirata                               isCostBenefitAnalysisEnabled()),
101106408758SMircea Trofin         Params(Params), Threshold(Params.DefaultThreshold),
10121022b5ebSKirill Naumov         BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
10139895c701SKazu Hirata         CostBenefitAnalysisEnabled(isCostBenefitAnalysisEnabled()),
1014f7fff46aSWenlei He         Writer(this) {
10157a47ee51SKazu Hirata     AllowRecursiveCall = *Params.AllowRecursiveCall;
1016f7fff46aSWenlei He   }
1017c965fd94SKirill Naumov 
10181022b5ebSKirill Naumov   /// Annotation Writer for instruction details
10191022b5ebSKirill Naumov   InlineCostAnnotationWriter Writer;
1020c965fd94SKirill Naumov 
102106408758SMircea Trofin   void dump();
102206408758SMircea Trofin 
1023ca899bf9SKirill Naumov   // Prints the same analysis as dump(), but its definition is not dependent
1024ca899bf9SKirill Naumov   // on the build.
1025ecd25edfSArthur Eubanks   void print(raw_ostream &OS);
1026ca899bf9SKirill Naumov 
getCostDetails(const Instruction * I)10271022b5ebSKirill Naumov   Optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
10281022b5ebSKirill Naumov     if (InstructionCostDetailMap.find(I) != InstructionCostDetailMap.end())
10291022b5ebSKirill Naumov       return InstructionCostDetailMap[I];
10301022b5ebSKirill Naumov     return None;
10311022b5ebSKirill Naumov   }
10321022b5ebSKirill Naumov 
10333a3cb929SKazu Hirata   virtual ~InlineCostCallAnalyzer() = default;
getThreshold() const1034cfc4def8SJacob Hegna   int getThreshold() const { return Threshold; }
getCost() const1035cfc4def8SJacob Hegna   int getCost() const { return Cost; }
getCostBenefitPair()10364bdfea2cSLiqiang Tao   Optional<CostBenefitPair> getCostBenefitPair() { return CostBenefit; }
wasDecidedByCostBenefit() const1037cfc4def8SJacob Hegna   bool wasDecidedByCostBenefit() const { return DecidedByCostBenefit; }
wasDecidedByCostThreshold() const10383f96f7b3SArtur Pilipenko   bool wasDecidedByCostThreshold() const { return DecidedByCostThreshold; }
103906408758SMircea Trofin };
104099f00635SJacob Hegna 
104199f00635SJacob Hegna class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
104299f00635SJacob Hegna private:
104399f00635SJacob Hegna   InlineCostFeatures Cost = {};
104499f00635SJacob Hegna 
104599f00635SJacob Hegna   // FIXME: These constants are taken from the heuristic-based cost visitor.
104699f00635SJacob Hegna   // These should be removed entirely in a later revision to avoid reliance on
104799f00635SJacob Hegna   // heuristics in the ML inliner.
104899f00635SJacob Hegna   static constexpr int JTCostMultiplier = 4;
104999f00635SJacob Hegna   static constexpr int CaseClusterCostMultiplier = 2;
105099f00635SJacob Hegna   static constexpr int SwitchCostMultiplier = 2;
105199f00635SJacob Hegna 
105299f00635SJacob Hegna   // FIXME: These are taken from the heuristic-based cost visitor: we should
105399f00635SJacob Hegna   // eventually abstract these to the CallAnalyzer to avoid duplication.
105499f00635SJacob Hegna   unsigned SROACostSavingOpportunities = 0;
105599f00635SJacob Hegna   int VectorBonus = 0;
105699f00635SJacob Hegna   int SingleBBBonus = 0;
105799f00635SJacob Hegna   int Threshold = 5;
105899f00635SJacob Hegna 
105999f00635SJacob Hegna   DenseMap<AllocaInst *, unsigned> SROACosts;
106099f00635SJacob Hegna 
increment(InlineCostFeatureIndex Feature,int64_t Delta=1)106199f00635SJacob Hegna   void increment(InlineCostFeatureIndex Feature, int64_t Delta = 1) {
106299f00635SJacob Hegna     Cost[static_cast<size_t>(Feature)] += Delta;
106399f00635SJacob Hegna   }
106499f00635SJacob Hegna 
set(InlineCostFeatureIndex Feature,int64_t Value)106599f00635SJacob Hegna   void set(InlineCostFeatureIndex Feature, int64_t Value) {
106699f00635SJacob Hegna     Cost[static_cast<size_t>(Feature)] = Value;
106799f00635SJacob Hegna   }
106899f00635SJacob Hegna 
onDisableSROA(AllocaInst * Arg)106999f00635SJacob Hegna   void onDisableSROA(AllocaInst *Arg) override {
107099f00635SJacob Hegna     auto CostIt = SROACosts.find(Arg);
107199f00635SJacob Hegna     if (CostIt == SROACosts.end())
107299f00635SJacob Hegna       return;
107399f00635SJacob Hegna 
107499f00635SJacob Hegna     increment(InlineCostFeatureIndex::SROALosses, CostIt->second);
107599f00635SJacob Hegna     SROACostSavingOpportunities -= CostIt->second;
107699f00635SJacob Hegna     SROACosts.erase(CostIt);
107799f00635SJacob Hegna   }
107899f00635SJacob Hegna 
onDisableLoadElimination()107999f00635SJacob Hegna   void onDisableLoadElimination() override {
108099f00635SJacob Hegna     set(InlineCostFeatureIndex::LoadElimination, 1);
108199f00635SJacob Hegna   }
108299f00635SJacob Hegna 
onCallPenalty()108399f00635SJacob Hegna   void onCallPenalty() override {
108446c03668SPhilipp Krones     increment(InlineCostFeatureIndex::CallPenalty, CallPenalty);
108599f00635SJacob Hegna   }
108699f00635SJacob Hegna 
onCallArgumentSetup(const CallBase & Call)108799f00635SJacob Hegna   void onCallArgumentSetup(const CallBase &Call) override {
108899f00635SJacob Hegna     increment(InlineCostFeatureIndex::CallArgumentSetup,
108999f00635SJacob Hegna               Call.arg_size() * InlineConstants::InstrCost);
109099f00635SJacob Hegna   }
109199f00635SJacob Hegna 
onLoadRelativeIntrinsic()109299f00635SJacob Hegna   void onLoadRelativeIntrinsic() override {
109399f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoadRelativeIntrinsic,
109499f00635SJacob Hegna               3 * InlineConstants::InstrCost);
109599f00635SJacob Hegna   }
109699f00635SJacob Hegna 
onLoweredCall(Function * F,CallBase & Call,bool IsIndirectCall)109799f00635SJacob Hegna   void onLoweredCall(Function *F, CallBase &Call,
109899f00635SJacob Hegna                      bool IsIndirectCall) override {
109999f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoweredCallArgSetup,
110099f00635SJacob Hegna               Call.arg_size() * InlineConstants::InstrCost);
110199f00635SJacob Hegna 
110299f00635SJacob Hegna     if (IsIndirectCall) {
110399f00635SJacob Hegna       InlineParams IndirectCallParams = {/* DefaultThreshold*/ 0,
110499f00635SJacob Hegna                                          /*HintThreshold*/ {},
110599f00635SJacob Hegna                                          /*ColdThreshold*/ {},
110699f00635SJacob Hegna                                          /*OptSizeThreshold*/ {},
110799f00635SJacob Hegna                                          /*OptMinSizeThreshold*/ {},
110899f00635SJacob Hegna                                          /*HotCallSiteThreshold*/ {},
110999f00635SJacob Hegna                                          /*LocallyHotCallSiteThreshold*/ {},
111099f00635SJacob Hegna                                          /*ColdCallSiteThreshold*/ {},
111199f00635SJacob Hegna                                          /*ComputeFullInlineCost*/ true,
111299f00635SJacob Hegna                                          /*EnableDeferral*/ true};
111399f00635SJacob Hegna       IndirectCallParams.DefaultThreshold =
111499f00635SJacob Hegna           InlineConstants::IndirectCallThreshold;
111599f00635SJacob Hegna 
111699f00635SJacob Hegna       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
111799f00635SJacob Hegna                                 GetAssumptionCache, GetBFI, PSI, ORE, false,
111899f00635SJacob Hegna                                 true);
111999f00635SJacob Hegna       if (CA.analyze().isSuccess()) {
112099f00635SJacob Hegna         increment(InlineCostFeatureIndex::NestedInlineCostEstimate,
112199f00635SJacob Hegna                   CA.getCost());
112299f00635SJacob Hegna         increment(InlineCostFeatureIndex::NestedInlines, 1);
112399f00635SJacob Hegna       }
112499f00635SJacob Hegna     } else {
112599f00635SJacob Hegna       onCallPenalty();
112699f00635SJacob Hegna     }
112799f00635SJacob Hegna   }
112899f00635SJacob Hegna 
onFinalizeSwitch(unsigned JumpTableSize,unsigned NumCaseCluster)112999f00635SJacob Hegna   void onFinalizeSwitch(unsigned JumpTableSize,
113099f00635SJacob Hegna                         unsigned NumCaseCluster) override {
113199f00635SJacob Hegna 
113299f00635SJacob Hegna     if (JumpTableSize) {
113399f00635SJacob Hegna       int64_t JTCost =
113499f00635SJacob Hegna           static_cast<int64_t>(JumpTableSize) * InlineConstants::InstrCost +
113599f00635SJacob Hegna           JTCostMultiplier * InlineConstants::InstrCost;
113699f00635SJacob Hegna       increment(InlineCostFeatureIndex::JumpTablePenalty, JTCost);
113799f00635SJacob Hegna       return;
113899f00635SJacob Hegna     }
113999f00635SJacob Hegna 
114099f00635SJacob Hegna     if (NumCaseCluster <= 3) {
114199f00635SJacob Hegna       increment(InlineCostFeatureIndex::CaseClusterPenalty,
114299f00635SJacob Hegna                 NumCaseCluster * CaseClusterCostMultiplier *
114399f00635SJacob Hegna                     InlineConstants::InstrCost);
114499f00635SJacob Hegna       return;
114599f00635SJacob Hegna     }
114699f00635SJacob Hegna 
114799f00635SJacob Hegna     int64_t ExpectedNumberOfCompare =
114899f00635SJacob Hegna         getExpectedNumberOfCompare(NumCaseCluster);
114999f00635SJacob Hegna 
115099f00635SJacob Hegna     int64_t SwitchCost = ExpectedNumberOfCompare * SwitchCostMultiplier *
115199f00635SJacob Hegna                          InlineConstants::InstrCost;
115299f00635SJacob Hegna     increment(InlineCostFeatureIndex::SwitchPenalty, SwitchCost);
115399f00635SJacob Hegna   }
115499f00635SJacob Hegna 
onMissedSimplification()115599f00635SJacob Hegna   void onMissedSimplification() override {
115699f00635SJacob Hegna     increment(InlineCostFeatureIndex::UnsimplifiedCommonInstructions,
115799f00635SJacob Hegna               InlineConstants::InstrCost);
115899f00635SJacob Hegna   }
115999f00635SJacob Hegna 
onInitializeSROAArg(AllocaInst * Arg)116099f00635SJacob Hegna   void onInitializeSROAArg(AllocaInst *Arg) override { SROACosts[Arg] = 0; }
onAggregateSROAUse(AllocaInst * Arg)116199f00635SJacob Hegna   void onAggregateSROAUse(AllocaInst *Arg) override {
116299f00635SJacob Hegna     SROACosts.find(Arg)->second += InlineConstants::InstrCost;
116399f00635SJacob Hegna     SROACostSavingOpportunities += InlineConstants::InstrCost;
116499f00635SJacob Hegna   }
116599f00635SJacob Hegna 
onBlockAnalyzed(const BasicBlock * BB)116699f00635SJacob Hegna   void onBlockAnalyzed(const BasicBlock *BB) override {
116799f00635SJacob Hegna     if (BB->getTerminator()->getNumSuccessors() > 1)
116899f00635SJacob Hegna       set(InlineCostFeatureIndex::IsMultipleBlocks, 1);
116999f00635SJacob Hegna     Threshold -= SingleBBBonus;
117099f00635SJacob Hegna   }
117199f00635SJacob Hegna 
finalizeAnalysis()117299f00635SJacob Hegna   InlineResult finalizeAnalysis() override {
117399f00635SJacob Hegna     auto *Caller = CandidateCall.getFunction();
117499f00635SJacob Hegna     if (Caller->hasMinSize()) {
117599f00635SJacob Hegna       DominatorTree DT(F);
117699f00635SJacob Hegna       LoopInfo LI(DT);
117799f00635SJacob Hegna       for (Loop *L : LI) {
117899f00635SJacob Hegna         // Ignore loops that will not be executed
117999f00635SJacob Hegna         if (DeadBlocks.count(L->getHeader()))
118099f00635SJacob Hegna           continue;
118199f00635SJacob Hegna         increment(InlineCostFeatureIndex::NumLoops,
118246c03668SPhilipp Krones                   InlineConstants::LoopPenalty);
118399f00635SJacob Hegna       }
118499f00635SJacob Hegna     }
118599f00635SJacob Hegna     set(InlineCostFeatureIndex::DeadBlocks, DeadBlocks.size());
118699f00635SJacob Hegna     set(InlineCostFeatureIndex::SimplifiedInstructions,
118799f00635SJacob Hegna         NumInstructionsSimplified);
118899f00635SJacob Hegna     set(InlineCostFeatureIndex::ConstantArgs, NumConstantArgs);
118999f00635SJacob Hegna     set(InlineCostFeatureIndex::ConstantOffsetPtrArgs,
119099f00635SJacob Hegna         NumConstantOffsetPtrArgs);
119199f00635SJacob Hegna     set(InlineCostFeatureIndex::SROASavings, SROACostSavingOpportunities);
119299f00635SJacob Hegna 
119399f00635SJacob Hegna     if (NumVectorInstructions <= NumInstructions / 10)
11941f3e90e1SJacob Hegna       Threshold -= VectorBonus;
119599f00635SJacob Hegna     else if (NumVectorInstructions <= NumInstructions / 2)
11961f3e90e1SJacob Hegna       Threshold -= VectorBonus / 2;
119799f00635SJacob Hegna 
119899f00635SJacob Hegna     set(InlineCostFeatureIndex::Threshold, Threshold);
119999f00635SJacob Hegna 
120099f00635SJacob Hegna     return InlineResult::success();
120199f00635SJacob Hegna   }
120299f00635SJacob Hegna 
shouldStop()120399f00635SJacob Hegna   bool shouldStop() override { return false; }
120499f00635SJacob Hegna 
onLoadEliminationOpportunity()120599f00635SJacob Hegna   void onLoadEliminationOpportunity() override {
120699f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoadElimination, 1);
120799f00635SJacob Hegna   }
120899f00635SJacob Hegna 
onAnalysisStart()120999f00635SJacob Hegna   InlineResult onAnalysisStart() override {
121099f00635SJacob Hegna     increment(InlineCostFeatureIndex::CallSiteCost,
121199f00635SJacob Hegna               -1 * getCallsiteCost(this->CandidateCall, DL));
121299f00635SJacob Hegna 
121399f00635SJacob Hegna     set(InlineCostFeatureIndex::ColdCcPenalty,
121499f00635SJacob Hegna         (F.getCallingConv() == CallingConv::Cold));
121599f00635SJacob Hegna 
1216c0022b4bSJun Ma     set(InlineCostFeatureIndex::LastCallToStaticBonus,
1217c0022b4bSJun Ma         (F.hasLocalLinkage() && F.hasOneLiveUse() &&
1218c0022b4bSJun Ma          &F == CandidateCall.getCalledFunction()));
1219c0022b4bSJun Ma 
122099f00635SJacob Hegna     // FIXME: we shouldn't repeat this logic in both the Features and Cost
122199f00635SJacob Hegna     // analyzer - instead, we should abstract it to a common method in the
122299f00635SJacob Hegna     // CallAnalyzer
122399f00635SJacob Hegna     int SingleBBBonusPercent = 50;
122499f00635SJacob Hegna     int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
122599f00635SJacob Hegna     Threshold += TTI.adjustInliningThreshold(&CandidateCall);
122699f00635SJacob Hegna     Threshold *= TTI.getInliningThresholdMultiplier();
122799f00635SJacob Hegna     SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
122899f00635SJacob Hegna     VectorBonus = Threshold * VectorBonusPercent / 100;
122999f00635SJacob Hegna     Threshold += (SingleBBBonus + VectorBonus);
123099f00635SJacob Hegna 
123199f00635SJacob Hegna     return InlineResult::success();
123299f00635SJacob Hegna   }
123399f00635SJacob Hegna 
123499f00635SJacob Hegna public:
InlineCostFeaturesAnalyzer(const TargetTransformInfo & TTI,function_ref<AssumptionCache & (Function &)> & GetAssumptionCache,function_ref<BlockFrequencyInfo & (Function &)> GetBFI,ProfileSummaryInfo * PSI,OptimizationRemarkEmitter * ORE,Function & Callee,CallBase & Call)123599f00635SJacob Hegna   InlineCostFeaturesAnalyzer(
123699f00635SJacob Hegna       const TargetTransformInfo &TTI,
123799f00635SJacob Hegna       function_ref<AssumptionCache &(Function &)> &GetAssumptionCache,
123899f00635SJacob Hegna       function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
123999f00635SJacob Hegna       ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
124099f00635SJacob Hegna       CallBase &Call)
124199f00635SJacob Hegna       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI) {}
124299f00635SJacob Hegna 
features() const124399f00635SJacob Hegna   const InlineCostFeatures &features() const { return Cost; }
124499f00635SJacob Hegna };
124599f00635SJacob Hegna 
12467adc3a2bSChandler Carruth } // namespace
12477adc3a2bSChandler Carruth 
12485f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument.
isAllocaDerivedArg(Value * V)12497adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
12507adc3a2bSChandler Carruth   return SROAArgValues.count(V);
12517adc3a2bSChandler Carruth }
12527adc3a2bSChandler Carruth 
disableSROAForArg(AllocaInst * SROAArg)125306408758SMircea Trofin void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
125406408758SMircea Trofin   onDisableSROA(SROAArg);
12552e42cc7aSMircea Trofin   EnabledSROAAllocas.erase(SROAArg);
1256338a6016SMircea Trofin   disableLoadElimination();
1257338a6016SMircea Trofin }
1258c965fd94SKirill Naumov 
emitInstructionAnnot(const Instruction * I,formatted_raw_ostream & OS)12597b639f50SJacob Hegna void InlineCostAnnotationWriter::emitInstructionAnnot(
12607b639f50SJacob Hegna     const Instruction *I, formatted_raw_ostream &OS) {
1261c965fd94SKirill Naumov   // The cost of inlining of the given instruction is printed always.
1262c965fd94SKirill Naumov   // The threshold delta is printed only when it is non-zero. It happens
1263c965fd94SKirill Naumov   // when we decided to give a bonus at a particular instruction.
12641022b5ebSKirill Naumov   Optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
12651022b5ebSKirill Naumov   if (!Record)
12661022b5ebSKirill Naumov     OS << "; No analysis for the instruction";
12671022b5ebSKirill Naumov   else {
12681022b5ebSKirill Naumov     OS << "; cost before = " << Record->CostBefore
12691022b5ebSKirill Naumov        << ", cost after = " << Record->CostAfter
12701022b5ebSKirill Naumov        << ", threshold before = " << Record->ThresholdBefore
12711022b5ebSKirill Naumov        << ", threshold after = " << Record->ThresholdAfter << ", ";
12721022b5ebSKirill Naumov     OS << "cost delta = " << Record->getCostDelta();
12731022b5ebSKirill Naumov     if (Record->hasThresholdChanged())
12741022b5ebSKirill Naumov       OS << ", threshold delta = " << Record->getThresholdDelta();
12750383253cSKirill Naumov   }
12767f094f7fSKirill Naumov   auto C = ICCA->getSimplifiedValue(const_cast<Instruction *>(I));
12777f094f7fSKirill Naumov   if (C) {
12787f094f7fSKirill Naumov     OS << ", simplified to ";
12797a47ee51SKazu Hirata     (*C)->print(OS, true);
12807f094f7fSKirill Naumov   }
1281c965fd94SKirill Naumov   OS << "\n";
1282c965fd94SKirill Naumov }
1283c965fd94SKirill Naumov 
12845f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it.
disableSROA(Value * V)12857adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
128606408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
128706408758SMircea Trofin     disableSROAForArg(SROAArg);
1288338a6016SMircea Trofin   }
12897adc3a2bSChandler Carruth }
12907adc3a2bSChandler Carruth 
disableLoadElimination()1291a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() {
1292a4461515SHaicheng Wu   if (EnableLoadElimination) {
129306408758SMircea Trofin     onDisableLoadElimination();
1294a4461515SHaicheng Wu     EnableLoadElimination = false;
1295a4461515SHaicheng Wu   }
1296a4461515SHaicheng Wu }
1297a4461515SHaicheng Wu 
12985f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible.
12997adc3a2bSChandler Carruth ///
13007adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
13017adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
accumulateGEPOffset(GEPOperator & GEP,APInt & Offset)13027adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
1303945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
13047adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
13057adc3a2bSChandler Carruth 
13067adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
13077adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
13087adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
13097adc3a2bSChandler Carruth     if (!OpC)
13107adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
13117adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
13127adc3a2bSChandler Carruth     if (!OpC)
13137adc3a2bSChandler Carruth       return false;
1314567556aaSChad Rosier     if (OpC->isZero())
1315567556aaSChad Rosier       continue;
13167adc3a2bSChandler Carruth 
13177adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
1318ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
13197adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
13207adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
13217adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
13227adc3a2bSChandler Carruth       continue;
13237adc3a2bSChandler Carruth     }
13247adc3a2bSChandler Carruth 
13257adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
13267adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
13277adc3a2bSChandler Carruth   }
13287adc3a2bSChandler Carruth   return true;
13297adc3a2bSChandler Carruth }
13307adc3a2bSChandler Carruth 
13315f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free.
1332201b191bSHaicheng Wu ///
1333201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
isGEPFree(GetElementPtrInst & GEP)1334201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
133561c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
133661c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
133791aff1d8SNick Desaulniers   for (const Use &Op : GEP.indices())
133891aff1d8SNick Desaulniers     if (Constant *SimpleOp = SimplifiedValues.lookup(Op))
133961c1bd5aSEvgeny Astigeevich       Operands.push_back(SimpleOp);
1340201b191bSHaicheng Wu     else
134191aff1d8SNick Desaulniers       Operands.push_back(Op);
13423ccbd4f3SSander de Smalen   return TTI.getUserCost(&GEP, Operands,
13433ccbd4f3SSander de Smalen                          TargetTransformInfo::TCK_SizeAndLatency) ==
13443ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
1345201b191bSHaicheng Wu }
1346201b191bSHaicheng Wu 
visitAlloca(AllocaInst & I)13477adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
1348a3a798d4SArthur Eubanks   disableSROA(I.getOperand(0));
1349a3a798d4SArthur Eubanks 
13507adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
13510f153424SSanjay Patel   // alloca and handle that case.
13527adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
13530f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
13540f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1355090c108dSAmara Emerson       // Sometimes a dynamic alloca could be converted into a static alloca
1356090c108dSAmara Emerson       // after this constant prop, and become a huge static alloca on an
1357090c108dSAmara Emerson       // unconditional CFG path. Avoid inlining if this is going to happen above
1358090c108dSAmara Emerson       // a threshold.
1359090c108dSAmara Emerson       // FIXME: If the threshold is removed or lowered too much, we could end up
1360090c108dSAmara Emerson       // being too pessimistic and prevent inlining non-problematic code. This
1361090c108dSAmara Emerson       // could result in unintended perf regressions. A better overall strategy
1362090c108dSAmara Emerson       // is needed to track stack usage during inlining.
13637adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
136422eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
13657b639f50SJacob Hegna           AllocSize->getLimitedValue(),
13667b639f50SJacob Hegna           DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
1367a3a798d4SArthur Eubanks       if (AllocatedSize > InlineConstants::MaxSimplifiedDynamicAllocaToInline)
1368090c108dSAmara Emerson         HasDynamicAlloca = true;
1369090c108dSAmara Emerson       return false;
1370090c108dSAmara Emerson     }
13717adc3a2bSChandler Carruth   }
13727adc3a2bSChandler Carruth 
13737adc3a2bSChandler Carruth   // Accumulate the allocated size.
13747adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
13757adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
13765a956c85SMircea Trofin     AllocatedSize =
13772ccde3c9SCullen Rhodes         SaturatingAdd(DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
13787adc3a2bSChandler Carruth   }
13797adc3a2bSChandler Carruth 
13807adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
13817adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
13827adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
13837adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
1384a3a798d4SArthur Eubanks   if (!I.isStaticAlloca())
13857adc3a2bSChandler Carruth     HasDynamicAlloca = true;
1386a3a798d4SArthur Eubanks 
13877adc3a2bSChandler Carruth   return false;
13887adc3a2bSChandler Carruth }
13897adc3a2bSChandler Carruth 
visitPHI(PHINode & I)13907adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
13917adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
13927adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
13937adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
13947adc3a2bSChandler Carruth 
13957adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
139677f32994SBjorn Pettersson   // FIXME: Pointer sizes may differ between different address spaces, so do we
139777f32994SBjorn Pettersson   // need to use correct address space in the call to getPointerSizeInBits here?
139877f32994SBjorn Pettersson   // Or could we skip the getPointerSizeInBits call completely? As far as I can
139977f32994SBjorn Pettersson   // see the ZeroOffset is used as a dummy value, so we can probably use any
140077f32994SBjorn Pettersson   // bit width for the ZeroOffset?
1401735f4671SChris Lattner   APInt ZeroOffset = APInt::getZero(DL.getPointerSizeInBits(0));
14023739e14aSHaicheng Wu   bool CheckSROA = I.getType()->isPointerTy();
14033739e14aSHaicheng Wu 
14043739e14aSHaicheng Wu   // Track the constant or pointer with constant offset we've seen so far.
14053739e14aSHaicheng Wu   Constant *FirstC = nullptr;
14063739e14aSHaicheng Wu   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
14073739e14aSHaicheng Wu   Value *FirstV = nullptr;
14083739e14aSHaicheng Wu 
14093739e14aSHaicheng Wu   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
14103739e14aSHaicheng Wu     BasicBlock *Pred = I.getIncomingBlock(i);
14113739e14aSHaicheng Wu     // If the incoming block is dead, skip the incoming block.
14123739e14aSHaicheng Wu     if (DeadBlocks.count(Pred))
14133739e14aSHaicheng Wu       continue;
14143739e14aSHaicheng Wu     // If the parent block of phi is not the known successor of the incoming
14153739e14aSHaicheng Wu     // block, skip the incoming block.
14163739e14aSHaicheng Wu     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
14173739e14aSHaicheng Wu     if (KnownSuccessor && KnownSuccessor != I.getParent())
14183739e14aSHaicheng Wu       continue;
14193739e14aSHaicheng Wu 
14203739e14aSHaicheng Wu     Value *V = I.getIncomingValue(i);
14213739e14aSHaicheng Wu     // If the incoming value is this phi itself, skip the incoming value.
14223739e14aSHaicheng Wu     if (&I == V)
14233739e14aSHaicheng Wu       continue;
14243739e14aSHaicheng Wu 
14253739e14aSHaicheng Wu     Constant *C = dyn_cast<Constant>(V);
14263739e14aSHaicheng Wu     if (!C)
14273739e14aSHaicheng Wu       C = SimplifiedValues.lookup(V);
14283739e14aSHaicheng Wu 
14293739e14aSHaicheng Wu     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
14303739e14aSHaicheng Wu     if (!C && CheckSROA)
14313739e14aSHaicheng Wu       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
14323739e14aSHaicheng Wu 
14333739e14aSHaicheng Wu     if (!C && !BaseAndOffset.first)
14343739e14aSHaicheng Wu       // The incoming value is neither a constant nor a pointer with constant
14353739e14aSHaicheng Wu       // offset, exit early.
14363739e14aSHaicheng Wu       return true;
14373739e14aSHaicheng Wu 
14383739e14aSHaicheng Wu     if (FirstC) {
14393739e14aSHaicheng Wu       if (FirstC == C)
14403739e14aSHaicheng Wu         // If we've seen a constant incoming value before and it is the same
14413739e14aSHaicheng Wu         // constant we see this time, continue checking the next incoming value.
14423739e14aSHaicheng Wu         continue;
14433739e14aSHaicheng Wu       // Otherwise early exit because we either see a different constant or saw
14443739e14aSHaicheng Wu       // a constant before but we have a pointer with constant offset this time.
14453739e14aSHaicheng Wu       return true;
14463739e14aSHaicheng Wu     }
14473739e14aSHaicheng Wu 
14483739e14aSHaicheng Wu     if (FirstV) {
14493739e14aSHaicheng Wu       // The same logic as above, but check pointer with constant offset here.
14503739e14aSHaicheng Wu       if (FirstBaseAndOffset == BaseAndOffset)
14513739e14aSHaicheng Wu         continue;
14523739e14aSHaicheng Wu       return true;
14533739e14aSHaicheng Wu     }
14543739e14aSHaicheng Wu 
14553739e14aSHaicheng Wu     if (C) {
14563739e14aSHaicheng Wu       // This is the 1st time we've seen a constant, record it.
14573739e14aSHaicheng Wu       FirstC = C;
14583739e14aSHaicheng Wu       continue;
14593739e14aSHaicheng Wu     }
14603739e14aSHaicheng Wu 
14613739e14aSHaicheng Wu     // The remaining case is that this is the 1st time we've seen a pointer with
14623739e14aSHaicheng Wu     // constant offset, record it.
14633739e14aSHaicheng Wu     FirstV = V;
14643739e14aSHaicheng Wu     FirstBaseAndOffset = BaseAndOffset;
14653739e14aSHaicheng Wu   }
14663739e14aSHaicheng Wu 
14673739e14aSHaicheng Wu   // Check if we can map phi to a constant.
14683739e14aSHaicheng Wu   if (FirstC) {
14693739e14aSHaicheng Wu     SimplifiedValues[&I] = FirstC;
14703739e14aSHaicheng Wu     return true;
14713739e14aSHaicheng Wu   }
14723739e14aSHaicheng Wu 
14733739e14aSHaicheng Wu   // Check if we can map phi to a pointer with constant offset.
14743739e14aSHaicheng Wu   if (FirstBaseAndOffset.first) {
14753739e14aSHaicheng Wu     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
14763739e14aSHaicheng Wu 
147706408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
14783739e14aSHaicheng Wu       SROAArgValues[&I] = SROAArg;
14793739e14aSHaicheng Wu   }
14803739e14aSHaicheng Wu 
14817adc3a2bSChandler Carruth   return true;
14827adc3a2bSChandler Carruth }
14837adc3a2bSChandler Carruth 
14845f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers.
1485d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs.
1486d3558b5dSEvgeny Astigeevich ///
1487d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded.
canFoldInboundsGEP(GetElementPtrInst & I)1488d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1489d3558b5dSEvgeny Astigeevich   // Check if we have a base + offset for the pointer.
1490d3558b5dSEvgeny Astigeevich   std::pair<Value *, APInt> BaseAndOffset =
1491d3558b5dSEvgeny Astigeevich       ConstantOffsetPtrs.lookup(I.getPointerOperand());
1492d3558b5dSEvgeny Astigeevich   if (!BaseAndOffset.first)
1493d3558b5dSEvgeny Astigeevich     return false;
1494d3558b5dSEvgeny Astigeevich 
1495d3558b5dSEvgeny Astigeevich   // Check if the offset of this GEP is constant, and if so accumulate it
1496d3558b5dSEvgeny Astigeevich   // into Offset.
1497d3558b5dSEvgeny Astigeevich   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1498d3558b5dSEvgeny Astigeevich     return false;
1499d3558b5dSEvgeny Astigeevich 
1500d3558b5dSEvgeny Astigeevich   // Add the result as a new mapping to Base + Offset.
1501d3558b5dSEvgeny Astigeevich   ConstantOffsetPtrs[&I] = BaseAndOffset;
1502d3558b5dSEvgeny Astigeevich 
1503d3558b5dSEvgeny Astigeevich   return true;
1504d3558b5dSEvgeny Astigeevich }
1505d3558b5dSEvgeny Astigeevich 
visitGetElementPtr(GetElementPtrInst & I)15067adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
150706408758SMircea Trofin   auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
15087adc3a2bSChandler Carruth 
1509a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
1510a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
151191aff1d8SNick Desaulniers     for (const Use &Op : GEP.indices())
151291aff1d8SNick Desaulniers       if (!isa<Constant>(Op) && !SimplifiedValues.lookup(Op))
1513a8b9cdc9SEaswaran Raman         return false;
1514a8b9cdc9SEaswaran Raman     return true;
1515a8b9cdc9SEaswaran Raman   };
1516a8b9cdc9SEaswaran Raman 
1517d48c7859SKirill Naumov   if (!DisableGEPConstOperand)
151854fcde42SNikita Popov     if (simplifyInstruction(I))
1519d48c7859SKirill Naumov       return true;
1520d48c7859SKirill Naumov 
1521d3558b5dSEvgeny Astigeevich   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
152206408758SMircea Trofin     if (SROAArg)
15237adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
15247adc3a2bSChandler Carruth 
15257adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
15267adc3a2bSChandler Carruth     return true;
15277adc3a2bSChandler Carruth   }
15287adc3a2bSChandler Carruth 
15297adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
153006408758SMircea Trofin   if (SROAArg)
153106408758SMircea Trofin     disableSROAForArg(SROAArg);
1532201b191bSHaicheng Wu   return isGEPFree(I);
15337adc3a2bSChandler Carruth }
15347adc3a2bSChandler Carruth 
1535617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
simplifyInstruction(Instruction & I)153654fcde42SNikita Popov bool CallAnalyzer::simplifyInstruction(Instruction &I) {
153754fcde42SNikita Popov   SmallVector<Constant *> COps;
1538617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
1539617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
15407adc3a2bSChandler Carruth     if (!COp)
1541617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
1542617f6364SEaswaran Raman     if (!COp)
1543617f6364SEaswaran Raman       return false;
1544617f6364SEaswaran Raman     COps.push_back(COp);
1545617f6364SEaswaran Raman   }
154654fcde42SNikita Popov   auto *C = ConstantFoldInstOperands(&I, COps, DL);
1547617f6364SEaswaran Raman   if (!C)
1548617f6364SEaswaran Raman     return false;
15497adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
15507adc3a2bSChandler Carruth   return true;
15517adc3a2bSChandler Carruth }
15527adc3a2bSChandler Carruth 
15539697f935SNick Desaulniers /// Try to simplify a call to llvm.is.constant.
15549697f935SNick Desaulniers ///
15559697f935SNick Desaulniers /// Duplicate the argument checking from CallAnalyzer::simplifyCallSite since
15569697f935SNick Desaulniers /// we expect calls of this specific intrinsic to be infrequent.
15579697f935SNick Desaulniers ///
15589697f935SNick Desaulniers /// FIXME: Given that we know CB's parent (F) caller
15599697f935SNick Desaulniers /// (CandidateCall->getParent()->getParent()), we might be able to determine
15609697f935SNick Desaulniers /// whether inlining F into F's caller would change how the call to
15619697f935SNick Desaulniers /// llvm.is.constant would evaluate.
simplifyIntrinsicCallIsConstant(CallBase & CB)15629697f935SNick Desaulniers bool CallAnalyzer::simplifyIntrinsicCallIsConstant(CallBase &CB) {
15639697f935SNick Desaulniers   Value *Arg = CB.getArgOperand(0);
15649697f935SNick Desaulniers   auto *C = dyn_cast<Constant>(Arg);
15659697f935SNick Desaulniers 
15669697f935SNick Desaulniers   if (!C)
15679697f935SNick Desaulniers     C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(Arg));
15689697f935SNick Desaulniers 
15699697f935SNick Desaulniers   Type *RT = CB.getFunctionType()->getReturnType();
15709697f935SNick Desaulniers   SimplifiedValues[&CB] = ConstantInt::get(RT, C ? 1 : 0);
15719697f935SNick Desaulniers   return true;
15729697f935SNick Desaulniers }
15739697f935SNick Desaulniers 
visitBitCast(BitCastInst & I)1574617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1575617f6364SEaswaran Raman   // Propagate constants through bitcasts.
157654fcde42SNikita Popov   if (simplifyInstruction(I))
1577617f6364SEaswaran Raman     return true;
1578617f6364SEaswaran Raman 
15797adc3a2bSChandler Carruth   // Track base/offsets through casts
1580567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
1581567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
15827adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
15837adc3a2bSChandler Carruth   if (BaseAndOffset.first)
15847adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
15857adc3a2bSChandler Carruth 
15867adc3a2bSChandler Carruth   // Also look for SROA candidates here.
158706408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
15887adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
15897adc3a2bSChandler Carruth 
15907adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
15917adc3a2bSChandler Carruth   return true;
15927adc3a2bSChandler Carruth }
15937adc3a2bSChandler Carruth 
visitPtrToInt(PtrToIntInst & I)15947adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
15957adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
159654fcde42SNikita Popov   if (simplifyInstruction(I))
15977adc3a2bSChandler Carruth     return true;
15987adc3a2bSChandler Carruth 
15997adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
16007adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
16017adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
160277f32994SBjorn Pettersson   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1603faf848acSMikael Holmen   if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1604567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
1605567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
16067adc3a2bSChandler Carruth     if (BaseAndOffset.first)
16077adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
16087adc3a2bSChandler Carruth   }
16097adc3a2bSChandler Carruth 
16107adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
16117adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
16127adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
16137adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
16147adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
16157adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
16167adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
161706408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
16187adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
16197adc3a2bSChandler Carruth 
16203ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
16213ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
16227adc3a2bSChandler Carruth }
16237adc3a2bSChandler Carruth 
visitIntToPtr(IntToPtrInst & I)16247adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
16257adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
162654fcde42SNikita Popov   if (simplifyInstruction(I))
16277adc3a2bSChandler Carruth     return true;
16287adc3a2bSChandler Carruth 
16297adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
16307adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
16317adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
16327adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
163377f32994SBjorn Pettersson   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
16347adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
16357adc3a2bSChandler Carruth     if (BaseAndOffset.first)
16367adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
16377adc3a2bSChandler Carruth   }
16387adc3a2bSChandler Carruth 
16397adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
164006408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(Op))
16417adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
16427adc3a2bSChandler Carruth 
16433ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
16443ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
16457adc3a2bSChandler Carruth }
16467adc3a2bSChandler Carruth 
visitCastInst(CastInst & I)16477adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
1648ab53c5e5SCraig Topper   // Propagate constants through casts.
164954fcde42SNikita Popov   if (simplifyInstruction(I))
16507adc3a2bSChandler Carruth     return true;
16517adc3a2bSChandler Carruth 
165210563e16SEric Christopher   // Disable SROA in the face of arbitrary casts we don't explicitly list
165310563e16SEric Christopher   // elsewhere.
16547adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
16557adc3a2bSChandler Carruth 
165639ed9a60SEli Friedman   // If this is a floating-point cast, and the target says this operation
165739ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
165839ed9a60SEli Friedman   // as such.
165939ed9a60SEli Friedman   switch (I.getOpcode()) {
166039ed9a60SEli Friedman   case Instruction::FPTrunc:
166139ed9a60SEli Friedman   case Instruction::FPExt:
166239ed9a60SEli Friedman   case Instruction::UIToFP:
166339ed9a60SEli Friedman   case Instruction::SIToFP:
166439ed9a60SEli Friedman   case Instruction::FPToUI:
166539ed9a60SEli Friedman   case Instruction::FPToSI:
166639ed9a60SEli Friedman     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
166706408758SMircea Trofin       onCallPenalty();
16684dc0b1acSReid Kleckner     break;
166939ed9a60SEli Friedman   default:
167039ed9a60SEli Friedman     break;
167139ed9a60SEli Friedman   }
167239ed9a60SEli Friedman 
16733ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
16743ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
16757adc3a2bSChandler Carruth }
16767adc3a2bSChandler Carruth 
paramHasAttr(Argument * A,Attribute::AttrKind Attr)16777adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1678652168a9SFedor Sergeev   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
16797adc3a2bSChandler Carruth }
16807adc3a2bSChandler Carruth 
isKnownNonNullInCallee(Value * V)16817adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
16827adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
16837adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
16847adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
16857adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
16867adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
16877adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
16887adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
16897adc3a2bSChandler Carruth       return true;
16907adc3a2bSChandler Carruth 
16917adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
16927adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
16937adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
16947adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
16957adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
16967adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
16977adc3a2bSChandler Carruth     // SROA firing.
16987adc3a2bSChandler Carruth     return true;
16997adc3a2bSChandler Carruth 
17007adc3a2bSChandler Carruth   return false;
17017adc3a2bSChandler Carruth }
17027adc3a2bSChandler Carruth 
allowSizeGrowth(CallBase & Call)1703652168a9SFedor Sergeev bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
17049a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
17059a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
17069a3fc17aSEaswaran Raman   // unless there is literally zero cost.
17079a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
17089a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
17099a3fc17aSEaswaran Raman   // beneficial :
17109a3fc17aSEaswaran Raman   // main() {
17119a3fc17aSEaswaran Raman   //   hot_call_1();
17129a3fc17aSEaswaran Raman   //   ...
17139a3fc17aSEaswaran Raman   //   hot_call_N()
17149a3fc17aSEaswaran Raman   //   exit(0);
17159a3fc17aSEaswaran Raman   // }
17169a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
17179a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
17189a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
1719652168a9SFedor Sergeev   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
17209a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
17219a3fc17aSEaswaran Raman       return false;
1722652168a9SFedor Sergeev   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
17239a3fc17aSEaswaran Raman     return false;
17249a3fc17aSEaswaran Raman 
17259a3fc17aSEaswaran Raman   return true;
17269a3fc17aSEaswaran Raman }
17279a3fc17aSEaswaran Raman 
isColdCallSite(CallBase & Call,BlockFrequencyInfo * CallerBFI)172806408758SMircea Trofin bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1729652168a9SFedor Sergeev                                             BlockFrequencyInfo *CallerBFI) {
1730c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
1731c5fa6358SEaswaran Raman   // determined based on that.
1732bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary())
1733ec73ae11SMircea Trofin     return PSI->isColdCallSite(Call, CallerBFI);
1734bba762a1SChandler Carruth 
1735bba762a1SChandler Carruth   // Otherwise we need BFI to be available.
1736c5fa6358SEaswaran Raman   if (!CallerBFI)
1737c5fa6358SEaswaran Raman     return false;
1738c5fa6358SEaswaran Raman 
1739bba762a1SChandler Carruth   // Determine if the callsite is cold relative to caller's entry. We could
1740bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1741bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1742bba762a1SChandler Carruth   // profiles.
1743c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
1744652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1745c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1746c5fa6358SEaswaran Raman   auto CallerEntryFreq =
1747652168a9SFedor Sergeev       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1748c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
1749c5fa6358SEaswaran Raman }
1750c5fa6358SEaswaran Raman 
1751974d4eeaSEaswaran Raman Optional<int>
getHotCallSiteThreshold(CallBase & Call,BlockFrequencyInfo * CallerBFI)175206408758SMircea Trofin InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1753974d4eeaSEaswaran Raman                                                 BlockFrequencyInfo *CallerBFI) {
1754bba762a1SChandler Carruth 
1755974d4eeaSEaswaran Raman   // If global profile summary is available, then callsite's hotness is
1756974d4eeaSEaswaran Raman   // determined based on that.
1757ec73ae11SMircea Trofin   if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1758bba762a1SChandler Carruth     return Params.HotCallSiteThreshold;
1759974d4eeaSEaswaran Raman 
1760bba762a1SChandler Carruth   // Otherwise we need BFI to be available and to have a locally hot callsite
1761bba762a1SChandler Carruth   // threshold.
1762bba762a1SChandler Carruth   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1763974d4eeaSEaswaran Raman     return None;
1764974d4eeaSEaswaran Raman 
1765bba762a1SChandler Carruth   // Determine if the callsite is hot relative to caller's entry. We could
1766bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1767bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1768bba762a1SChandler Carruth   // profiles.
1769652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1770974d4eeaSEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
1771974d4eeaSEaswaran Raman   auto CallerEntryFreq = CallerBFI->getEntryFreq();
1772974d4eeaSEaswaran Raman   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
1773bba762a1SChandler Carruth     return Params.LocallyHotCallSiteThreshold;
1774bba762a1SChandler Carruth 
1775bba762a1SChandler Carruth   // Otherwise treat it normally.
1776974d4eeaSEaswaran Raman   return None;
1777974d4eeaSEaswaran Raman }
1778974d4eeaSEaswaran Raman 
updateThreshold(CallBase & Call,Function & Callee)177906408758SMircea Trofin void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
17809a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
1781652168a9SFedor Sergeev   if (!allowSizeGrowth(Call)) {
17829a3fc17aSEaswaran Raman     Threshold = 0;
17839a3fc17aSEaswaran Raman     return;
17849a3fc17aSEaswaran Raman   }
17859a3fc17aSEaswaran Raman 
1786652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
17871c57cc2bSEaswaran Raman 
17881c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
17891c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
1790611ffcf4SKazu Hirata     return B ? std::min(A, B.value()) : A;
17911c57cc2bSEaswaran Raman   };
17921c57cc2bSEaswaran Raman 
17930d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
17940d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
1795611ffcf4SKazu Hirata     return B ? std::max(A, B.value()) : A;
17960d58fcacSEaswaran Raman   };
17970d58fcacSEaswaran Raman 
179851b809bfSEaswaran Raman   // Various bonus percentages. These are multiplied by Threshold to get the
179951b809bfSEaswaran Raman   // bonus values.
180051b809bfSEaswaran Raman   // SingleBBBonus: This bonus is applied if the callee has a single reachable
180151b809bfSEaswaran Raman   // basic block at the given callsite context. This is speculatively applied
180251b809bfSEaswaran Raman   // and withdrawn if more than one basic block is seen.
180351b809bfSEaswaran Raman   //
180451b809bfSEaswaran Raman   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
180551b809bfSEaswaran Raman   // of the last call to a static function as inlining such functions is
180651b809bfSEaswaran Raman   // guaranteed to reduce code size.
180751b809bfSEaswaran Raman   //
180851b809bfSEaswaran Raman   // These bonus percentages may be set to 0 based on properties of the caller
180951b809bfSEaswaran Raman   // and the callsite.
181051b809bfSEaswaran Raman   int SingleBBBonusPercent = 50;
1811d912a9baSDaniil Fukalov   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
181202647f73SJordan Rupprecht   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
181351b809bfSEaswaran Raman 
181451b809bfSEaswaran Raman   // Lambda to set all the above bonus and bonus percentages to 0.
181551b809bfSEaswaran Raman   auto DisallowAllBonuses = [&]() {
181651b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
181751b809bfSEaswaran Raman     VectorBonusPercent = 0;
181851b809bfSEaswaran Raman     LastCallToStaticBonus = 0;
181951b809bfSEaswaran Raman   };
182051b809bfSEaswaran Raman 
18211c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
18221c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
182385bd3978SEvandro Menezes   if (Caller->hasMinSize()) {
18241c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
182551b809bfSEaswaran Raman     // For minsize, we want to disable the single BB bonus and the vector
182651b809bfSEaswaran Raman     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
182751b809bfSEaswaran Raman     // a static function will, at the minimum, eliminate the parameter setup and
182851b809bfSEaswaran Raman     // call/return instructions.
182951b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
183051b809bfSEaswaran Raman     VectorBonusPercent = 0;
183185bd3978SEvandro Menezes   } else if (Caller->hasOptSize())
18321c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
1833f4bb2f0dSEaswaran Raman 
1834e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
1835e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
183685bd3978SEvandro Menezes   if (!Caller->hasMinSize()) {
1837e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
18380d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1839bba762a1SChandler Carruth 
18403cd1479cSEaswaran Raman     // FIXME: After switching to the new passmanager, simplify the logic below
1841bba762a1SChandler Carruth     // by checking only the callsite hotness/coldness as we will reliably
1842bba762a1SChandler Carruth     // have local profile information.
18433cd1479cSEaswaran Raman     //
1844bba762a1SChandler Carruth     // Callsite hotness and coldness can be determined if sample profile is
1845bba762a1SChandler Carruth     // used (which adds hotness metadata to calls) or if caller's
1846bba762a1SChandler Carruth     // BlockFrequencyInfo is available.
184708e2386dSMircea Trofin     BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
1848652168a9SFedor Sergeev     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
184985bd3978SEvandro Menezes     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
1850d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
1851974d4eeaSEaswaran Raman       // FIXME: This should update the threshold only if it exceeds the
1852974d4eeaSEaswaran Raman       // current threshold, but AutoFDO + ThinLTO currently relies on this
1853974d4eeaSEaswaran Raman       // behavior to prevent inlining of hot callsites during ThinLTO
1854974d4eeaSEaswaran Raman       // compile phase.
18557a47ee51SKazu Hirata       Threshold = *HotCallSiteThreshold;
1856652168a9SFedor Sergeev     } else if (isColdCallSite(Call, CallerBFI)) {
1857d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
185851b809bfSEaswaran Raman       // Do not apply bonuses for a cold callsite including the
185951b809bfSEaswaran Raman       // LastCallToStatic bonus. While this bonus might result in code size
186051b809bfSEaswaran Raman       // reduction, it can cause the size of a non-cold caller to increase
186151b809bfSEaswaran Raman       // preventing it from being inlined.
186251b809bfSEaswaran Raman       DisallowAllBonuses();
18633cd1479cSEaswaran Raman       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
1864bba762a1SChandler Carruth     } else if (PSI) {
1865bba762a1SChandler Carruth       // Use callee's global profile information only if we have no way of
1866bba762a1SChandler Carruth       // determining this via callsite information.
18673cd1479cSEaswaran Raman       if (PSI->isFunctionEntryHot(&Callee)) {
1868d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Hot callee.\n");
1869e08b139dSEaswaran Raman         // If callsite hotness can not be determined, we may still know
1870e08b139dSEaswaran Raman         // that the callee is hot and treat it as a weaker hint for threshold
1871e08b139dSEaswaran Raman         // increase.
1872e08b139dSEaswaran Raman         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1873e08b139dSEaswaran Raman       } else if (PSI->isFunctionEntryCold(&Callee)) {
1874d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Cold callee.\n");
187551b809bfSEaswaran Raman         // Do not apply bonuses for a cold callee including the
187651b809bfSEaswaran Raman         // LastCallToStatic bonus. While this bonus might result in code size
187751b809bfSEaswaran Raman         // reduction, it can cause the size of a non-cold caller to increase
187851b809bfSEaswaran Raman         // preventing it from being inlined.
187951b809bfSEaswaran Raman         DisallowAllBonuses();
18801c57cc2bSEaswaran Raman         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
1881e08b139dSEaswaran Raman       }
1882e08b139dSEaswaran Raman     }
1883e08b139dSEaswaran Raman   }
18848650a4daSJustin Lebar 
1885b7b99b07SStanislav Mekhanoshin   Threshold += TTI.adjustInliningThreshold(&Call);
1886b7b99b07SStanislav Mekhanoshin 
188702647f73SJordan Rupprecht   // Finally, take the target-specific inlining threshold multiplier into
188802647f73SJordan Rupprecht   // account.
18898650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
189051b809bfSEaswaran Raman 
189151b809bfSEaswaran Raman   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
189251b809bfSEaswaran Raman   VectorBonus = Threshold * VectorBonusPercent / 100;
189351b809bfSEaswaran Raman 
189411c8efd4SErik Desjardins   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneLiveUse() &&
189511c8efd4SErik Desjardins                                     &F == Call.getCalledFunction();
189602647f73SJordan Rupprecht   // If there is only one call of the function, and it has internal linkage,
189702647f73SJordan Rupprecht   // the cost of inlining it drops dramatically. It may seem odd to update
189802647f73SJordan Rupprecht   // Cost in updateThreshold, but the bonus depends on the logic in this method.
189902647f73SJordan Rupprecht   if (OnlyOneCallAndLocalLinkage)
190002647f73SJordan Rupprecht     Cost -= LastCallToStaticBonus;
1901f4bb2f0dSEaswaran Raman }
1902f4bb2f0dSEaswaran Raman 
visitCmpInst(CmpInst & I)19037adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
19047adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
19057adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
190654fcde42SNikita Popov   if (simplifyInstruction(I))
19077adc3a2bSChandler Carruth     return true;
19087adc3a2bSChandler Carruth 
19097adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
19107adc3a2bSChandler Carruth     return false;
19117adc3a2bSChandler Carruth 
19127adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
19137adc3a2bSChandler Carruth   // a common base.
19147adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
19157adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
19167adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
19177adc3a2bSChandler Carruth   if (LHSBase) {
19187adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
19197adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
19207adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
19217adc3a2bSChandler Carruth       // offsets.
19227adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
19237adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
19247adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
19257adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
19267adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
19277adc3a2bSChandler Carruth         return true;
19287adc3a2bSChandler Carruth       }
19297adc3a2bSChandler Carruth     }
19307adc3a2bSChandler Carruth   }
19317adc3a2bSChandler Carruth 
19327adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
19337adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
19347adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
19357adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
19367adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
19377adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
19387adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
19397adc3a2bSChandler Carruth     return true;
19407adc3a2bSChandler Carruth   }
194106408758SMircea Trofin   return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
19427adc3a2bSChandler Carruth }
19437adc3a2bSChandler Carruth 
visitSub(BinaryOperator & I)19447adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
19457adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
19467adc3a2bSChandler Carruth   // constant-related pointers.
19477adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
19487adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
19497adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
19507adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
19517adc3a2bSChandler Carruth   if (LHSBase) {
19527adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
19537adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
19547adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
19557adc3a2bSChandler Carruth       // offsets.
19567adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
19577adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
19587adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
19597adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
19607adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
19617adc3a2bSChandler Carruth         return true;
19627adc3a2bSChandler Carruth       }
19637adc3a2bSChandler Carruth     }
19647adc3a2bSChandler Carruth   }
19657adc3a2bSChandler Carruth 
19667adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
19677adc3a2bSChandler Carruth   // instructions.
19687adc3a2bSChandler Carruth   return Base::visitSub(I);
19697adc3a2bSChandler Carruth }
19707adc3a2bSChandler Carruth 
visitBinaryOperator(BinaryOperator & I)19717adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
19727adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
19736d14dfe8SHaicheng Wu   Constant *CLHS = dyn_cast<Constant>(LHS);
19746d14dfe8SHaicheng Wu   if (!CLHS)
19756d14dfe8SHaicheng Wu     CLHS = SimplifiedValues.lookup(LHS);
19766d14dfe8SHaicheng Wu   Constant *CRHS = dyn_cast<Constant>(RHS);
19776d14dfe8SHaicheng Wu   if (!CRHS)
19786d14dfe8SHaicheng Wu     CRHS = SimplifiedValues.lookup(RHS);
19796d14dfe8SHaicheng Wu 
19807adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
19817adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
1982b8c2781fSSimon Moll     SimpleV = simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
19835a956c85SMircea Trofin                             FI->getFastMathFlags(), DL);
19847adc3a2bSChandler Carruth   else
19856d14dfe8SHaicheng Wu     SimpleV =
1986b8c2781fSSimon Moll         simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
19877adc3a2bSChandler Carruth 
19886d14dfe8SHaicheng Wu   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
19896d14dfe8SHaicheng Wu     SimplifiedValues[&I] = C;
19906d14dfe8SHaicheng Wu 
19916d14dfe8SHaicheng Wu   if (SimpleV)
19927adc3a2bSChandler Carruth     return true;
19937adc3a2bSChandler Carruth 
19947adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
19957adc3a2bSChandler Carruth   disableSROA(LHS);
19967adc3a2bSChandler Carruth   disableSROA(RHS);
19977adc3a2bSChandler Carruth 
199839ed9a60SEli Friedman   // If the instruction is floating point, and the target says this operation
199939ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
20007cebf0afSCraig Topper   // as such. Unless it's fneg which can be implemented with an xor.
20017cebf0afSCraig Topper   using namespace llvm::PatternMatch;
200239ed9a60SEli Friedman   if (I.getType()->isFloatingPointTy() &&
20037cebf0afSCraig Topper       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
20047cebf0afSCraig Topper       !match(&I, m_FNeg(m_Value())))
200506408758SMircea Trofin     onCallPenalty();
200639ed9a60SEli Friedman 
20077adc3a2bSChandler Carruth   return false;
20087adc3a2bSChandler Carruth }
20097adc3a2bSChandler Carruth 
visitFNeg(UnaryOperator & I)20106cda33baSCraig Topper bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
20116cda33baSCraig Topper   Value *Op = I.getOperand(0);
20126cda33baSCraig Topper   Constant *COp = dyn_cast<Constant>(Op);
20136cda33baSCraig Topper   if (!COp)
20146cda33baSCraig Topper     COp = SimplifiedValues.lookup(Op);
20156cda33baSCraig Topper 
2016b8c2781fSSimon Moll   Value *SimpleV = simplifyFNegInst(
20175a956c85SMircea Trofin       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
20186cda33baSCraig Topper 
20196cda33baSCraig Topper   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
20206cda33baSCraig Topper     SimplifiedValues[&I] = C;
20216cda33baSCraig Topper 
20226cda33baSCraig Topper   if (SimpleV)
20236cda33baSCraig Topper     return true;
20246cda33baSCraig Topper 
20256cda33baSCraig Topper   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
20266cda33baSCraig Topper   disableSROA(Op);
20276cda33baSCraig Topper 
20286cda33baSCraig Topper   return false;
20296cda33baSCraig Topper }
20306cda33baSCraig Topper 
visitLoad(LoadInst & I)20317adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
203206408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
20337adc3a2bSChandler Carruth     return true;
20347adc3a2bSChandler Carruth 
2035a4461515SHaicheng Wu   // If the data is already loaded from this address and hasn't been clobbered
2036a4461515SHaicheng Wu   // by any stores or calls, this load is likely to be redundant and can be
2037a4461515SHaicheng Wu   // eliminated.
2038a4461515SHaicheng Wu   if (EnableLoadElimination &&
2039b3689cabSHaicheng Wu       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
204006408758SMircea Trofin     onLoadEliminationOpportunity();
2041a4461515SHaicheng Wu     return true;
2042a4461515SHaicheng Wu   }
2043a4461515SHaicheng Wu 
20447adc3a2bSChandler Carruth   return false;
20457adc3a2bSChandler Carruth }
20467adc3a2bSChandler Carruth 
visitStore(StoreInst & I)20477adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
204806408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
20497adc3a2bSChandler Carruth     return true;
20507adc3a2bSChandler Carruth 
2051a4461515SHaicheng Wu   // The store can potentially clobber loads and prevent repeated loads from
2052a4461515SHaicheng Wu   // being eliminated.
2053a4461515SHaicheng Wu   // FIXME:
2054a4461515SHaicheng Wu   // 1. We can probably keep an initial set of eliminatable loads substracted
2055a4461515SHaicheng Wu   // from the cost even when we finally see a store. We just need to disable
2056a4461515SHaicheng Wu   // *further* accumulation of elimination savings.
2057a4461515SHaicheng Wu   // 2. We should probably at some point thread MemorySSA for the callee into
2058a4461515SHaicheng Wu   // this and then use that to actually compute *really* precise savings.
2059a4461515SHaicheng Wu   disableLoadElimination();
20607adc3a2bSChandler Carruth   return false;
20617adc3a2bSChandler Carruth }
20627adc3a2bSChandler Carruth 
visitExtractValue(ExtractValueInst & I)20637adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
20647adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
206554fcde42SNikita Popov   if (simplifyInstruction(I))
20667adc3a2bSChandler Carruth     return true;
20677adc3a2bSChandler Carruth 
2068ba5b015bSRoman Lebedev   // SROA can't look through these, but they may be free.
2069ba5b015bSRoman Lebedev   return Base::visitExtractValue(I);
20707adc3a2bSChandler Carruth }
20717adc3a2bSChandler Carruth 
visitInsertValue(InsertValueInst & I)20727adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
20737adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
207454fcde42SNikita Popov   if (simplifyInstruction(I))
20757adc3a2bSChandler Carruth     return true;
20767adc3a2bSChandler Carruth 
2077ba5b015bSRoman Lebedev   // SROA can't look through these, but they may be free.
2078ba5b015bSRoman Lebedev   return Base::visitInsertValue(I);
20797adc3a2bSChandler Carruth }
20807adc3a2bSChandler Carruth 
20815f8f34e4SAdrian Prantl /// Try to simplify a call site.
20827adc3a2bSChandler Carruth ///
20837adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
20847adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
20857adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
20867adc3a2bSChandler Carruth /// free.
simplifyCallSite(Function * F,CallBase & Call)2087652168a9SFedor Sergeev bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
20887adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
20897adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
20907adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
20917adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
2092652168a9SFedor Sergeev   if (!canConstantFoldCallTo(&Call, F))
20937adc3a2bSChandler Carruth     return false;
20947adc3a2bSChandler Carruth 
20957adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
20967adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
2097652168a9SFedor Sergeev   ConstantArgs.reserve(Call.arg_size());
2098652168a9SFedor Sergeev   for (Value *I : Call.args()) {
2099652168a9SFedor Sergeev     Constant *C = dyn_cast<Constant>(I);
21007adc3a2bSChandler Carruth     if (!C)
2101652168a9SFedor Sergeev       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
21027adc3a2bSChandler Carruth     if (!C)
21037adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
21047adc3a2bSChandler Carruth 
21057adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
21067adc3a2bSChandler Carruth   }
2107652168a9SFedor Sergeev   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2108652168a9SFedor Sergeev     SimplifiedValues[&Call] = C;
21097adc3a2bSChandler Carruth     return true;
21107adc3a2bSChandler Carruth   }
21117adc3a2bSChandler Carruth 
21127adc3a2bSChandler Carruth   return false;
21137adc3a2bSChandler Carruth }
21147adc3a2bSChandler Carruth 
visitCallBase(CallBase & Call)2115652168a9SFedor Sergeev bool CallAnalyzer::visitCallBase(CallBase &Call) {
21165c97507eSDaniil Suchkov   if (!onCallBaseVisitStart(Call))
21175c97507eSDaniil Suchkov     return true;
21185c97507eSDaniil Suchkov 
2119652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
21207adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
21217adc3a2bSChandler Carruth     // This aborts the entire analysis.
21227adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
21237adc3a2bSChandler Carruth     return false;
21247adc3a2bSChandler Carruth   }
2125652168a9SFedor Sergeev   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
21267adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
21277adc3a2bSChandler Carruth 
21288d5c8d57SNikita Popov   Function *F = Call.getCalledFunction();
2129825debe8SEhud Katz   bool IsIndirectCall = !F;
2130825debe8SEhud Katz   if (IsIndirectCall) {
2131825debe8SEhud Katz     // Check if this happens to be an indirect function call to a known function
2132825debe8SEhud Katz     // in this inline context. If not, we've done all we can.
21338d5c8d57SNikita Popov     Value *Callee = Call.getCalledOperand();
2134825debe8SEhud Katz     F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
21358d5c8d57SNikita Popov     if (!F || F->getFunctionType() != Call.getFunctionType()) {
213606408758SMircea Trofin       onCallArgumentSetup(Call);
2137825debe8SEhud Katz 
2138825debe8SEhud Katz       if (!Call.onlyReadsMemory())
2139825debe8SEhud Katz         disableLoadElimination();
2140825debe8SEhud Katz       return Base::visitCallBase(Call);
2141825debe8SEhud Katz     }
2142825debe8SEhud Katz   }
2143825debe8SEhud Katz 
2144825debe8SEhud Katz   assert(F && "Expected a call to a known function");
2145825debe8SEhud Katz 
21467adc3a2bSChandler Carruth   // When we have a concrete function, first try to simplify it directly.
2147652168a9SFedor Sergeev   if (simplifyCallSite(F, Call))
21487adc3a2bSChandler Carruth     return true;
21497adc3a2bSChandler Carruth 
21507adc3a2bSChandler Carruth   // Next check if it is an intrinsic we know about.
21517adc3a2bSChandler Carruth   // FIXME: Lift this into part of the InstVisitor.
2152652168a9SFedor Sergeev   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
21537adc3a2bSChandler Carruth     switch (II->getIntrinsicID()) {
21547adc3a2bSChandler Carruth     default:
2155652168a9SFedor Sergeev       if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
2156a4461515SHaicheng Wu         disableLoadElimination();
2157652168a9SFedor Sergeev       return Base::visitCallBase(Call);
21587adc3a2bSChandler Carruth 
21597dd8dbf4SPeter Collingbourne     case Intrinsic::load_relative:
216006408758SMircea Trofin       onLoadRelativeIntrinsic();
21617dd8dbf4SPeter Collingbourne       return false;
21627dd8dbf4SPeter Collingbourne 
21637adc3a2bSChandler Carruth     case Intrinsic::memset:
21647adc3a2bSChandler Carruth     case Intrinsic::memcpy:
21657adc3a2bSChandler Carruth     case Intrinsic::memmove:
2166a4461515SHaicheng Wu       disableLoadElimination();
21677adc3a2bSChandler Carruth       // SROA can usually chew through these intrinsics, but they aren't free.
21687adc3a2bSChandler Carruth       return false;
21694296ea72SVitaly Buka     case Intrinsic::icall_branch_funnel:
21707adc3a2bSChandler Carruth     case Intrinsic::localescape:
21714296ea72SVitaly Buka       HasUninlineableIntrinsic = true;
21727adc3a2bSChandler Carruth       return false;
217380788d80SFlorian Hahn     case Intrinsic::vastart:
217477beee41SSameer AbuAsal       InitsVargArgs = true;
217580788d80SFlorian Hahn       return false;
2176269b335bSArthur Eubanks     case Intrinsic::launder_invariant_group:
2177269b335bSArthur Eubanks     case Intrinsic::strip_invariant_group:
2178269b335bSArthur Eubanks       if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2179269b335bSArthur Eubanks         SROAArgValues[II] = SROAArg;
2180269b335bSArthur Eubanks       return true;
21819697f935SNick Desaulniers     case Intrinsic::is_constant:
21829697f935SNick Desaulniers       return simplifyIntrinsicCallIsConstant(Call);
21837adc3a2bSChandler Carruth     }
21847adc3a2bSChandler Carruth   }
21857adc3a2bSChandler Carruth 
2186652168a9SFedor Sergeev   if (F == Call.getFunction()) {
21877adc3a2bSChandler Carruth     // This flag will fully abort the analysis, so don't bother with anything
21887adc3a2bSChandler Carruth     // else.
21897adc3a2bSChandler Carruth     IsRecursiveCall = true;
2190f7fff46aSWenlei He     if (!AllowRecursiveCall)
21917adc3a2bSChandler Carruth       return false;
21927adc3a2bSChandler Carruth   }
21937adc3a2bSChandler Carruth 
21947adc3a2bSChandler Carruth   if (TTI.isLoweredToCall(F)) {
219506408758SMircea Trofin     onLoweredCall(F, Call, IsIndirectCall);
2196825debe8SEhud Katz   }
21977adc3a2bSChandler Carruth 
2198825debe8SEhud Katz   if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2199a4461515SHaicheng Wu     disableLoadElimination();
2200652168a9SFedor Sergeev   return Base::visitCallBase(Call);
22017adc3a2bSChandler Carruth }
22027adc3a2bSChandler Carruth 
visitReturnInst(ReturnInst & RI)22037adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
22047adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
22057adc3a2bSChandler Carruth   bool Free = !HasReturn;
22067adc3a2bSChandler Carruth   HasReturn = true;
22077adc3a2bSChandler Carruth   return Free;
22087adc3a2bSChandler Carruth }
22097adc3a2bSChandler Carruth 
visitBranchInst(BranchInst & BI)22107adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
22117adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
22127adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
22137adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
22147adc3a2bSChandler Carruth   // which will fold away are also free.
22157adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
2216d243cbf8SKazu Hirata          isa_and_nonnull<ConstantInt>(
22177adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
22187adc3a2bSChandler Carruth }
22197adc3a2bSChandler Carruth 
visitSelectInst(SelectInst & SI)22203ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
22213ec848bcSHaicheng Wu   bool CheckSROA = SI.getType()->isPointerTy();
22223ec848bcSHaicheng Wu   Value *TrueVal = SI.getTrueValue();
22233ec848bcSHaicheng Wu   Value *FalseVal = SI.getFalseValue();
22243ec848bcSHaicheng Wu 
22253ec848bcSHaicheng Wu   Constant *TrueC = dyn_cast<Constant>(TrueVal);
22263ec848bcSHaicheng Wu   if (!TrueC)
22273ec848bcSHaicheng Wu     TrueC = SimplifiedValues.lookup(TrueVal);
22283ec848bcSHaicheng Wu   Constant *FalseC = dyn_cast<Constant>(FalseVal);
22293ec848bcSHaicheng Wu   if (!FalseC)
22303ec848bcSHaicheng Wu     FalseC = SimplifiedValues.lookup(FalseVal);
22313ec848bcSHaicheng Wu   Constant *CondC =
22323ec848bcSHaicheng Wu       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
22333ec848bcSHaicheng Wu 
22343ec848bcSHaicheng Wu   if (!CondC) {
22353ec848bcSHaicheng Wu     // Select C, X, X => X
22363ec848bcSHaicheng Wu     if (TrueC == FalseC && TrueC) {
22373ec848bcSHaicheng Wu       SimplifiedValues[&SI] = TrueC;
22383ec848bcSHaicheng Wu       return true;
22393ec848bcSHaicheng Wu     }
22403ec848bcSHaicheng Wu 
22413ec848bcSHaicheng Wu     if (!CheckSROA)
22423ec848bcSHaicheng Wu       return Base::visitSelectInst(SI);
22433ec848bcSHaicheng Wu 
22443ec848bcSHaicheng Wu     std::pair<Value *, APInt> TrueBaseAndOffset =
22453ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(TrueVal);
22463ec848bcSHaicheng Wu     std::pair<Value *, APInt> FalseBaseAndOffset =
22473ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(FalseVal);
22483ec848bcSHaicheng Wu     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
22493ec848bcSHaicheng Wu       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
22503ec848bcSHaicheng Wu 
225106408758SMircea Trofin       if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
22523ec848bcSHaicheng Wu         SROAArgValues[&SI] = SROAArg;
22533ec848bcSHaicheng Wu       return true;
22543ec848bcSHaicheng Wu     }
22553ec848bcSHaicheng Wu 
22563ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
22573ec848bcSHaicheng Wu   }
22583ec848bcSHaicheng Wu 
22593ec848bcSHaicheng Wu   // Select condition is a constant.
22607b639f50SJacob Hegna   Value *SelectedV = CondC->isAllOnesValue()  ? TrueVal
22617b639f50SJacob Hegna                      : (CondC->isNullValue()) ? FalseVal
22627b639f50SJacob Hegna                                               : nullptr;
22633ec848bcSHaicheng Wu   if (!SelectedV) {
22643ec848bcSHaicheng Wu     // Condition is a vector constant that is not all 1s or all 0s.  If all
22653ec848bcSHaicheng Wu     // operands are constants, ConstantExpr::getSelect() can handle the cases
22663ec848bcSHaicheng Wu     // such as select vectors.
22673ec848bcSHaicheng Wu     if (TrueC && FalseC) {
22683ec848bcSHaicheng Wu       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
22693ec848bcSHaicheng Wu         SimplifiedValues[&SI] = C;
22703ec848bcSHaicheng Wu         return true;
22713ec848bcSHaicheng Wu       }
22723ec848bcSHaicheng Wu     }
22733ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
22743ec848bcSHaicheng Wu   }
22753ec848bcSHaicheng Wu 
22763ec848bcSHaicheng Wu   // Condition is either all 1s or all 0s. SI can be simplified.
22773ec848bcSHaicheng Wu   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
22783ec848bcSHaicheng Wu     SimplifiedValues[&SI] = SelectedC;
22793ec848bcSHaicheng Wu     return true;
22803ec848bcSHaicheng Wu   }
22813ec848bcSHaicheng Wu 
22823ec848bcSHaicheng Wu   if (!CheckSROA)
22833ec848bcSHaicheng Wu     return true;
22843ec848bcSHaicheng Wu 
22853ec848bcSHaicheng Wu   std::pair<Value *, APInt> BaseAndOffset =
22863ec848bcSHaicheng Wu       ConstantOffsetPtrs.lookup(SelectedV);
22873ec848bcSHaicheng Wu   if (BaseAndOffset.first) {
22883ec848bcSHaicheng Wu     ConstantOffsetPtrs[&SI] = BaseAndOffset;
22893ec848bcSHaicheng Wu 
229006408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
22913ec848bcSHaicheng Wu       SROAArgValues[&SI] = SROAArg;
22923ec848bcSHaicheng Wu   }
22933ec848bcSHaicheng Wu 
22943ec848bcSHaicheng Wu   return true;
22953ec848bcSHaicheng Wu }
22963ec848bcSHaicheng Wu 
visitSwitchInst(SwitchInst & SI)22977adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
22987adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
22997adc3a2bSChandler Carruth   // branches.
23007adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
23017adc3a2bSChandler Carruth     return true;
23027adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
23037adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
23047adc3a2bSChandler Carruth       return true;
23057adc3a2bSChandler Carruth 
23067ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
2307919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
2308919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
2309919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
2310919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
2311919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
23122960d41eSJun Bum Lim   //
23132960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
2314472462c4SBjorn Pettersson   // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
23152960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
23162960d41eSJun Bum Lim   // does not (yet) fire.
2317919f9e8dSJun Bum Lim 
2318919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
231908e2386dSMircea Trofin   BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2320919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
23210d987e41SHiroshi Yamauchi       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2322919f9e8dSJun Bum Lim 
232306408758SMircea Trofin   onFinalizeSwitch(JumpTableSize, NumCaseCluster);
2324919f9e8dSJun Bum Lim   return false;
2325919f9e8dSJun Bum Lim }
2326919f9e8dSJun Bum Lim 
visitIndirectBrInst(IndirectBrInst & IBI)23277adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
23287adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
23297adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
23307adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
23317adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
23327adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
23337adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
23347adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
23357adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
23367adc3a2bSChandler Carruth   HasIndirectBr = true;
23377adc3a2bSChandler Carruth   return false;
23387adc3a2bSChandler Carruth }
23397adc3a2bSChandler Carruth 
visitResumeInst(ResumeInst & RI)23407adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
23417adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
23427adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
23437adc3a2bSChandler Carruth   return false;
23447adc3a2bSChandler Carruth }
23457adc3a2bSChandler Carruth 
visitCleanupReturnInst(CleanupReturnInst & CRI)23467adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
23477adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
23487adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
23497adc3a2bSChandler Carruth   return false;
23507adc3a2bSChandler Carruth }
23517adc3a2bSChandler Carruth 
visitCatchReturnInst(CatchReturnInst & CRI)23527adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
23537adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
23548220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
23557adc3a2bSChandler Carruth   return false;
23567adc3a2bSChandler Carruth }
23577adc3a2bSChandler Carruth 
visitUnreachableInst(UnreachableInst & I)23587adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
23597adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
23607adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
23617adc3a2bSChandler Carruth   // code size.
23627adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
23637adc3a2bSChandler Carruth }
23647adc3a2bSChandler Carruth 
visitInstruction(Instruction & I)23657adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
23667adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
23677adc3a2bSChandler Carruth   // handled by SROA, etc.
23683ccbd4f3SSander de Smalen   if (TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
23693ccbd4f3SSander de Smalen       TargetTransformInfo::TCC_Free)
23707adc3a2bSChandler Carruth     return true;
23717adc3a2bSChandler Carruth 
23727adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
23737adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
237491aff1d8SNick Desaulniers   for (const Use &Op : I.operands())
237591aff1d8SNick Desaulniers     disableSROA(Op);
23767adc3a2bSChandler Carruth 
23777adc3a2bSChandler Carruth   return false;
23787adc3a2bSChandler Carruth }
23797adc3a2bSChandler Carruth 
23805f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost.
23817adc3a2bSChandler Carruth ///
23827adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
23837adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
23847adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
23857adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
23867adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
2387c0aa4b75SDavid Bolvansky InlineResult
analyzeBlock(BasicBlock * BB,SmallPtrSetImpl<const Value * > & EphValues)2388c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB,
23897adc3a2bSChandler Carruth                            SmallPtrSetImpl<const Value *> &EphValues) {
239091aff1d8SNick Desaulniers   for (Instruction &I : *BB) {
23917adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
23927adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
23937adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
23947adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
23957adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
23967adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
23977adc3a2bSChandler Carruth     // hack around it here.
2398098a0d8fSHongtao Yu     // Similarly, skip pseudo-probes.
2399098a0d8fSHongtao Yu     if (I.isDebugOrPseudoInst())
2400f3c44569SHongtao Yu       continue;
2401f3c44569SHongtao Yu 
24027adc3a2bSChandler Carruth     // Skip ephemeral values.
240391aff1d8SNick Desaulniers     if (EphValues.count(&I))
24047adc3a2bSChandler Carruth       continue;
24057adc3a2bSChandler Carruth 
24067adc3a2bSChandler Carruth     ++NumInstructions;
240791aff1d8SNick Desaulniers     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
24087adc3a2bSChandler Carruth       ++NumVectorInstructions;
24097adc3a2bSChandler Carruth 
24107adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
24117adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
24127adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
24137adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
24147adc3a2bSChandler Carruth     // cost should count against inlining.
241591aff1d8SNick Desaulniers     onInstructionAnalysisStart(&I);
2416c965fd94SKirill Naumov 
241791aff1d8SNick Desaulniers     if (Base::visit(&I))
24187adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
24197adc3a2bSChandler Carruth     else
242014a16faeSMircea Trofin       onMissedSimplification();
24217adc3a2bSChandler Carruth 
242291aff1d8SNick Desaulniers     onInstructionAnalysisFinish(&I);
24230812c5beSHaicheng Wu     using namespace ore;
24247adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
24255466597fSMircea Trofin     InlineResult IR = InlineResult::success();
2426f7fff46aSWenlei He     if (IsRecursiveCall && !AllowRecursiveCall)
24275466597fSMircea Trofin       IR = InlineResult::failure("recursive");
2428c0aa4b75SDavid Bolvansky     else if (ExposesReturnsTwice)
24295466597fSMircea Trofin       IR = InlineResult::failure("exposes returns twice");
2430c0aa4b75SDavid Bolvansky     else if (HasDynamicAlloca)
24315466597fSMircea Trofin       IR = InlineResult::failure("dynamic alloca");
2432c0aa4b75SDavid Bolvansky     else if (HasIndirectBr)
24335466597fSMircea Trofin       IR = InlineResult::failure("indirect branch");
2434c0aa4b75SDavid Bolvansky     else if (HasUninlineableIntrinsic)
24355466597fSMircea Trofin       IR = InlineResult::failure("uninlinable intrinsic");
243677beee41SSameer AbuAsal     else if (InitsVargArgs)
24375466597fSMircea Trofin       IR = InlineResult::failure("varargs");
24385466597fSMircea Trofin     if (!IR.isSuccess()) {
24390812c5beSHaicheng Wu       if (ORE)
24409590658fSVivek Pandya         ORE->emit([&]() {
24419590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2442652168a9SFedor Sergeev                                           &CandidateCall)
2443c0aa4b75SDavid Bolvansky                  << NV("Callee", &F) << " has uninlinable pattern ("
24445466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2445c0aa4b75SDavid Bolvansky                  << ") and cost is not fully computed";
24469590658fSVivek Pandya         });
2447c0aa4b75SDavid Bolvansky       return IR;
24480812c5beSHaicheng Wu     }
24497adc3a2bSChandler Carruth 
24507adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
24517adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
24527adc3a2bSChandler Carruth     // the caller stack usage dramatically.
2453a78f436cSWenlei He     if (IsCallerRecursive && AllocatedSize > RecurStackSizeThreshold) {
24545466597fSMircea Trofin       auto IR =
24555466597fSMircea Trofin           InlineResult::failure("recursive and allocates too much stack space");
24560812c5beSHaicheng Wu       if (ORE)
24579590658fSVivek Pandya         ORE->emit([&]() {
24589590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2459652168a9SFedor Sergeev                                           &CandidateCall)
24605466597fSMircea Trofin                  << NV("Callee", &F) << " is "
24615466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2462c0aa4b75SDavid Bolvansky                  << ". Cost is not fully computed";
24639590658fSVivek Pandya         });
2464c0aa4b75SDavid Bolvansky       return IR;
24650812c5beSHaicheng Wu     }
24667adc3a2bSChandler Carruth 
246706408758SMircea Trofin     if (shouldStop())
24685466597fSMircea Trofin       return InlineResult::failure(
24695466597fSMircea Trofin           "Call site analysis is not favorable to inlining.");
24707adc3a2bSChandler Carruth   }
24717adc3a2bSChandler Carruth 
24725466597fSMircea Trofin   return InlineResult::success();
24737adc3a2bSChandler Carruth }
24747adc3a2bSChandler Carruth 
24755f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V.
24767adc3a2bSChandler Carruth ///
24777adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
24787adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
24797adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
24807adc3a2bSChandler Carruth /// no constant offsets applied.
stripAndComputeInBoundsConstantOffsets(Value * & V)24817adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
24827adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
24837adc3a2bSChandler Carruth     return nullptr;
24847adc3a2bSChandler Carruth 
248577f32994SBjorn Pettersson   unsigned AS = V->getType()->getPointerAddressSpace();
2486945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
2487735f4671SChris Lattner   APInt Offset = APInt::getZero(IntPtrWidth);
24887adc3a2bSChandler Carruth 
24897adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
24907adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
24917adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
24927adc3a2bSChandler Carruth   Visited.insert(V);
24937adc3a2bSChandler Carruth   do {
24947adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
24957adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
24967adc3a2bSChandler Carruth         return nullptr;
24977adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
24987adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
24997adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
25007adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
25015ce32728SSanjoy Das       if (GA->isInterposable())
25027adc3a2bSChandler Carruth         break;
25037adc3a2bSChandler Carruth       V = GA->getAliasee();
25047adc3a2bSChandler Carruth     } else {
25057adc3a2bSChandler Carruth       break;
25067adc3a2bSChandler Carruth     }
25077adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
25087adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
25097adc3a2bSChandler Carruth 
251097572775SNicola Zaghen   Type *IdxPtrTy = DL.getIndexType(V->getType());
251197572775SNicola Zaghen   return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
25127adc3a2bSChandler Carruth }
25137adc3a2bSChandler Carruth 
25145f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining.
25153739e14aSHaicheng Wu ///
25163739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p
25173739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have
25183739e14aSHaicheng Wu /// no live incoming CFG edges.  If one block is found to be dead, we can
25193739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead
25203739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not.
findDeadBlocks(BasicBlock * CurrBB,BasicBlock * NextBB)25213739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
25223739e14aSHaicheng Wu   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
252302a2bb2fSHiroshi Inoue     // A CFG edge is dead if the predecessor is dead or the predecessor has a
25243739e14aSHaicheng Wu     // known successor which is not the one under exam.
25253739e14aSHaicheng Wu     return (DeadBlocks.count(Pred) ||
25263739e14aSHaicheng Wu             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
25273739e14aSHaicheng Wu   };
25283739e14aSHaicheng Wu 
25293739e14aSHaicheng Wu   auto IsNewlyDead = [&](BasicBlock *BB) {
25303739e14aSHaicheng Wu     // If all the edges to a block are dead, the block is also dead.
25313739e14aSHaicheng Wu     return (!DeadBlocks.count(BB) &&
25323739e14aSHaicheng Wu             llvm::all_of(predecessors(BB),
25333739e14aSHaicheng Wu                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
25343739e14aSHaicheng Wu   };
25353739e14aSHaicheng Wu 
25363739e14aSHaicheng Wu   for (BasicBlock *Succ : successors(CurrBB)) {
25373739e14aSHaicheng Wu     if (Succ == NextBB || !IsNewlyDead(Succ))
25383739e14aSHaicheng Wu       continue;
25393739e14aSHaicheng Wu     SmallVector<BasicBlock *, 4> NewDead;
25403739e14aSHaicheng Wu     NewDead.push_back(Succ);
25413739e14aSHaicheng Wu     while (!NewDead.empty()) {
25423739e14aSHaicheng Wu       BasicBlock *Dead = NewDead.pop_back_val();
25433c53d3a7SNikita Popov       if (DeadBlocks.insert(Dead).second)
25443739e14aSHaicheng Wu         // Continue growing the dead block lists.
25453739e14aSHaicheng Wu         for (BasicBlock *S : successors(Dead))
25463739e14aSHaicheng Wu           if (IsNewlyDead(S))
25473739e14aSHaicheng Wu             NewDead.push_back(S);
25483739e14aSHaicheng Wu     }
25493739e14aSHaicheng Wu   }
25503739e14aSHaicheng Wu }
25513739e14aSHaicheng Wu 
25525f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining.
25537adc3a2bSChandler Carruth ///
25547adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
25557adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
25567adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
25577adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
25587adc3a2bSChandler Carruth /// some artifact of the routine.
analyze()255993ac81ccSMircea Trofin InlineResult CallAnalyzer::analyze() {
25607adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
25617adc3a2bSChandler Carruth 
256206408758SMircea Trofin   auto Result = onAnalysisStart();
25635466597fSMircea Trofin   if (!Result.isSuccess())
256406408758SMircea Trofin     return Result;
25657adc3a2bSChandler Carruth 
25667adc3a2bSChandler Carruth   if (F.empty())
25675466597fSMircea Trofin     return InlineResult::success();
25687adc3a2bSChandler Carruth 
256993ac81ccSMircea Trofin   Function *Caller = CandidateCall.getFunction();
25707adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
25717adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
2572652168a9SFedor Sergeev     CallBase *Call = dyn_cast<CallBase>(U);
2573652168a9SFedor Sergeev     if (Call && Call->getFunction() == Caller) {
25747adc3a2bSChandler Carruth       IsCallerRecursive = true;
25757adc3a2bSChandler Carruth       break;
25767adc3a2bSChandler Carruth     }
25777adc3a2bSChandler Carruth   }
25787adc3a2bSChandler Carruth 
25797adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
25807adc3a2bSChandler Carruth   // arguments with known important simplifications.
258193ac81ccSMircea Trofin   auto CAI = CandidateCall.arg_begin();
258291aff1d8SNick Desaulniers   for (Argument &FAI : F.args()) {
258393ac81ccSMircea Trofin     assert(CAI != CandidateCall.arg_end());
25847adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
258591aff1d8SNick Desaulniers       SimplifiedValues[&FAI] = C;
25867adc3a2bSChandler Carruth 
25877adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
25887adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
258991aff1d8SNick Desaulniers       ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
25907adc3a2bSChandler Carruth 
25917adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
259206408758SMircea Trofin       if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
259391aff1d8SNick Desaulniers         SROAArgValues[&FAI] = SROAArg;
259406408758SMircea Trofin         onInitializeSROAArg(SROAArg);
25952e42cc7aSMircea Trofin         EnabledSROAAllocas.insert(SROAArg);
25967adc3a2bSChandler Carruth       }
25977adc3a2bSChandler Carruth     }
259891aff1d8SNick Desaulniers     ++CAI;
25997adc3a2bSChandler Carruth   }
26007adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
26017adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
26027adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
26037adc3a2bSChandler Carruth 
26047adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
26057adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
26067adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
26077adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
2608aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
26097adc3a2bSChandler Carruth 
26107adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
26117adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
26127adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
26137adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
26147adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
26157adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
26167adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
26177adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
2618567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
2619567556aaSChad Rosier       BBSetVector;
26207adc3a2bSChandler Carruth   BBSetVector BBWorklist;
26217adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
262206408758SMircea Trofin 
26237adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
26247adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
262506408758SMircea Trofin     if (shouldStop())
26267adc3a2bSChandler Carruth       break;
26277adc3a2bSChandler Carruth 
26287adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
26297adc3a2bSChandler Carruth     if (BB->empty())
26307adc3a2bSChandler Carruth       continue;
26317adc3a2bSChandler Carruth 
26329895c701SKazu Hirata     onBlockStart(BB);
26339895c701SKazu Hirata 
2634639b29b1SNick Desaulniers     // Disallow inlining a blockaddress with uses other than strictly callbr.
2635639b29b1SNick Desaulniers     // A blockaddress only has defined behavior for an indirect branch in the
2636639b29b1SNick Desaulniers     // same function, and we do not currently support inlining indirect
2637639b29b1SNick Desaulniers     // branches.  But, the inliner may not see an indirect branch that ends up
2638639b29b1SNick Desaulniers     // being dead code at a particular call site. If the blockaddress escapes
2639639b29b1SNick Desaulniers     // the function, e.g., via a global variable, inlining may lead to an
2640639b29b1SNick Desaulniers     // invalid cross-function reference.
2641639b29b1SNick Desaulniers     // FIXME: pr/39560: continue relaxing this overt restriction.
26426a84cd3bSNick Desaulniers     if (BB->hasAddressTaken())
2643639b29b1SNick Desaulniers       for (User *U : BlockAddress::get(&*BB)->users())
2644639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
26455466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
26467adc3a2bSChandler Carruth 
26477adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
26487adc3a2bSChandler Carruth     // returns false, and we can bail on out.
2649c0aa4b75SDavid Bolvansky     InlineResult IR = analyzeBlock(BB, EphValues);
26505466597fSMircea Trofin     if (!IR.isSuccess())
2651c0aa4b75SDavid Bolvansky       return IR;
26527adc3a2bSChandler Carruth 
2653edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
26547adc3a2bSChandler Carruth 
26557adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
26567adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
26577adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
26587adc3a2bSChandler Carruth       if (BI->isConditional()) {
26597adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
2660567556aaSChad Rosier         if (ConstantInt *SimpleCond =
2661567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
26623739e14aSHaicheng Wu           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
26633739e14aSHaicheng Wu           BBWorklist.insert(NextBB);
26643739e14aSHaicheng Wu           KnownSuccessors[BB] = NextBB;
26653739e14aSHaicheng Wu           findDeadBlocks(BB, NextBB);
26667adc3a2bSChandler Carruth           continue;
26677adc3a2bSChandler Carruth         }
26687adc3a2bSChandler Carruth       }
26697adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
26707adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
2671567556aaSChad Rosier       if (ConstantInt *SimpleCond =
2672567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
26733739e14aSHaicheng Wu         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
26743739e14aSHaicheng Wu         BBWorklist.insert(NextBB);
26753739e14aSHaicheng Wu         KnownSuccessors[BB] = NextBB;
26763739e14aSHaicheng Wu         findDeadBlocks(BB, NextBB);
26777adc3a2bSChandler Carruth         continue;
26787adc3a2bSChandler Carruth       }
26797adc3a2bSChandler Carruth     }
26807adc3a2bSChandler Carruth 
26817adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
26827adc3a2bSChandler Carruth     // them.
26837adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
26847adc3a2bSChandler Carruth          ++TIdx)
26857adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
26867adc3a2bSChandler Carruth 
268706408758SMircea Trofin     onBlockAnalyzed(BB);
26887adc3a2bSChandler Carruth   }
26897adc3a2bSChandler Carruth 
269011c8efd4SErik Desjardins   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneLiveUse() &&
269193ac81ccSMircea Trofin                                     &F == CandidateCall.getCalledFunction();
26927adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
26937adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
26947adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
26957adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
26965466597fSMircea Trofin     return InlineResult::failure("noduplicate");
26977adc3a2bSChandler Carruth 
2698c50e6f59SWolfgang Pieb   // If the callee's stack size exceeds the user-specified threshold,
2699c50e6f59SWolfgang Pieb   // do not let it be inlined.
2700c50e6f59SWolfgang Pieb   if (AllocatedSize > StackSizeThreshold)
2701c50e6f59SWolfgang Pieb     return InlineResult::failure("stacksize");
2702c50e6f59SWolfgang Pieb 
270306408758SMircea Trofin   return finalizeAnalysis();
27047adc3a2bSChandler Carruth }
27057adc3a2bSChandler Carruth 
print(raw_ostream & OS)2706ecd25edfSArthur Eubanks void InlineCostCallAnalyzer::print(raw_ostream &OS) {
2707ecd25edfSArthur Eubanks #define DEBUG_PRINT_STAT(x) OS << "      " #x ": " << x << "\n"
27081022b5ebSKirill Naumov   if (PrintInstructionComments)
2709ecd25edfSArthur Eubanks     F.print(OS, &Writer);
27107adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
27117adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
27127adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
27137adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
27147adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
27157adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
27167adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
27177adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
27187adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
2719a4461515SHaicheng Wu   DEBUG_PRINT_STAT(LoadEliminationCost);
27207adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
27217adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
27227adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
27237adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
27247adc3a2bSChandler Carruth }
2725ca899bf9SKirill Naumov 
2726ca899bf9SKirill Naumov #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2727ca899bf9SKirill Naumov /// Dump stats about this call's analysis.
dump()2728ecd25edfSArthur Eubanks LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(dbgs()); }
27297adc3a2bSChandler Carruth #endif
27307adc3a2bSChandler Carruth 
27315f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee
27327adc3a2bSChandler Carruth ///        that prevent inlining.
functionsHaveCompatibleAttributes(Function * Caller,Function * Callee,TargetTransformInfo & TTI,function_ref<const TargetLibraryInfo & (Function &)> & GetTLI)2733f9ca75f1STeresa Johnson static bool functionsHaveCompatibleAttributes(
2734f9ca75f1STeresa Johnson     Function *Caller, Function *Callee, TargetTransformInfo &TTI,
2735f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
2736f9ca75f1STeresa Johnson   // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
2737f9ca75f1STeresa Johnson   // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
2738f9ca75f1STeresa Johnson   // object, and always returns the same object (which is overwritten on each
2739f9ca75f1STeresa Johnson   // GetTLI call). Therefore we copy the first result.
2740f9ca75f1STeresa Johnson   auto CalleeTLI = GetTLI(*Callee);
2741a4aa97d5SAnna Thomas   return (IgnoreTTIInlineCompatible ||
2742a4aa97d5SAnna Thomas           TTI.areInlineCompatible(Caller, Callee)) &&
2743f9ca75f1STeresa Johnson          GetTLI(*Caller).areInlineCompatible(CalleeTLI,
2744ed03d948SMehdi Amini                                              InlineCallerSupersetNoBuiltin) &&
27451cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
27467adc3a2bSChandler Carruth }
27477adc3a2bSChandler Carruth 
getCallsiteCost(CallBase & Call,const DataLayout & DL)2748652168a9SFedor Sergeev int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
2749351d9b01SXinliang David Li   int Cost = 0;
2750652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
2751652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2752351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
2753351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
2754652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
275507a9df59SArthur Eubanks       unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
275677f32994SBjorn Pettersson       unsigned AS = PTy->getAddressSpace();
275777f32994SBjorn Pettersson       unsigned PointerSize = DL.getPointerSizeInBits(AS);
2758351d9b01SXinliang David Li       // Ceiling division.
2759351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2760351d9b01SXinliang David Li 
2761351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
2762351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
2763351d9b01SXinliang David Li       // one load and one store per word copied.
2764351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
2765351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
2766351d9b01SXinliang David Li       // DataLayout.
2767351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
2768351d9b01SXinliang David Li 
2769351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
2770351d9b01SXinliang David Li     } else {
2771351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
2772351d9b01SXinliang David Li       // argument.
2773351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
2774351d9b01SXinliang David Li     }
2775351d9b01SXinliang David Li   }
2776351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
277746c03668SPhilipp Krones   Cost += InlineConstants::InstrCost + CallPenalty;
2778351d9b01SXinliang David Li   return Cost;
2779351d9b01SXinliang David Li }
2780351d9b01SXinliang David Li 
getInlineCost(CallBase & Call,const InlineParams & Params,TargetTransformInfo & CalleeTTI,function_ref<AssumptionCache & (Function &)> GetAssumptionCache,function_ref<const TargetLibraryInfo & (Function &)> GetTLI,function_ref<BlockFrequencyInfo & (Function &)> GetBFI,ProfileSummaryInfo * PSI,OptimizationRemarkEmitter * ORE)2781ab6a6837SSean Silva InlineCost llvm::getInlineCost(
2782652168a9SFedor Sergeev     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
278308e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2784f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
278508e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
27860812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2787652168a9SFedor Sergeev   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
278808e2386dSMircea Trofin                        GetAssumptionCache, GetTLI, GetBFI, PSI, ORE);
2789b9f7120eSEaswaran Raman }
2790b9f7120eSEaswaran Raman 
getInliningCostEstimate(CallBase & Call,TargetTransformInfo & CalleeTTI,function_ref<AssumptionCache & (Function &)> GetAssumptionCache,function_ref<BlockFrequencyInfo & (Function &)> GetBFI,ProfileSummaryInfo * PSI,OptimizationRemarkEmitter * ORE)2791011a07c0SMircea Trofin Optional<int> llvm::getInliningCostEstimate(
27928a4013edSMircea Trofin     CallBase &Call, TargetTransformInfo &CalleeTTI,
279308e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
279408e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
27958a4013edSMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
27968a4013edSMircea Trofin   const InlineParams Params = {/* DefaultThreshold*/ 0,
27978a4013edSMircea Trofin                                /*HintThreshold*/ {},
27988a4013edSMircea Trofin                                /*ColdThreshold*/ {},
27998a4013edSMircea Trofin                                /*OptSizeThreshold*/ {},
28008a4013edSMircea Trofin                                /*OptMinSizeThreshold*/ {},
28018a4013edSMircea Trofin                                /*HotCallSiteThreshold*/ {},
28028a4013edSMircea Trofin                                /*LocallyHotCallSiteThreshold*/ {},
28038a4013edSMircea Trofin                                /*ColdCallSiteThreshold*/ {},
2804347a599eSKazu Hirata                                /*ComputeFullInlineCost*/ true,
2805347a599eSKazu Hirata                                /*EnableDeferral*/ true};
28068a4013edSMircea Trofin 
280708e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
280808e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE, true,
28098a4013edSMircea Trofin                             /*IgnoreThreshold*/ true);
28108a4013edSMircea Trofin   auto R = CA.analyze();
28118a4013edSMircea Trofin   if (!R.isSuccess())
28128a4013edSMircea Trofin     return None;
28138a4013edSMircea Trofin   return CA.getCost();
28148a4013edSMircea Trofin }
28158a4013edSMircea Trofin 
getInliningCostFeatures(CallBase & Call,TargetTransformInfo & CalleeTTI,function_ref<AssumptionCache & (Function &)> GetAssumptionCache,function_ref<BlockFrequencyInfo & (Function &)> GetBFI,ProfileSummaryInfo * PSI,OptimizationRemarkEmitter * ORE)281699f00635SJacob Hegna Optional<InlineCostFeatures> llvm::getInliningCostFeatures(
281799f00635SJacob Hegna     CallBase &Call, TargetTransformInfo &CalleeTTI,
281899f00635SJacob Hegna     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
281999f00635SJacob Hegna     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
282099f00635SJacob Hegna     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
282199f00635SJacob Hegna   InlineCostFeaturesAnalyzer CFA(CalleeTTI, GetAssumptionCache, GetBFI, PSI,
282299f00635SJacob Hegna                                  ORE, *Call.getCalledFunction(), Call);
282399f00635SJacob Hegna   auto R = CFA.analyze();
282499f00635SJacob Hegna   if (!R.isSuccess())
282599f00635SJacob Hegna     return None;
282699f00635SJacob Hegna   return CFA.features();
282799f00635SJacob Hegna }
282899f00635SJacob Hegna 
getAttributeBasedInliningDecision(CallBase & Call,Function * Callee,TargetTransformInfo & CalleeTTI,function_ref<const TargetLibraryInfo & (Function &)> GetTLI)2829201498c6SMircea Trofin Optional<InlineResult> llvm::getAttributeBasedInliningDecision(
2830201498c6SMircea Trofin     CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
2831201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
2832f4bb2f0dSEaswaran Raman 
28337adc3a2bSChandler Carruth   // Cannot inline indirect calls.
28347adc3a2bSChandler Carruth   if (!Callee)
2835201498c6SMircea Trofin     return InlineResult::failure("indirect call");
28367adc3a2bSChandler Carruth 
283731e60b91SXun Li   // When callee coroutine function is inlined into caller coroutine function
283831e60b91SXun Li   // before coro-split pass,
283931e60b91SXun Li   // coro-early pass can not handle this quiet well.
284031e60b91SXun Li   // So we won't inline the coroutine function if it have not been unsplited
284131e60b91SXun Li   if (Callee->isPresplitCoroutine())
284231e60b91SXun Li     return InlineResult::failure("unsplited coroutine call");
284331e60b91SXun Li 
28443851496eSBjorn Pettersson   // Never inline calls with byval arguments that does not have the alloca
28453851496eSBjorn Pettersson   // address space. Since byval arguments can be replaced with a copy to an
28463851496eSBjorn Pettersson   // alloca, the inlined code would need to be adjusted to handle that the
28473851496eSBjorn Pettersson   // argument is in the alloca address space (so it is a little bit complicated
28483851496eSBjorn Pettersson   // to solve).
28493851496eSBjorn Pettersson   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2850652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2851652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2852652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
28533851496eSBjorn Pettersson       if (PTy->getAddressSpace() != AllocaAS)
2854201498c6SMircea Trofin         return InlineResult::failure("byval arguments without alloca"
2855c0aa4b75SDavid Bolvansky                                      " address space");
28563851496eSBjorn Pettersson     }
28573851496eSBjorn Pettersson 
28587adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
28597adc3a2bSChandler Carruth   // whenever possible.
2860652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
2861f0e6ec15SDávid Bolvanský     if (Call.getAttributes().hasFnAttr(Attribute::NoInline))
2862f0e6ec15SDávid Bolvanský       return InlineResult::failure("noinline call site attribute");
2863f0e6ec15SDávid Bolvanský 
286415b17d0aSYevgeny Rouban     auto IsViable = isInlineViable(*Callee);
28655466597fSMircea Trofin     if (IsViable.isSuccess())
2866201498c6SMircea Trofin       return InlineResult::success();
2867201498c6SMircea Trofin     return InlineResult::failure(IsViable.getFailureReason());
28687adc3a2bSChandler Carruth   }
28697adc3a2bSChandler Carruth 
28707adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
28717adc3a2bSChandler Carruth   // always-inline attribute).
2872652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
2873f9ca75f1STeresa Johnson   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI, GetTLI))
2874201498c6SMircea Trofin     return InlineResult::failure("conflicting attributes");
28757adc3a2bSChandler Carruth 
28767adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
287785bd3978SEvandro Menezes   if (Caller->hasOptNone())
2878201498c6SMircea Trofin     return InlineResult::failure("optnone attribute");
28797adc3a2bSChandler Carruth 
288077eeac3dSManoj Gupta   // Don't inline a function that treats null pointer as valid into a caller
288177eeac3dSManoj Gupta   // that does not have this attribute.
288277eeac3dSManoj Gupta   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2883201498c6SMircea Trofin     return InlineResult::failure("nullptr definitions incompatible");
288477eeac3dSManoj Gupta 
2885c0aa4b75SDavid Bolvansky   // Don't inline functions which can be interposed at link-time.
2886c0aa4b75SDavid Bolvansky   if (Callee->isInterposable())
2887201498c6SMircea Trofin     return InlineResult::failure("interposable");
2888c0aa4b75SDavid Bolvansky 
2889c0aa4b75SDavid Bolvansky   // Don't inline functions marked noinline.
2890c0aa4b75SDavid Bolvansky   if (Callee->hasFnAttribute(Attribute::NoInline))
2891201498c6SMircea Trofin     return InlineResult::failure("noinline function attribute");
2892c0aa4b75SDavid Bolvansky 
2893c0aa4b75SDavid Bolvansky   // Don't inline call sites marked noinline.
2894652168a9SFedor Sergeev   if (Call.isNoInline())
2895201498c6SMircea Trofin     return InlineResult::failure("noinline call site attribute");
2896201498c6SMircea Trofin 
2897201498c6SMircea Trofin   return None;
2898201498c6SMircea Trofin }
2899201498c6SMircea Trofin 
getInlineCost(CallBase & Call,Function * Callee,const InlineParams & Params,TargetTransformInfo & CalleeTTI,function_ref<AssumptionCache & (Function &)> GetAssumptionCache,function_ref<const TargetLibraryInfo & (Function &)> GetTLI,function_ref<BlockFrequencyInfo & (Function &)> GetBFI,ProfileSummaryInfo * PSI,OptimizationRemarkEmitter * ORE)2900201498c6SMircea Trofin InlineCost llvm::getInlineCost(
2901201498c6SMircea Trofin     CallBase &Call, Function *Callee, const InlineParams &Params,
2902201498c6SMircea Trofin     TargetTransformInfo &CalleeTTI,
290308e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2904201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
290508e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2906201498c6SMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2907201498c6SMircea Trofin 
2908201498c6SMircea Trofin   auto UserDecision =
2909201498c6SMircea Trofin       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
2910201498c6SMircea Trofin 
2911e0e687a6SKazu Hirata   if (UserDecision) {
2912201498c6SMircea Trofin     if (UserDecision->isSuccess())
2913201498c6SMircea Trofin       return llvm::InlineCost::getAlways("always inline attribute");
2914201498c6SMircea Trofin     return llvm::InlineCost::getNever(UserDecision->getFailureReason());
2915201498c6SMircea Trofin   }
29167adc3a2bSChandler Carruth 
2917d34e60caSNicola Zaghen   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
2918201498c6SMircea Trofin                           << "... (caller:" << Call.getCaller()->getName()
2919201498c6SMircea Trofin                           << ")\n");
29207adc3a2bSChandler Carruth 
292108e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
292208e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE);
292393ac81ccSMircea Trofin   InlineResult ShouldInline = CA.analyze();
29247adc3a2bSChandler Carruth 
2925d34e60caSNicola Zaghen   LLVM_DEBUG(CA.dump());
29267adc3a2bSChandler Carruth 
29276869e6c1SWenlei He   // Always make cost benefit based decision explicit.
29286869e6c1SWenlei He   // We use always/never here since threshold is not meaningful,
29296869e6c1SWenlei He   // as it's not what drives cost-benefit analysis.
29306869e6c1SWenlei He   if (CA.wasDecidedByCostBenefit()) {
29316869e6c1SWenlei He     if (ShouldInline.isSuccess())
29324bdfea2cSLiqiang Tao       return InlineCost::getAlways("benefit over cost",
29334bdfea2cSLiqiang Tao                                    CA.getCostBenefitPair());
29346869e6c1SWenlei He     else
29354bdfea2cSLiqiang Tao       return InlineCost::getNever("cost over benefit", CA.getCostBenefitPair());
29366869e6c1SWenlei He   }
29376869e6c1SWenlei He 
29383f96f7b3SArtur Pilipenko   if (CA.wasDecidedByCostThreshold())
29393f96f7b3SArtur Pilipenko     return InlineCost::get(CA.getCost(), CA.getThreshold());
29407adc3a2bSChandler Carruth 
29413f96f7b3SArtur Pilipenko   // No details on how the decision was made, simply return always or never.
29423f96f7b3SArtur Pilipenko   return ShouldInline.isSuccess()
29433f96f7b3SArtur Pilipenko              ? InlineCost::getAlways("empty function")
29443f96f7b3SArtur Pilipenko              : InlineCost::getNever(ShouldInline.getFailureReason());
29457adc3a2bSChandler Carruth }
29467adc3a2bSChandler Carruth 
isInlineViable(Function & F)294715b17d0aSYevgeny Rouban InlineResult llvm::isInlineViable(Function &F) {
29487adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
294991aff1d8SNick Desaulniers   for (BasicBlock &BB : F) {
2950639b29b1SNick Desaulniers     // Disallow inlining of functions which contain indirect branches.
295191aff1d8SNick Desaulniers     if (isa<IndirectBrInst>(BB.getTerminator()))
29525466597fSMircea Trofin       return InlineResult::failure("contains indirect branches");
295315b17d0aSYevgeny Rouban 
2954639b29b1SNick Desaulniers     // Disallow inlining of blockaddresses which are used by non-callbr
2955639b29b1SNick Desaulniers     // instructions.
295691aff1d8SNick Desaulniers     if (BB.hasAddressTaken())
295791aff1d8SNick Desaulniers       for (User *U : BlockAddress::get(&BB)->users())
2958639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
29595466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
29607adc3a2bSChandler Carruth 
296191aff1d8SNick Desaulniers     for (auto &II : BB) {
2962652168a9SFedor Sergeev       CallBase *Call = dyn_cast<CallBase>(&II);
2963652168a9SFedor Sergeev       if (!Call)
29647adc3a2bSChandler Carruth         continue;
29657adc3a2bSChandler Carruth 
29667adc3a2bSChandler Carruth       // Disallow recursive calls.
2967bc044a88SNick Desaulniers       Function *Callee = Call->getCalledFunction();
2968bc044a88SNick Desaulniers       if (&F == Callee)
29695466597fSMircea Trofin         return InlineResult::failure("recursive call");
29707adc3a2bSChandler Carruth 
29717adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
29727adc3a2bSChandler Carruth       // attributed as such.
2973652168a9SFedor Sergeev       if (!ReturnsTwice && isa<CallInst>(Call) &&
2974652168a9SFedor Sergeev           cast<CallInst>(Call)->canReturnTwice())
29755466597fSMircea Trofin         return InlineResult::failure("exposes returns-twice attribute");
29767adc3a2bSChandler Carruth 
2977bc044a88SNick Desaulniers       if (Callee)
2978bc044a88SNick Desaulniers         switch (Callee->getIntrinsicID()) {
29791636651eSFlorian Hahn         default:
29801636651eSFlorian Hahn           break;
298106408758SMircea Trofin         case llvm::Intrinsic::icall_branch_funnel:
29824296ea72SVitaly Buka           // Disallow inlining of @llvm.icall.branch.funnel because current
29834296ea72SVitaly Buka           // backend can't separate call targets from call arguments.
29845466597fSMircea Trofin           return InlineResult::failure(
29855466597fSMircea Trofin               "disallowed inlining of @llvm.icall.branch.funnel");
298606408758SMircea Trofin         case llvm::Intrinsic::localescape:
29877adc3a2bSChandler Carruth           // Disallow inlining functions that call @llvm.localescape. Doing this
29887adc3a2bSChandler Carruth           // correctly would require major changes to the inliner.
29895466597fSMircea Trofin           return InlineResult::failure(
29905466597fSMircea Trofin               "disallowed inlining of @llvm.localescape");
29911636651eSFlorian Hahn         case llvm::Intrinsic::vastart:
299206408758SMircea Trofin           // Disallow inlining of functions that initialize VarArgs with
299306408758SMircea Trofin           // va_start.
29945466597fSMircea Trofin           return InlineResult::failure(
29955466597fSMircea Trofin               "contains VarArgs initialized with va_start");
29967adc3a2bSChandler Carruth         }
29977adc3a2bSChandler Carruth     }
29981636651eSFlorian Hahn   }
29997adc3a2bSChandler Carruth 
30005466597fSMircea Trofin   return InlineResult::success();
30017adc3a2bSChandler Carruth }
30021c57cc2bSEaswaran Raman 
30031c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
30041c57cc2bSEaswaran Raman // parameters.
30051c57cc2bSEaswaran Raman 
getInlineParams(int Threshold)30061c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
30071c57cc2bSEaswaran Raman   InlineParams Params;
30081c57cc2bSEaswaran Raman 
30091c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
30101c57cc2bSEaswaran Raman   // derived from one or more of:
30111c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
30121c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
30131c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
30141c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
30151c57cc2bSEaswaran Raman   //  irrespective of anything else.
30161c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
30171c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
30181c57cc2bSEaswaran Raman   else
30191c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
30201c57cc2bSEaswaran Raman 
30211c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
30221c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
30231c57cc2bSEaswaran Raman 
30241c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
30251c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
30261c57cc2bSEaswaran Raman 
3027974d4eeaSEaswaran Raman   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
3028974d4eeaSEaswaran Raman   // populate LocallyHotCallSiteThreshold. Later, we populate
3029974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
3030974d4eeaSEaswaran Raman   // we know that optimization level is O3 (in the getInlineParams variant that
3031974d4eeaSEaswaran Raman   // takes the opt and size levels).
3032974d4eeaSEaswaran Raman   // FIXME: Remove this check (and make the assignment unconditional) after
3033974d4eeaSEaswaran Raman   // addressing size regression issues at O2.
3034974d4eeaSEaswaran Raman   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
3035974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
3036974d4eeaSEaswaran Raman 
30375a956c85SMircea Trofin   // Set the ColdCallSiteThreshold knob from the
30385a956c85SMircea Trofin   // -inline-cold-callsite-threshold.
303912585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
304012585b01SEaswaran Raman 
30411c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
30421c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
30431c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
30441c57cc2bSEaswaran Raman   // minsize attributes.
30451c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
30461c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
30471c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
30481c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
30491c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
30501c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
30511c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
30521c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
30531c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
30541c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
30551c57cc2bSEaswaran Raman   }
30561c57cc2bSEaswaran Raman   return Params;
30571c57cc2bSEaswaran Raman }
30581c57cc2bSEaswaran Raman 
getInlineParams()30591c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
30607f37a802STeresa Johnson   return getInlineParams(DefaultThreshold);
30611c57cc2bSEaswaran Raman }
30621c57cc2bSEaswaran Raman 
30631c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
30641c57cc2bSEaswaran Raman // size opt level.
computeThresholdFromOptLevels(unsigned OptLevel,unsigned SizeOptLevel)30651c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
30661c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
30671c57cc2bSEaswaran Raman   if (OptLevel > 2)
30681c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
30691c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
30701c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
30711c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
30721c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
30737f37a802STeresa Johnson   return DefaultThreshold;
30741c57cc2bSEaswaran Raman }
30751c57cc2bSEaswaran Raman 
getInlineParams(unsigned OptLevel,unsigned SizeOptLevel)30761c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
3077974d4eeaSEaswaran Raman   auto Params =
3078974d4eeaSEaswaran Raman       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
3079974d4eeaSEaswaran Raman   // At O3, use the value of -locally-hot-callsite-threshold option to populate
3080974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
3081974d4eeaSEaswaran Raman   // when it is specified explicitly.
3082974d4eeaSEaswaran Raman   if (OptLevel > 2)
3083974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
3084974d4eeaSEaswaran Raman   return Params;
30851c57cc2bSEaswaran Raman }
30866a5d7d49SKirill Naumov 
30876a5d7d49SKirill Naumov PreservedAnalyses
run(Function & F,FunctionAnalysisManager & FAM)30886a5d7d49SKirill Naumov InlineCostAnnotationPrinterPass::run(Function &F,
30896a5d7d49SKirill Naumov                                      FunctionAnalysisManager &FAM) {
30906a5d7d49SKirill Naumov   PrintInstructionComments = true;
30917b639f50SJacob Hegna   std::function<AssumptionCache &(Function &)> GetAssumptionCache =
30927b639f50SJacob Hegna       [&](Function &F) -> AssumptionCache & {
30936a5d7d49SKirill Naumov     return FAM.getResult<AssumptionAnalysis>(F);
30946a5d7d49SKirill Naumov   };
30956a5d7d49SKirill Naumov   Module *M = F.getParent();
30966a5d7d49SKirill Naumov   ProfileSummaryInfo PSI(*M);
30976a5d7d49SKirill Naumov   DataLayout DL(M);
30986a5d7d49SKirill Naumov   TargetTransformInfo TTI(DL);
30996a5d7d49SKirill Naumov   // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
31006a5d7d49SKirill Naumov   // In the current implementation, the type of InlineParams doesn't matter as
31016a5d7d49SKirill Naumov   // the pass serves only for verification of inliner's decisions.
31026a5d7d49SKirill Naumov   // We can add a flag which determines InlineParams for this run. Right now,
31036a5d7d49SKirill Naumov   // the default InlineParams are used.
31046a5d7d49SKirill Naumov   const InlineParams Params = llvm::getInlineParams();
31056a5d7d49SKirill Naumov   for (BasicBlock &BB : F) {
31066a5d7d49SKirill Naumov     for (Instruction &I : BB) {
31076a5d7d49SKirill Naumov       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
31086a5d7d49SKirill Naumov         Function *CalledFunction = CI->getCalledFunction();
31096a5d7d49SKirill Naumov         if (!CalledFunction || CalledFunction->isDeclaration())
31106a5d7d49SKirill Naumov           continue;
31116a5d7d49SKirill Naumov         OptimizationRemarkEmitter ORE(CalledFunction);
31126a5d7d49SKirill Naumov         InlineCostCallAnalyzer ICCA(*CalledFunction, *CI, Params, TTI,
31136a5d7d49SKirill Naumov                                     GetAssumptionCache, nullptr, &PSI, &ORE);
31146a5d7d49SKirill Naumov         ICCA.analyze();
31156a5d7d49SKirill Naumov         OS << "      Analyzing call of " << CalledFunction->getName()
31166a5d7d49SKirill Naumov            << "... (caller:" << CI->getCaller()->getName() << ")\n";
3117ecd25edfSArthur Eubanks         ICCA.print(OS);
3118ecd25edfSArthur Eubanks         OS << "\n";
31196a5d7d49SKirill Naumov       }
31206a5d7d49SKirill Naumov     }
31216a5d7d49SKirill Naumov   }
31226a5d7d49SKirill Naumov   return PreservedAnalyses::all();
31236a5d7d49SKirill Naumov }
3124