42 #define DEBUG_TYPE "inline"
44 STATISTIC(NumInlined,
"Number of functions inlined");
45 STATISTIC(NumCallsDeleted,
"Number of call sites deleted, not inlined");
46 STATISTIC(NumDeleted,
"Number of functions deleted because all callers found");
47 STATISTIC(NumMergedAllocas,
"Number of allocas merged together");
52 STATISTIC(NumCallerCallersAnalyzed,
"Number of caller-callers analyzed");
73 "inliner-function-import-stats",
74 cl::init(InlinerFunctionImportStatsOpts::No),
77 clEnumValN(InlinerFunctionImportStatsOpts::Verbose,
"verbose",
78 "printing of statistics for each inlined function")),
138 if (InlineHistory != -1)
143 for (
unsigned AllocaNo = 0, e = IFI.
StaticAllocas.size(); AllocaNo != e;
155 std::vector<AllocaInst *> &AllocasForType = InlinedArrayAllocas[ATy];
162 bool MergedAwayAlloca =
false;
163 for (
AllocaInst *AvailableAlloca : AllocasForType) {
166 Align2 = AvailableAlloca->getAlignment();
170 if (AvailableAlloca->getParent() != AI->
getParent())
175 if (!UsedAllocas.
insert(AvailableAlloca).second)
180 DEBUG(
dbgs() <<
" ***MERGED ALLOCA: " << *AI
181 <<
"\n\t\tINTO: " << *AvailableAlloca <<
'\n');
189 DDI->moveBefore(AvailableAlloca->getNextNode());
193 if (Align1 != Align2) {
194 if (!Align1 || !Align2) {
198 Align1 = Align1 ? Align1 : TypeAlign;
199 Align2 = Align2 ? Align2 : TypeAlign;
207 MergedAwayAlloca =
true;
214 if (MergedAwayAlloca)
222 AllocasForType.push_back(AI);
250 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
268 int &TotalSecondaryCost,
290 TotalSecondaryCost = 0;
292 int CandidateCost = IC.
getCost() - 1;
296 bool inliningPreventsSomeOuterInline =
false;
304 callerWillBeRemoved =
false;
309 ++NumCallerCallersAnalyzed;
311 callerWillBeRemoved =
false;
321 inliningPreventsSomeOuterInline =
true;
322 TotalSecondaryCost += IC2.
getCost();
329 if (callerWillBeRemoved && !Caller->
hasOneUse())
332 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.
getCost())
352 <<
NV(
"Callee", Callee)
353 <<
" should always be inlined (cost=always)");
358 DEBUG(
dbgs() <<
" NOT Inlining: cost=never"
361 <<
NV(
"Callee", Callee) <<
" not inlined into "
362 <<
NV(
"Caller", Caller)
363 <<
" because it should never be inlined (cost=never)");
372 <<
NV(
"Callee", Callee) <<
" not inlined into "
373 <<
NV(
"Caller", Caller) <<
" because too costly to inline (cost="
374 <<
NV(
"Cost", IC.
getCost()) <<
", threshold="
379 int TotalSecondaryCost = 0;
383 <<
", outer Cost = " << TotalSecondaryCost <<
'\n');
386 <<
"Not inlining. Cost of inlining " <<
NV(
"Callee", Callee)
387 <<
" increases the cost of inlining " <<
NV(
"Caller", Caller)
388 <<
" in other contexts");
396 <<
NV(
"Callee", Callee) <<
" can be inlined into "
397 <<
NV(
"Caller", Caller) <<
" with cost=" <<
NV(
"Cost", IC.
getCost())
408 while (InlineHistoryID != -1) {
409 assert(
unsigned(InlineHistoryID) < InlineHistory.size() &&
410 "Invalid inline history ID");
411 if (InlineHistory[InlineHistoryID].
first == F)
413 InlineHistoryID = InlineHistory[InlineHistoryID].second;
419 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
439 DEBUG(
dbgs() <<
"Inliner visiting SCC:");
469 if (!CS || isa<IntrinsicInst>(
I))
476 if (Callee->isDeclaration()) {
479 <<
NV(
"Callee", Callee) <<
" will not be inlined into "
481 <<
" because its definition is unavailable"
486 CallSites.
push_back(std::make_pair(CS, -1));
490 DEBUG(
dbgs() <<
": " << CallSites.
size() <<
" call sites.\n");
493 if (CallSites.
empty())
498 unsigned FirstCallInSCC = CallSites.
size();
499 for (
unsigned i = 0; i < FirstCallInSCC; ++i)
501 if (SCCFunctions.
count(
F))
502 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
509 bool Changed =
false;
516 for (
unsigned CSi = 0; CSi != CallSites.
size(); ++CSi) {
531 if (!IsTriviallyDead) {
537 InlineHistoryID = CallSites[CSi].second;
538 if (InlineHistoryID != -1 &&
557 if (IsTriviallyDead) {
558 DEBUG(
dbgs() <<
" -> Deleting dead call: " << *Instr <<
"\n");
560 CG[Caller]->removeCallEdgeFor(CS);
571 InlineHistoryID, InsertLifetime, AARGetter,
572 ImportedFunctionsStats)) {
575 <<
NV(
"Callee", Callee) <<
" will not be inlined into "
576 <<
NV(
"Caller", Caller));
583 <<
NV(
"Callee", Callee) <<
" inlined into "
584 <<
NV(
"Caller", Caller));
591 int NewHistoryID = InlineHistory.
size();
592 InlineHistory.
push_back(std::make_pair(Callee, InlineHistoryID));
603 !SCCFunctions.
count(Callee) &&
608 CG[Callee]->getNumReferences() == 0) {
614 CalleeNode->removeAllCalledFunctions();
625 if (SCC.isSingular()) {
626 CallSites[CSi] = CallSites.
back();
636 }
while (LocalChange);
642 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
643 ACT = &getAnalysis<AssumptionCacheTracker>();
644 PSI = getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
645 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
649 return inlineCallsImpl(SCC, CG, GetAssumptionCache, PSI, TLI, InsertLifetime,
657 if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
659 InlinerFunctionImportStatsOpts::Verbose);
665 bool AlwaysInlineOnly) {
671 CGN->removeAllCalledFunctions();
684 for (
const auto &
I : CG) {
693 if (AlwaysInlineOnly && !F->
hasFnAttribute(Attribute::AlwaysInline))
716 if (!DeadFunctionsInComdats.
empty()) {
720 for (
Function *
F : DeadFunctionsInComdats)
724 if (FunctionsToRemove.
empty())
735 FunctionsToRemove.
erase(
736 std::unique(FunctionsToRemove.
begin(), FunctionsToRemove.
end()),
737 FunctionsToRemove.
end());
739 delete CG.removeFunctionFromModule(CGN);
750 bool Changed =
false;
752 assert(InitialC.size() > 0 &&
"Cannot handle an empty SCC!");
753 Module &M = *InitialC.begin()->getFunction().getParent();
783 for (
auto &
N : InitialC) {
792 if (!Callee->isDeclaration())
793 Calls.push_back({CS, -1});
800 auto *RC = &
C->getOuterRefSCC();
819 for (
int i = 0; i < (int)Calls.size(); ++i) {
824 Function &
F = *Calls[i].first.getCaller();
826 if (CG.lookupSCC(N) !=
C)
843 std::function<AssumptionCache &(Function &)> GetAssumptionCache =
851 auto GetInlineCost = [&](
CallSite CS) {
854 return getInlineCost(CS, Params, CalleeTTI, GetAssumptionCache, {GetBFI},
864 bool DidInline =
false;
865 for (; i < (int)Calls.size() && Calls[i].first.getCaller() == &
F; ++i) {
868 std::tie(CS, InlineHistoryID) = Calls[i];
871 if (InlineHistoryID != -1 &&
882 nullptr, &GetAssumptionCache, PSI,
889 InlinedCallees.
insert(&Callee);
893 int NewHistoryID = InlineHistory.
size();
894 InlineHistory.
push_back({&Callee, InlineHistoryID});
897 if (!NewCallee->isDeclaration())
898 Calls.push_back({CS, NewHistoryID});
912 if (Callee.
use_empty() && !CG.isLibFunction(Callee)) {
915 [&Callee](
const std::pair<CallSite, int> &
Call) {
916 return Call.first.getCaller() == &Callee;
924 assert(
find(DeadFunctions, &Callee) == DeadFunctions.
end() &&
925 "Cannot put cause a function to become dead twice!");
947 for (
Function *InlinedCallee : InlinedCallees) {
950 RC->insertTrivialRefEdge(N,
E.getNode());
952 InlinedCallees.clear();
961 DEBUG(
dbgs() <<
"Updated inlining SCC: " << *C <<
"\n");
962 RC = &C->getOuterRefSCC();
972 for (
Function *DeadF : DeadFunctions) {
975 auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF));
981 auto &DeadRC = DeadC.getOuterRefSCC();
982 CG.removeDeadFunction(*DeadF);
986 UR.InvalidatedSCCs.insert(&DeadC);
987 UR.InvalidatedRefSCCs.insert(&DeadRC);
990 M.getFunctionList().erase(DeadF);
InlinerFunctionImportStatsOpts
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
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. ...
FunTy * getCaller() const
Return the caller function for this call site.
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.
DiagnosticInfoOptimizationBase::Argument NV
STATISTIC(NumFunctions,"Total number of functions")
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. ...
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
void recordInline(const Function &Caller, const Function &Callee)
Record inline of.
virtual InlineCost getInlineCost(CallSite CS)=0
This method must be implemented by the subclass to determine the cost of inlining the specified call ...
Analysis providing profile information.
BBTy * getParent() const
Get the basic block containing the call site.
An immutable pass that tracks lazily created AssumptionCache objects.
An efficient, type-erasing, non-owning reference to a callable.
A cache of .assume calls within a function.
Analysis pass providing the TargetTransformInfo.
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.
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.
StringRef getName() const
Return a constant reference to the value's name.
Function * getFunction() const
Returns the function that this call graph node represents.
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...
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
AnalysisUsage & addRequired()
bool runOnSCC(CallGraphSCC &SCC) override
Main run interface method, this implements the interface required by the Pass class.
int getCost() const
Get the inline cost estimate.
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...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class is a functor to be used in legacy module or SCC passes for computing AA results for a func...
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM, LazyCallGraph &CG, CGSCCUpdateResult &UR)
void filterDeadComdatFunctions(Module &M, SmallVectorImpl< Function * > &DeadComdatFunctions)
Filter out potentially dead comdat functions where other entries keep the entire comdat group alive...
LLVM_NODISCARD bool empty() const
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.
int getCostDelta() const
Get the cost delta from the threshold for inlining.
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
A node in the call graph.
A class used to represent edges in the call graph.
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...
LLVMContext & getContext() const
All values hold a context through their type.
void getAAResultsAnalysisUsage(AnalysisUsage &AU)
A helper for the legacy pass manager to populate AU to add uses to make sure the analyses required by...
A function analysis which provides an AssumptionCache.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
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.
InlineCost getInlineCost(CallSite CS, const InlineParams &Params, TargetTransformInfo &CalleeTTI, std::function< AssumptionCache &(Function &)> &GetAssumptionCache, Optional< function_ref< BlockFrequencyInfo &(Function &)>> GetBFI, ProfileSummaryInfo *PSI)
Get an InlineCost object representing the cost of inlining this callsite.
Analysis pass which computes BlockFrequencyInfo.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
ImportedFunctionsInliningStatistics ImportedFunctionsStats
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
InstrTy * getInstruction() const
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.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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.
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...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
SmallVector< AllocaInst *, 4 > StaticAllocas
StaticAllocas - InlineFunction fills this in with all static allocas that get copied into the caller...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
The basic data container for the call graph of a Module of IR.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
LegacyInlinerBase(char &ID)
void clear(IRUnitT &IR)
Clear any cached analysis results for a single unit of IR.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
SmallVector< WeakTrackingVH, 8 > InlinedCalls
InlinedCalls - InlineFunction fills this in with callsites that were inlined from the callee...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasLinkOnceODRLinkage() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
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.
static bool shouldInline(CallSite CS, function_ref< InlineCost(CallSite CS)> GetInlineCost, OptimizationRemarkEmitter &ORE)
Return true if the inliner should attempt to inline at the given CallSite.
bool hasLocalLinkage() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
bool skipSCC(CallGraphSCC &SCC) const
Optional passes call this function to check whether the pass should be skipped.
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
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...
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LazyCallGraph::SCC & updateCGAndAnalysisManagerForFunctionPass(LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging=false)
Helper to update the call graph after running a function pass.
CallGraphNode * getExternalCallingNode() const
Returns the CallGraphNode which is used to represent undetermined calls into the callgraph.
This represents the llvm.dbg.declare instruction.
const BasicBlock * getParent() const
DenseMap< ArrayType *, std::vector< AllocaInst * > > InlinedArrayAllocasTy
an instruction to allocate memory on the stack