73 #define DEBUG_TYPE "inline" 75 STATISTIC(NumInlined,
"Number of functions inlined");
76 STATISTIC(NumCallsDeleted,
"Number of call sites deleted, not inlined");
77 STATISTIC(NumDeleted,
"Number of functions deleted because all callers found");
78 STATISTIC(NumMergedAllocas,
"Number of allocas merged together");
83 STATISTIC(NumCallerCallersAnalyzed,
"Number of caller-callers analyzed");
107 "inliner-function-import-stats",
111 clEnumValN(InlinerFunctionImportStatsOpts::Verbose,
"verbose",
112 "printing of statistics for each inlined function")),
170 if (InlineHistory != -1)
175 for (
unsigned AllocaNo = 0, e = IFI.
StaticAllocas.size(); AllocaNo != e;
187 std::vector<AllocaInst *> &AllocasForType = InlinedArrayAllocas[ATy];
194 bool MergedAwayAlloca =
false;
195 for (
AllocaInst *AvailableAlloca : AllocasForType) {
197 Align2 = AvailableAlloca->getAlignment();
201 if (AvailableAlloca->getParent() != AI->
getParent())
206 if (!UsedAllocas.
insert(AvailableAlloca).second)
212 <<
"\n\t\tINTO: " << *AvailableAlloca <<
'\n');
220 DDI->moveBefore(AvailableAlloca->getNextNode());
224 if (Align1 != Align2) {
225 if (!Align1 || !Align2) {
229 Align1 = Align1 ? Align1 : TypeAlign;
230 Align2 = Align2 ? Align2 : TypeAlign;
238 MergedAwayAlloca =
true;
245 if (MergedAwayAlloca)
253 AllocasForType.push_back(AI);
299 int &TotalSecondaryCost,
320 TotalSecondaryCost = 0;
322 int CandidateCost = IC.
getCost() - 1;
326 bool inliningPreventsSomeOuterInline =
false;
334 callerWillBeRemoved =
false;
339 ++NumCallerCallersAnalyzed;
341 callerWillBeRemoved =
false;
351 inliningPreventsSomeOuterInline =
true;
352 TotalSecondaryCost += IC2.
getCost();
359 if (callerWillBeRemoved && !Caller->
hasOneUse())
362 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.
getCost())
392 <<
NV(
"Callee", Callee) <<
" not inlined into " 393 <<
NV(
"Caller", Caller)
394 <<
" because it should never be inlined (cost=never)";
405 <<
NV(
"Callee", Callee) <<
" not inlined into " 406 <<
NV(
"Caller", Caller) <<
" because too costly to inline (cost=" 413 int TotalSecondaryCost = 0;
417 <<
", outer Cost = " << TotalSecondaryCost <<
'\n');
421 <<
"Not inlining. Cost of inlining " <<
NV(
"Callee", Callee)
422 <<
" increases the cost of inlining " <<
NV(
"Caller", Caller)
423 <<
" in other contexts";
442 while (InlineHistoryID != -1) {
443 assert(
unsigned(InlineHistoryID) < InlineHistory.size() &&
444 "Invalid inline history ID");
445 if (InlineHistory[InlineHistoryID].
first == F)
447 InlineHistoryID = InlineHistory[InlineHistoryID].second;
503 if (!CS || isa<IntrinsicInst>(
I))
510 if (
Callee->isDeclaration()) {
515 <<
NV(
"Callee",
Callee) <<
" will not be inlined into " 517 <<
" because its definition is unavailable" 523 CallSites.
push_back(std::make_pair(CS, -1));
530 if (CallSites.
empty())
535 unsigned FirstCallInSCC = CallSites.
size();
536 for (
unsigned i = 0; i < FirstCallInSCC; ++i)
538 if (SCCFunctions.
count(
F))
539 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
546 bool Changed =
false;
553 for (
unsigned CSi = 0; CSi != CallSites.
size(); ++CSi) {
568 if (!IsTriviallyDead) {
574 InlineHistoryID = CallSites[CSi].second;
575 if (InlineHistoryID != -1 &&
595 if (IsTriviallyDead) {
596 LLVM_DEBUG(
dbgs() <<
" -> Deleting dead call: " << *Instr <<
"\n");
598 CG[Caller]->removeCallEdgeFor(CS);
610 InlineHistoryID, InsertLifetime, AARGetter,
611 ImportedFunctionsStats)) {
615 <<
NV(
"Callee", Callee) <<
" will not be inlined into " 616 <<
NV(
"Caller", Caller);
623 bool AlwaysInline = OIC->
isAlways();
624 StringRef RemarkName = AlwaysInline ?
"AlwaysInline" :
"Inlined";
626 R <<
NV(
"Callee", Callee) <<
" inlined into ";
627 R <<
NV(
"Caller", Caller);
629 R <<
" with cost=always";
631 R <<
" with cost=" <<
NV(
"Cost", OIC->
getCost());
643 int NewHistoryID = InlineHistory.
size();
644 InlineHistory.
push_back(std::make_pair(Callee, InlineHistoryID));
655 !SCCFunctions.
count(Callee) &&
659 CG[
Callee]->getNumReferences() == 0) {
665 CalleeNode->removeAllCalledFunctions();
676 if (SCC.isSingular()) {
677 CallSites[CSi] = CallSites.
back();
687 }
while (LocalChange);
693 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
694 ACT = &getAnalysis<AssumptionCacheTracker>();
695 PSI = getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
696 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
700 return inlineCallsImpl(SCC, CG, GetAssumptionCache, PSI, TLI, InsertLifetime,
710 InlinerFunctionImportStatsOpts::Verbose);
716 bool AlwaysInlineOnly) {
722 CGN->removeAllCalledFunctions();
735 for (
const auto &
I : CG) {
744 if (AlwaysInlineOnly && !F->
hasFnAttribute(Attribute::AlwaysInline))
767 if (!DeadFunctionsInComdats.
empty()) {
771 for (
Function *
F : DeadFunctionsInComdats)
775 if (FunctionsToRemove.
empty())
786 FunctionsToRemove.
erase(
787 std::unique(FunctionsToRemove.
begin(), FunctionsToRemove.
end()),
788 FunctionsToRemove.
end());
790 delete CG.removeFunctionFromModule(CGN);
800 InlinerFunctionImportStatsOpts::Verbose);
809 bool Changed =
false;
811 assert(InitialC.size() > 0 &&
"Cannot handle an empty SCC!");
812 Module &M = *InitialC.begin()->getFunction().getParent();
818 llvm::make_unique<ImportedFunctionsInliningStatistics>();
853 for (
auto &
N : InitialC) {
864 if (!
Callee->isDeclaration())
866 else if (!isa<IntrinsicInst>(
I)) {
870 <<
NV(
"Callee",
Callee) <<
" will not be inlined into " 872 <<
" because its definition is unavailable" 883 auto *RC = &
C->getOuterRefSCC();
902 for (
int i = 0; i < (int)Calls.
size(); ++i) {
907 Function &
F = *Calls[i].first.getCaller();
930 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
938 auto GetInlineCost = [&](
CallSite CS) {
941 return getInlineCost(CS, Params, CalleeTTI, GetAssumptionCache, {GetBFI},
948 bool DidInline =
false;
949 for (; i < (int)Calls.
size() && Calls[i].first.getCaller() == &
F; ++i) {
952 std::tie(CS, InlineHistoryID) = Calls[i];
955 if (InlineHistoryID != -1 &&
966 LLVM_DEBUG(
dbgs() <<
"Skipping inlining internal SCC edge from a node " 967 "previously split out of this SCC by inlining: " 980 nullptr, &GetAssumptionCache, PSI,
993 <<
NV(
"Callee", &Callee) <<
" will not be inlined into " 999 InlinedCallees.
insert(&Callee);
1002 bool AlwaysInline = OIC->
isAlways();
1003 StringRef RemarkName = AlwaysInline ?
"AlwaysInline" :
"Inlined";
1005 R <<
NV(
"Callee", &Callee) <<
" inlined into ";
1006 R <<
NV(
"Caller", &F);
1008 R <<
" with cost=always";
1010 R <<
" with cost=" <<
NV(
"Cost", OIC->
getCost());
1019 int NewHistoryID = InlineHistory.
size();
1023 if (!NewCallee->isDeclaration())
1044 [&
Callee](
const std::pair<CallSite, int> &Call) {
1045 return Call.first.getCaller() == &
Callee;
1053 assert(
find(DeadFunctions, &Callee) == DeadFunctions.
end() &&
1054 "Cannot put cause a function to become dead twice!");
1076 for (
Function *InlinedCallee : InlinedCallees) {
1079 RC->insertTrivialRefEdge(N,
E.getNode());
1091 RC = &C->getOuterRefSCC();
1108 LLVM_DEBUG(
dbgs() <<
"Inlined an internal call edge and split an SCC, " 1109 "retaining this to avoid infinite inlining.\n");
1112 InlinedCallees.clear();
1122 for (
Function *DeadF : DeadFunctions) {
1129 FAM.
clear(*DeadF, DeadF->getName());
1130 AM.
clear(DeadC, DeadC.getName());
1131 auto &DeadRC = DeadC.getOuterRefSCC();
1140 M.getFunctionList().erase(DeadF);
InlinerFunctionImportStatsOpts
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
bool doFinalization(CallGraph &CG) override
Remove now-dead linkonce functions at the end of processing to avoid breaking the SCC traversal...
void setModuleInfo(const Module &M)
Set information like AllFunctions, ImportedFunctions, ModuleName.
bool hasLocalLinkage() const
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
static bool InlineHistoryIncludes(Function *F, int InlineHistoryID, const SmallVectorImpl< std::pair< Function *, int >> &InlineHistory)
Return true if the specified inline history ID indicates an inline history that includes the specifie...
A Module instance is used to store all the information related to an LLVM module. ...
LazyCallGraph::SCC & updateCGAndAnalysisManagerForFunctionPass(LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR)
Helper to update the call graph after running a function pass.
void recordInline(const Function &Caller, const Function &Callee)
Record inline of.
void clear(IRUnitT &IR, llvm::StringRef Name)
Clear any cached analysis results for a single unit of IR.
virtual InlineCost getInlineCost(CallSite CS)=0
This method must be implemented by the subclass to determine the cost of inlining the specified call ...
SCC * lookupSCC(Node &N) const
Lookup a function's SCC in the graph.
Analysis providing profile information.
Implements a lazy call graph analysis and related passes for the new pass manager.
An immutable pass that tracks lazily created AssumptionCache objects.
An efficient, type-erasing, non-owning reference to a callable.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
LLVMContext & getContext() const
All values hold a context through their type.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
STATISTIC(NumFunctions, "Total number of functions")
Calculate and dump ThinLTO specific inliner stats.
InlineFunctionInfo - This class captures the data input to the InlineFunction call, and records the auxiliary results produced by it.
static void mergeInlinedArrayAllocas(Function *Caller, InlineFunctionInfo &IFI, InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory)
Look at all of the allocas that we inlined through this call site.
A proxy from a FunctionAnalysisManager to an SCC.
A node in the call graph for a module.
bool skipSCC(CallGraphSCC &SCC) const
Optional passes call this function to check whether the pass should be skipped.
void getAnalysisUsage(AnalysisUsage &Info) const override
getAnalysisUsage - For this class, we declare that we require and preserve the call graph...
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
Represents the cost of inlining a function.
Module & getModule() const
Returns the module the call graph corresponds to.
bool InlineFunction(CallInst *C, InlineFunctionInfo &IFI, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true)
InlineFunction - This function inlines the called function into the basic block of the caller...
AnalysisUsage & addRequired()
bool runOnSCC(CallGraphSCC &SCC) override
Main run interface method, this implements the interface required by the Pass class.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This class is a functor to be used in legacy module or SCC passes for computing AA results for a func...
bool isLibFunction(Function &F) const
Test whether a function is a known and defined library function tracked by the call graph...
This file contains the simple types necessary to represent the attributes associated with functions a...
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
InstrTy * getInstruction() const
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
static Optional< InlineCost > shouldInline(CallSite CS, function_ref< InlineCost(CallSite CS)> GetInlineCost, OptimizationRemarkEmitter &ORE)
Return the cost only if the inliner should attempt to inline at the given CallSite.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
bool insert(const value_type &X)
Insert a new element into the SetVector.
Class to represent array types.
A lazily constructed view of the call graph of a module.
const int LastCallToStaticBonus
DiagnosticInfoOptimizationBase::setIsVerbose setIsVerbose
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
amdgpu Simplify well known AMD library false Value * Callee
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
bool hasLinkOnceODRLinkage() const
SmallVector< CallSite, 8 > InlinedCallSites
All of the new call sites inlined into the caller.
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
void getAnalysisUsage(AnalysisUsage &Info) const override
For this class, we declare that we require and preserve the call graph.
void removeAnyCallEdgeTo(CallGraphNode *Callee)
Removes all call edges from this node to the specified callee function.
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
bool inlineCalls(CallGraphSCC &SCC)
This function performs the main work of the pass.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
SmallPtrSetImpl< LazyCallGraph::RefSCC * > & InvalidatedRefSCCs
The set of invalidated RefSCCs which should be skipped if they are found in RCWorklist.
SmallPtrSetImpl< LazyCallGraph::SCC * > & InvalidatedSCCs
The set of invalidated SCCs which should be skipped if they are found in CWorklist.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
A node in the call graph.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
A class used to represent edges in the call graph.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool doInitialization(CallGraph &CG) override
doInitialization - This method is called before the SCC's of the program has been processed...
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
int getThreshold() const
Get the threshold against which the cost was computed.
void getAAResultsAnalysisUsage(AnalysisUsage &AU)
A helper for the legacy pass manager to populate AU to add uses to make sure the analyses required by...
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Function * getFunction() const
Returns the function that this call graph node represents.
A function analysis which provides an AssumptionCache.
static bool inlineCallsImpl(CallGraphSCC &SCC, CallGraph &CG, std::function< AssumptionCache &(Function &)> GetAssumptionCache, ProfileSummaryInfo *PSI, TargetLibraryInfo &TLI, bool InsertLifetime, function_ref< InlineCost(CallSite CS)> GetInlineCost, function_ref< AAResults &(Function &)> AARGetter, ImportedFunctionsInliningStatistics &ImportedFunctionsStats)
A SetVector that performs no allocations if smaller than a certain size.
Analysis pass which computes BlockFrequencyInfo.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void removeDeadFunction(Function &F)
Remove a dead function from the call graph (typically to delete it).
ImportedFunctionsInliningStatistics ImportedFunctionsStats
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
static cl::opt< bool > DisableInlinedAllocaMerging("disable-inlined-alloca-merging", cl::init(false), cl::Hidden)
Flag to disable manual alloca merging.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
void dropAllReferences()
dropAllReferences() - This method causes all the subinstructions to "let go" of all references that t...
AssumptionCacheTracker * ACT
bool removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly=false)
Remove dead functions.
Node * lookup(const Function &F) const
Lookup a function in the graph which has already been scanned and added.
BBTy * getParent() const
Get the basic block containing the call site.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void mergeAttributesForInlining(Function &Caller, const Function &Callee)
Merge caller's and callee's attributes.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
void dump(bool Verbose)
Dump stats computed with InlinerStatistics class.
iterator_range< user_iterator > users()
static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI, InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory, bool InsertLifetime, function_ref< AAResults &(Function &)> &AARGetter, ImportedFunctionsInliningStatistics &ImportedFunctionsStats)
If it is possible to inline the specified call site, do so and update the CallGraph for this operatio...
int getCost() const
Get the inline cost estimate.
int getCostDelta() const
Get the cost delta from the threshold for inlining.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
void filterDeadComdatFunctions(Module &M, SmallVectorImpl< Function *> &DeadComdatFunctions)
Filter out potentially dead comdat functions where other entries keep the entire comdat group alive...
SmallVector< AllocaInst *, 4 > StaticAllocas
StaticAllocas - InlineFunction fills this in with all static allocas that get copied into the caller...
The basic data container for the call graph of a Module of IR.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
FunTy * getCaller() const
Return the caller function for this call site.
LegacyInlinerBase(char &ID)
LLVM_NODISCARD bool empty() const
SmallVector< WeakTrackingVH, 8 > InlinedCalls
InlinedCalls - InlineFunction fills this in with callsites that were inlined from the callee...
StringRef getName() const
Return a constant reference to the value's name.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
CallGraphNode * getExternalCallingNode() const
Returns the CallGraphNode which is used to represent undetermined calls into the callgraph.
This header provides classes for managing passes over SCCs of the call graph.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
An SCC of the call graph.
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
AssumptionCache & getAssumptionCache(Function &F)
Get the cached assumptions for a function.
print Print MemDeps of function
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
inst_range instructions(Function *F)
A container for analyses that lazily runs them and caches their results.
static bool shouldBeDeferred(Function *Caller, CallSite CS, InlineCost IC, int &TotalSecondaryCost, function_ref< InlineCost(CallSite CS)> GetInlineCost)
Return true if inlining of CS can block the caller from being inlined which is proved to be more bene...
static cl::opt< InlinerFunctionImportStatsOpts > InlinerFunctionImportStats("inliner-function-import-stats", cl::init(InlinerFunctionImportStatsOpts::No), cl::values(clEnumValN(InlinerFunctionImportStatsOpts::Basic, "basic", "basic statistics"), clEnumValN(InlinerFunctionImportStatsOpts::Verbose, "verbose", "printing of statistics for each inlined function")), cl::Hidden, cl::desc("Enable inliner stats for imported functions"))
This header defines various interfaces for pass management in LLVM.
SmallDenseSet< std::pair< LazyCallGraph::Node *, LazyCallGraph::SCC * >, 4 > & InlinedInternalEdges
A hacky area where the inliner can retain history about inlining decisions that mutated the call grap...
This represents the llvm.dbg.declare instruction.
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
const BasicBlock * getParent() const
an instruction to allocate memory on the stack