1af732203SDimitry Andric //===-- ImportedFunctionsInliningStats.cpp ----------------------*- C++ -*-===//
2af732203SDimitry Andric //
3af732203SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4af732203SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5af732203SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6af732203SDimitry Andric //
7af732203SDimitry Andric //===----------------------------------------------------------------------===//
8af732203SDimitry Andric // Generating inliner statistics for imported functions, mostly useful for
9af732203SDimitry Andric // ThinLTO.
10af732203SDimitry Andric //===----------------------------------------------------------------------===//
11af732203SDimitry Andric 
12af732203SDimitry Andric #include "llvm/Analysis/Utils/ImportedFunctionsInliningStatistics.h"
13af732203SDimitry Andric #include "llvm/ADT/STLExtras.h"
14af732203SDimitry Andric #include "llvm/IR/Function.h"
15af732203SDimitry Andric #include "llvm/IR/Module.h"
16af732203SDimitry Andric #include "llvm/Support/CommandLine.h"
17af732203SDimitry Andric #include "llvm/Support/Debug.h"
18af732203SDimitry Andric #include "llvm/Support/raw_ostream.h"
19af732203SDimitry Andric #include <algorithm>
20af732203SDimitry Andric #include <iomanip>
21af732203SDimitry Andric #include <sstream>
22*5f7ddb14SDimitry Andric #include <string>
23*5f7ddb14SDimitry Andric 
24af732203SDimitry Andric using namespace llvm;
25af732203SDimitry Andric 
26af732203SDimitry Andric cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats(
27af732203SDimitry Andric     "inliner-function-import-stats",
28af732203SDimitry Andric     cl::init(InlinerFunctionImportStatsOpts::No),
29af732203SDimitry Andric     cl::values(clEnumValN(InlinerFunctionImportStatsOpts::Basic, "basic",
30af732203SDimitry Andric                           "basic statistics"),
31af732203SDimitry Andric                clEnumValN(InlinerFunctionImportStatsOpts::Verbose, "verbose",
32af732203SDimitry Andric                           "printing of statistics for each inlined function")),
33af732203SDimitry Andric     cl::Hidden, cl::desc("Enable inliner stats for imported functions"));
34af732203SDimitry Andric 
35af732203SDimitry Andric ImportedFunctionsInliningStatistics::InlineGraphNode &
createInlineGraphNode(const Function & F)36af732203SDimitry Andric ImportedFunctionsInliningStatistics::createInlineGraphNode(const Function &F) {
37af732203SDimitry Andric 
38af732203SDimitry Andric   auto &ValueLookup = NodesMap[F.getName()];
39af732203SDimitry Andric   if (!ValueLookup) {
40af732203SDimitry Andric     ValueLookup = std::make_unique<InlineGraphNode>();
41af732203SDimitry Andric     ValueLookup->Imported = F.hasMetadata("thinlto_src_module");
42af732203SDimitry Andric   }
43af732203SDimitry Andric   return *ValueLookup;
44af732203SDimitry Andric }
45af732203SDimitry Andric 
recordInline(const Function & Caller,const Function & Callee)46af732203SDimitry Andric void ImportedFunctionsInliningStatistics::recordInline(const Function &Caller,
47af732203SDimitry Andric                                                        const Function &Callee) {
48af732203SDimitry Andric 
49af732203SDimitry Andric   InlineGraphNode &CallerNode = createInlineGraphNode(Caller);
50af732203SDimitry Andric   InlineGraphNode &CalleeNode = createInlineGraphNode(Callee);
51af732203SDimitry Andric   CalleeNode.NumberOfInlines++;
52af732203SDimitry Andric 
53af732203SDimitry Andric   if (!CallerNode.Imported && !CalleeNode.Imported) {
54af732203SDimitry Andric     // Direct inline from not imported callee to not imported caller, so we
55af732203SDimitry Andric     // don't have to add this to graph. It might be very helpful if you wanna
56af732203SDimitry Andric     // get the inliner statistics in compile step where there are no imported
57af732203SDimitry Andric     // functions. In this case the graph would be empty.
58af732203SDimitry Andric     CalleeNode.NumberOfRealInlines++;
59af732203SDimitry Andric     return;
60af732203SDimitry Andric   }
61af732203SDimitry Andric 
62af732203SDimitry Andric   CallerNode.InlinedCallees.push_back(&CalleeNode);
63af732203SDimitry Andric   if (!CallerNode.Imported) {
64af732203SDimitry Andric     // We could avoid second lookup, but it would make the code ultra ugly.
65af732203SDimitry Andric     auto It = NodesMap.find(Caller.getName());
66af732203SDimitry Andric     assert(It != NodesMap.end() && "The node should be already there.");
67af732203SDimitry Andric     // Save Caller as a starting node for traversal. The string has to be one
68af732203SDimitry Andric     // from map because Caller can disappear (and function name with it).
69af732203SDimitry Andric     NonImportedCallers.push_back(It->first());
70af732203SDimitry Andric   }
71af732203SDimitry Andric }
72af732203SDimitry Andric 
setModuleInfo(const Module & M)73af732203SDimitry Andric void ImportedFunctionsInliningStatistics::setModuleInfo(const Module &M) {
74af732203SDimitry Andric   ModuleName = M.getName();
75af732203SDimitry Andric   for (const auto &F : M.functions()) {
76af732203SDimitry Andric     if (F.isDeclaration())
77af732203SDimitry Andric       continue;
78af732203SDimitry Andric     AllFunctions++;
79af732203SDimitry Andric     ImportedFunctions += int(F.hasMetadata("thinlto_src_module"));
80af732203SDimitry Andric   }
81af732203SDimitry Andric }
getStatString(const char * Msg,int32_t Fraction,int32_t All,const char * PercentageOfMsg,bool LineEnd=true)82af732203SDimitry Andric static std::string getStatString(const char *Msg, int32_t Fraction, int32_t All,
83af732203SDimitry Andric                                  const char *PercentageOfMsg,
84af732203SDimitry Andric                                  bool LineEnd = true) {
85af732203SDimitry Andric   double Result = 0;
86af732203SDimitry Andric   if (All != 0)
87af732203SDimitry Andric     Result = 100 * static_cast<double>(Fraction) / All;
88af732203SDimitry Andric 
89af732203SDimitry Andric   std::stringstream Str;
90af732203SDimitry Andric   Str << std::setprecision(4) << Msg << ": " << Fraction << " [" << Result
91af732203SDimitry Andric       << "% of " << PercentageOfMsg << "]";
92af732203SDimitry Andric   if (LineEnd)
93af732203SDimitry Andric     Str << "\n";
94af732203SDimitry Andric   return Str.str();
95af732203SDimitry Andric }
96af732203SDimitry Andric 
dump(const bool Verbose)97af732203SDimitry Andric void ImportedFunctionsInliningStatistics::dump(const bool Verbose) {
98af732203SDimitry Andric   calculateRealInlines();
99af732203SDimitry Andric   NonImportedCallers.clear();
100af732203SDimitry Andric 
101af732203SDimitry Andric   int32_t InlinedImportedFunctionsCount = 0;
102af732203SDimitry Andric   int32_t InlinedNotImportedFunctionsCount = 0;
103af732203SDimitry Andric 
104af732203SDimitry Andric   int32_t InlinedImportedFunctionsToImportingModuleCount = 0;
105af732203SDimitry Andric   int32_t InlinedNotImportedFunctionsToImportingModuleCount = 0;
106af732203SDimitry Andric 
107af732203SDimitry Andric   const auto SortedNodes = getSortedNodes();
108af732203SDimitry Andric   std::string Out;
109af732203SDimitry Andric   Out.reserve(5000);
110af732203SDimitry Andric   raw_string_ostream Ostream(Out);
111af732203SDimitry Andric 
112af732203SDimitry Andric   Ostream << "------- Dumping inliner stats for [" << ModuleName
113af732203SDimitry Andric           << "] -------\n";
114af732203SDimitry Andric 
115af732203SDimitry Andric   if (Verbose)
116af732203SDimitry Andric     Ostream << "-- List of inlined functions:\n";
117af732203SDimitry Andric 
118af732203SDimitry Andric   for (const auto &Node : SortedNodes) {
119af732203SDimitry Andric     assert(Node->second->NumberOfInlines >= Node->second->NumberOfRealInlines);
120af732203SDimitry Andric     if (Node->second->NumberOfInlines == 0)
121af732203SDimitry Andric       continue;
122af732203SDimitry Andric 
123af732203SDimitry Andric     if (Node->second->Imported) {
124af732203SDimitry Andric       InlinedImportedFunctionsCount++;
125af732203SDimitry Andric       InlinedImportedFunctionsToImportingModuleCount +=
126af732203SDimitry Andric           int(Node->second->NumberOfRealInlines > 0);
127af732203SDimitry Andric     } else {
128af732203SDimitry Andric       InlinedNotImportedFunctionsCount++;
129af732203SDimitry Andric       InlinedNotImportedFunctionsToImportingModuleCount +=
130af732203SDimitry Andric           int(Node->second->NumberOfRealInlines > 0);
131af732203SDimitry Andric     }
132af732203SDimitry Andric 
133af732203SDimitry Andric     if (Verbose)
134af732203SDimitry Andric       Ostream << "Inlined "
135af732203SDimitry Andric               << (Node->second->Imported ? "imported " : "not imported ")
136af732203SDimitry Andric               << "function [" << Node->first() << "]"
137af732203SDimitry Andric               << ": #inlines = " << Node->second->NumberOfInlines
138af732203SDimitry Andric               << ", #inlines_to_importing_module = "
139af732203SDimitry Andric               << Node->second->NumberOfRealInlines << "\n";
140af732203SDimitry Andric   }
141af732203SDimitry Andric 
142af732203SDimitry Andric   auto InlinedFunctionsCount =
143af732203SDimitry Andric       InlinedImportedFunctionsCount + InlinedNotImportedFunctionsCount;
144af732203SDimitry Andric   auto NotImportedFuncCount = AllFunctions - ImportedFunctions;
145af732203SDimitry Andric   auto ImportedNotInlinedIntoModule =
146af732203SDimitry Andric       ImportedFunctions - InlinedImportedFunctionsToImportingModuleCount;
147af732203SDimitry Andric 
148af732203SDimitry Andric   Ostream << "-- Summary:\n"
149af732203SDimitry Andric           << "All functions: " << AllFunctions
150af732203SDimitry Andric           << ", imported functions: " << ImportedFunctions << "\n"
151af732203SDimitry Andric           << getStatString("inlined functions", InlinedFunctionsCount,
152af732203SDimitry Andric                            AllFunctions, "all functions")
153af732203SDimitry Andric           << getStatString("imported functions inlined anywhere",
154af732203SDimitry Andric                            InlinedImportedFunctionsCount, ImportedFunctions,
155af732203SDimitry Andric                            "imported functions")
156af732203SDimitry Andric           << getStatString("imported functions inlined into importing module",
157af732203SDimitry Andric                            InlinedImportedFunctionsToImportingModuleCount,
158af732203SDimitry Andric                            ImportedFunctions, "imported functions",
159af732203SDimitry Andric                            /*LineEnd=*/false)
160af732203SDimitry Andric           << getStatString(", remaining", ImportedNotInlinedIntoModule,
161af732203SDimitry Andric                            ImportedFunctions, "imported functions")
162af732203SDimitry Andric           << getStatString("non-imported functions inlined anywhere",
163af732203SDimitry Andric                            InlinedNotImportedFunctionsCount,
164af732203SDimitry Andric                            NotImportedFuncCount, "non-imported functions")
165af732203SDimitry Andric           << getStatString(
166af732203SDimitry Andric                  "non-imported functions inlined into importing module",
167af732203SDimitry Andric                  InlinedNotImportedFunctionsToImportingModuleCount,
168af732203SDimitry Andric                  NotImportedFuncCount, "non-imported functions");
169af732203SDimitry Andric   Ostream.flush();
170af732203SDimitry Andric   dbgs() << Out;
171af732203SDimitry Andric }
172af732203SDimitry Andric 
calculateRealInlines()173af732203SDimitry Andric void ImportedFunctionsInliningStatistics::calculateRealInlines() {
174af732203SDimitry Andric   // Removing duplicated Callers.
175af732203SDimitry Andric   llvm::sort(NonImportedCallers);
176af732203SDimitry Andric   NonImportedCallers.erase(
177af732203SDimitry Andric       std::unique(NonImportedCallers.begin(), NonImportedCallers.end()),
178af732203SDimitry Andric       NonImportedCallers.end());
179af732203SDimitry Andric 
180af732203SDimitry Andric   for (const auto &Name : NonImportedCallers) {
181af732203SDimitry Andric     auto &Node = *NodesMap[Name];
182af732203SDimitry Andric     if (!Node.Visited)
183af732203SDimitry Andric       dfs(Node);
184af732203SDimitry Andric   }
185af732203SDimitry Andric }
186af732203SDimitry Andric 
dfs(InlineGraphNode & GraphNode)187af732203SDimitry Andric void ImportedFunctionsInliningStatistics::dfs(InlineGraphNode &GraphNode) {
188af732203SDimitry Andric   assert(!GraphNode.Visited);
189af732203SDimitry Andric   GraphNode.Visited = true;
190af732203SDimitry Andric   for (auto *const InlinedFunctionNode : GraphNode.InlinedCallees) {
191af732203SDimitry Andric     InlinedFunctionNode->NumberOfRealInlines++;
192af732203SDimitry Andric     if (!InlinedFunctionNode->Visited)
193af732203SDimitry Andric       dfs(*InlinedFunctionNode);
194af732203SDimitry Andric   }
195af732203SDimitry Andric }
196af732203SDimitry Andric 
197af732203SDimitry Andric ImportedFunctionsInliningStatistics::SortedNodesTy
getSortedNodes()198af732203SDimitry Andric ImportedFunctionsInliningStatistics::getSortedNodes() {
199af732203SDimitry Andric   SortedNodesTy SortedNodes;
200af732203SDimitry Andric   SortedNodes.reserve(NodesMap.size());
201af732203SDimitry Andric   for (const NodesMapTy::value_type &Node : NodesMap)
202af732203SDimitry Andric     SortedNodes.push_back(&Node);
203af732203SDimitry Andric 
204af732203SDimitry Andric   llvm::sort(SortedNodes, [&](const SortedNodesTy::value_type &Lhs,
205af732203SDimitry Andric                               const SortedNodesTy::value_type &Rhs) {
206af732203SDimitry Andric     if (Lhs->second->NumberOfInlines != Rhs->second->NumberOfInlines)
207af732203SDimitry Andric       return Lhs->second->NumberOfInlines > Rhs->second->NumberOfInlines;
208af732203SDimitry Andric     if (Lhs->second->NumberOfRealInlines != Rhs->second->NumberOfRealInlines)
209af732203SDimitry Andric       return Lhs->second->NumberOfRealInlines >
210af732203SDimitry Andric              Rhs->second->NumberOfRealInlines;
211af732203SDimitry Andric     return Lhs->first() < Rhs->first();
212af732203SDimitry Andric   });
213af732203SDimitry Andric   return SortedNodes;
214af732203SDimitry Andric }
215