xref: /llvm-project/bolt/lib/Passes/ReorderFunctions.cpp (revision b402487b7445a799c3ed03109d291198fd529d3a)
1 //===- bolt/Passes/ReorderFunctions.cpp - Function reordering pass --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements ReorderFunctions class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Passes/ReorderFunctions.h"
14 #include "bolt/Passes/HFSort.h"
15 #include "bolt/Utils/Utils.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Transforms/Utils/CodeLayout.h"
19 #include <fstream>
20 
21 #define DEBUG_TYPE "hfsort"
22 
23 using namespace llvm;
24 
25 namespace opts {
26 
27 extern cl::OptionCategory BoltOptCategory;
28 extern cl::opt<unsigned> Verbosity;
29 extern cl::opt<uint32_t> RandomSeed;
30 
31 extern size_t padFunction(const bolt::BinaryFunction &Function);
32 
33 cl::opt<bolt::ReorderFunctions::ReorderType> ReorderFunctions(
34     "reorder-functions",
35     cl::desc("reorder and cluster functions (works only with relocations)"),
36     cl::init(bolt::ReorderFunctions::RT_NONE),
37     cl::values(clEnumValN(bolt::ReorderFunctions::RT_NONE, "none",
38                           "do not reorder functions"),
39                clEnumValN(bolt::ReorderFunctions::RT_EXEC_COUNT, "exec-count",
40                           "order by execution count"),
41                clEnumValN(bolt::ReorderFunctions::RT_HFSORT, "hfsort",
42                           "use hfsort algorithm"),
43                clEnumValN(bolt::ReorderFunctions::RT_HFSORT_PLUS, "hfsort+",
44                           "use hfsort+ algorithm"),
45                clEnumValN(bolt::ReorderFunctions::RT_CDS, "cds",
46                           "use cache-directed sort"),
47                clEnumValN(bolt::ReorderFunctions::RT_PETTIS_HANSEN,
48                           "pettis-hansen", "use Pettis-Hansen algorithm"),
49                clEnumValN(bolt::ReorderFunctions::RT_RANDOM, "random",
50                           "reorder functions randomly"),
51                clEnumValN(bolt::ReorderFunctions::RT_USER, "user",
52                           "use function order specified by -function-order")),
53     cl::ZeroOrMore, cl::cat(BoltOptCategory));
54 
55 static cl::opt<bool> ReorderFunctionsUseHotSize(
56     "reorder-functions-use-hot-size",
57     cl::desc("use a function's hot size when doing clustering"), cl::init(true),
58     cl::cat(BoltOptCategory));
59 
60 static cl::opt<std::string> FunctionOrderFile(
61     "function-order",
62     cl::desc("file containing an ordered list of functions to use for function "
63              "reordering"),
64     cl::cat(BoltOptCategory));
65 
66 static cl::opt<std::string> GenerateFunctionOrderFile(
67     "generate-function-order",
68     cl::desc("file to dump the ordered list of functions to use for function "
69              "reordering"),
70     cl::cat(BoltOptCategory));
71 
72 static cl::opt<std::string> LinkSectionsFile(
73     "generate-link-sections",
74     cl::desc("generate a list of function sections in a format suitable for "
75              "inclusion in a linker script"),
76     cl::cat(BoltOptCategory));
77 
78 static cl::opt<bool>
79     UseEdgeCounts("use-edge-counts",
80                   cl::desc("use edge count data when doing clustering"),
81                   cl::init(true), cl::cat(BoltOptCategory));
82 
83 static cl::opt<bool> CgFromPerfData(
84     "cg-from-perf-data",
85     cl::desc("use perf data directly when constructing the call graph"
86              " for stale functions"),
87     cl::init(true), cl::ZeroOrMore, cl::cat(BoltOptCategory));
88 
89 static cl::opt<bool> CgIgnoreRecursiveCalls(
90     "cg-ignore-recursive-calls",
91     cl::desc("ignore recursive calls when constructing the call graph"),
92     cl::init(true), cl::cat(BoltOptCategory));
93 
94 static cl::opt<bool> CgUseSplitHotSize(
95     "cg-use-split-hot-size",
96     cl::desc("use hot/cold data on basic blocks to determine hot sizes for "
97              "call graph functions"),
98     cl::init(false), cl::ZeroOrMore, cl::cat(BoltOptCategory));
99 
100 } // namespace opts
101 
102 namespace llvm {
103 namespace bolt {
104 
105 using NodeId = CallGraph::NodeId;
106 using Arc = CallGraph::Arc;
107 using Node = CallGraph::Node;
108 
109 void ReorderFunctions::reorder(std::vector<Cluster> &&Clusters,
110                                std::map<uint64_t, BinaryFunction> &BFs) {
111   std::vector<uint64_t> FuncAddr(Cg.numNodes()); // Just for computing stats
112   uint64_t TotalSize = 0;
113   uint32_t Index = 0;
114 
115   // Set order of hot functions based on clusters.
116   for (const Cluster &Cluster : Clusters) {
117     for (const NodeId FuncId : Cluster.targets()) {
118       Cg.nodeIdToFunc(FuncId)->setIndex(Index++);
119       FuncAddr[FuncId] = TotalSize;
120       TotalSize += Cg.size(FuncId);
121     }
122   }
123 
124   // Assign valid index for functions with valid profile.
125   for (auto &It : BFs) {
126     BinaryFunction &BF = It.second;
127     if (!BF.hasValidIndex() && BF.hasValidProfile())
128       BF.setIndex(Index++);
129   }
130 
131   if (opts::ReorderFunctions == RT_NONE)
132     return;
133 
134   printStats(Clusters, FuncAddr);
135 }
136 
137 void ReorderFunctions::printStats(const std::vector<Cluster> &Clusters,
138                                   const std::vector<uint64_t> &FuncAddr) {
139   if (opts::Verbosity == 0) {
140 #ifndef NDEBUG
141     if (!DebugFlag || !isCurrentDebugType("hfsort"))
142       return;
143 #else
144     return;
145 #endif
146   }
147 
148   bool PrintDetailed = opts::Verbosity > 1;
149 #ifndef NDEBUG
150   PrintDetailed |=
151       (DebugFlag && isCurrentDebugType("hfsort") && opts::Verbosity > 0);
152 #endif
153   uint64_t TotalSize = 0;
154   uint64_t CurPage = 0;
155   uint64_t Hotfuncs = 0;
156   double TotalDistance = 0;
157   double TotalCalls = 0;
158   double TotalCalls64B = 0;
159   double TotalCalls4KB = 0;
160   double TotalCalls2MB = 0;
161   if (PrintDetailed)
162     outs() << "BOLT-INFO: Function reordering page layout\n"
163            << "BOLT-INFO: ============== page 0 ==============\n";
164   for (const Cluster &Cluster : Clusters) {
165     if (PrintDetailed)
166       outs() << format(
167           "BOLT-INFO: -------- density = %.3lf (%u / %u) --------\n",
168           Cluster.density(), Cluster.samples(), Cluster.size());
169 
170     for (NodeId FuncId : Cluster.targets()) {
171       if (Cg.samples(FuncId) > 0) {
172         Hotfuncs++;
173 
174         if (PrintDetailed)
175           outs() << "BOLT-INFO: hot func " << *Cg.nodeIdToFunc(FuncId) << " ("
176                  << Cg.size(FuncId) << ")\n";
177 
178         uint64_t Dist = 0;
179         uint64_t Calls = 0;
180         for (NodeId Dst : Cg.successors(FuncId)) {
181           if (FuncId == Dst) // ignore recursive calls in stats
182             continue;
183           const Arc &Arc = *Cg.findArc(FuncId, Dst);
184           const auto D = std::abs(FuncAddr[Arc.dst()] -
185                                   (FuncAddr[FuncId] + Arc.avgCallOffset()));
186           const double W = Arc.weight();
187           if (D < 64 && PrintDetailed && opts::Verbosity > 2)
188             outs() << "BOLT-INFO: short (" << D << "B) call:\n"
189                    << "BOLT-INFO:   Src: " << *Cg.nodeIdToFunc(FuncId) << "\n"
190                    << "BOLT-INFO:   Dst: " << *Cg.nodeIdToFunc(Dst) << "\n"
191                    << "BOLT-INFO:   Weight = " << W << "\n"
192                    << "BOLT-INFO:   AvgOffset = " << Arc.avgCallOffset()
193                    << "\n";
194           Calls += W;
195           if (D < 64)
196             TotalCalls64B += W;
197           if (D < 4096)
198             TotalCalls4KB += W;
199           if (D < (2 << 20))
200             TotalCalls2MB += W;
201           Dist += Arc.weight() * D;
202           if (PrintDetailed)
203             outs() << format("BOLT-INFO: arc: %u [@%lu+%.1lf] -> %u [@%lu]: "
204                              "weight = %.0lf, callDist = %f\n",
205                              Arc.src(), FuncAddr[Arc.src()],
206                              Arc.avgCallOffset(), Arc.dst(),
207                              FuncAddr[Arc.dst()], Arc.weight(), D);
208         }
209         TotalCalls += Calls;
210         TotalDistance += Dist;
211         TotalSize += Cg.size(FuncId);
212 
213         if (PrintDetailed) {
214           outs() << format("BOLT-INFO: start = %6u : avgCallDist = %lu : ",
215                            TotalSize, Calls ? Dist / Calls : 0)
216                  << Cg.nodeIdToFunc(FuncId)->getPrintName() << '\n';
217           const uint64_t NewPage = TotalSize / HugePageSize;
218           if (NewPage != CurPage) {
219             CurPage = NewPage;
220             outs() << format(
221                 "BOLT-INFO: ============== page %u ==============\n", CurPage);
222           }
223         }
224       }
225     }
226   }
227   outs() << "BOLT-INFO: Function reordering stats\n"
228          << format("BOLT-INFO:  Number of hot functions: %u\n"
229                    "BOLT-INFO:  Number of clusters: %lu\n",
230                    Hotfuncs, Clusters.size())
231          << format("BOLT-INFO:  Final average call distance = %.1lf "
232                    "(%.0lf / %.0lf)\n",
233                    TotalCalls ? TotalDistance / TotalCalls : 0, TotalDistance,
234                    TotalCalls)
235          << format("BOLT-INFO:  Total Calls = %.0lf\n", TotalCalls);
236   if (TotalCalls)
237     outs() << format("BOLT-INFO:  Total Calls within 64B = %.0lf (%.2lf%%)\n",
238                      TotalCalls64B, 100 * TotalCalls64B / TotalCalls)
239            << format("BOLT-INFO:  Total Calls within 4KB = %.0lf (%.2lf%%)\n",
240                      TotalCalls4KB, 100 * TotalCalls4KB / TotalCalls)
241            << format("BOLT-INFO:  Total Calls within 2MB = %.0lf (%.2lf%%)\n",
242                      TotalCalls2MB, 100 * TotalCalls2MB / TotalCalls);
243 }
244 
245 std::vector<std::string> ReorderFunctions::readFunctionOrderFile() {
246   std::vector<std::string> FunctionNames;
247   std::ifstream FuncsFile(opts::FunctionOrderFile, std::ios::in);
248   if (!FuncsFile) {
249     errs() << "Ordered functions file \"" << opts::FunctionOrderFile
250            << "\" can't be opened.\n";
251     exit(1);
252   }
253   std::string FuncName;
254   while (std::getline(FuncsFile, FuncName))
255     FunctionNames.push_back(FuncName);
256   return FunctionNames;
257 }
258 
259 void ReorderFunctions::runOnFunctions(BinaryContext &BC) {
260   auto &BFs = BC.getBinaryFunctions();
261   if (opts::ReorderFunctions != RT_NONE &&
262       opts::ReorderFunctions != RT_EXEC_COUNT &&
263       opts::ReorderFunctions != RT_USER) {
264     Cg = buildCallGraph(
265         BC,
266         [](const BinaryFunction &BF) {
267           if (!BF.hasProfile())
268             return true;
269           if (BF.getState() != BinaryFunction::State::CFG)
270             return true;
271           return false;
272         },
273         opts::CgFromPerfData,
274         /*IncludeSplitCalls=*/false, opts::ReorderFunctionsUseHotSize,
275         opts::CgUseSplitHotSize, opts::UseEdgeCounts,
276         opts::CgIgnoreRecursiveCalls);
277     Cg.normalizeArcWeights();
278   }
279 
280   std::vector<Cluster> Clusters;
281 
282   switch (opts::ReorderFunctions) {
283   case RT_NONE:
284     break;
285   case RT_EXEC_COUNT: {
286     std::vector<BinaryFunction *> SortedFunctions(BFs.size());
287     uint32_t Index = 0;
288     llvm::transform(llvm::make_second_range(BFs), SortedFunctions.begin(),
289                     [](BinaryFunction &BF) { return &BF; });
290     llvm::stable_sort(SortedFunctions, [&](const BinaryFunction *A,
291                                            const BinaryFunction *B) {
292       if (A->isIgnored())
293         return false;
294       const size_t PadA = opts::padFunction(*A);
295       const size_t PadB = opts::padFunction(*B);
296       if (!PadA || !PadB) {
297         if (PadA)
298           return true;
299         if (PadB)
300           return false;
301       }
302       return !A->hasProfile() && (B->hasProfile() || (A->getExecutionCount() >
303                                                       B->getExecutionCount()));
304     });
305     for (BinaryFunction *BF : SortedFunctions)
306       if (BF->hasProfile())
307         BF->setIndex(Index++);
308   } break;
309   case RT_HFSORT:
310     Clusters = clusterize(Cg);
311     break;
312   case RT_HFSORT_PLUS:
313     Clusters = hfsortPlus(Cg);
314     break;
315   case RT_CDS: {
316     // It is required that the sum of incoming arc weights is not greater
317     // than the number of samples for every function. Ensuring the call graph
318     // obeys the property before running the algorithm.
319     Cg.adjustArcWeights();
320 
321     // Initialize CFG nodes and their data
322     std::vector<uint64_t> FuncSizes;
323     std::vector<uint64_t> FuncCounts;
324     using JumpT = std::pair<uint64_t, uint64_t>;
325     std::vector<std::pair<JumpT, uint64_t>> CallCounts;
326     std::vector<uint64_t> CallOffsets;
327     for (NodeId F = 0; F < Cg.numNodes(); ++F) {
328       FuncSizes.push_back(Cg.size(F));
329       FuncCounts.push_back(Cg.samples(F));
330       for (NodeId Succ : Cg.successors(F)) {
331         const Arc &Arc = *Cg.findArc(F, Succ);
332         auto It = std::make_pair(F, Succ);
333         CallCounts.push_back(std::make_pair(It, Arc.weight()));
334         CallOffsets.push_back(uint64_t(Arc.avgCallOffset()));
335       }
336     }
337 
338     // Run the layout algorithm.
339     std::vector<uint64_t> Result =
340         applyCDSLayout(FuncSizes, FuncCounts, CallCounts, CallOffsets);
341 
342     // Create a single cluster from the computed order of hot functions.
343     Clusters.emplace_back(Cluster(Result, Cg));
344   } break;
345   case RT_PETTIS_HANSEN:
346     Clusters = pettisAndHansen(Cg);
347     break;
348   case RT_RANDOM:
349     std::srand(opts::RandomSeed);
350     Clusters = randomClusters(Cg);
351     break;
352   case RT_USER: {
353     // Build LTOCommonNameMap
354     StringMap<std::vector<uint64_t>> LTOCommonNameMap;
355     for (const BinaryFunction &BF : llvm::make_second_range(BFs))
356       for (StringRef Name : BF.getNames())
357         if (std::optional<StringRef> LTOCommonName = getLTOCommonName(Name))
358           LTOCommonNameMap[*LTOCommonName].push_back(BF.getAddress());
359 
360     uint32_t Index = 0;
361     uint32_t InvalidEntries = 0;
362     for (const std::string &Function : readFunctionOrderFile()) {
363       std::vector<uint64_t> FuncAddrs;
364 
365       BinaryData *BD = BC.getBinaryDataByName(Function);
366       if (!BD) {
367         // If we can't find the main symbol name, look for alternates.
368         uint32_t LocalID = 1;
369         while (true) {
370           const std::string FuncName = Function + "/" + std::to_string(LocalID);
371           BD = BC.getBinaryDataByName(FuncName);
372           if (BD)
373             FuncAddrs.push_back(BD->getAddress());
374           else
375             break;
376           LocalID++;
377         }
378         // Strip LTO suffixes
379         if (std::optional<StringRef> CommonName = getLTOCommonName(Function))
380           if (LTOCommonNameMap.contains(*CommonName))
381             llvm::append_range(FuncAddrs, LTOCommonNameMap[*CommonName]);
382       } else {
383         FuncAddrs.push_back(BD->getAddress());
384       }
385 
386       if (FuncAddrs.empty()) {
387         if (opts::Verbosity >= 1)
388           errs() << "BOLT-WARNING: Reorder functions: can't find function "
389                  << "for " << Function << "\n";
390         ++InvalidEntries;
391         continue;
392       }
393 
394       for (const uint64_t FuncAddr : FuncAddrs) {
395         const BinaryData *FuncBD = BC.getBinaryDataAtAddress(FuncAddr);
396         assert(FuncBD);
397 
398         BinaryFunction *BF = BC.getFunctionForSymbol(FuncBD->getSymbol());
399         if (!BF) {
400           if (opts::Verbosity >= 1)
401             errs() << "BOLT-WARNING: Reorder functions: can't find function "
402                    << "for " << Function << "\n";
403           ++InvalidEntries;
404           break;
405         }
406         if (!BF->hasValidIndex())
407           BF->setIndex(Index++);
408         else if (opts::Verbosity > 0)
409           errs() << "BOLT-WARNING: Duplicate reorder entry for " << Function
410                  << "\n";
411       }
412     }
413     if (InvalidEntries)
414       errs() << "BOLT-WARNING: Reorder functions: can't find functions for "
415              << InvalidEntries << " entries in -function-order list\n";
416   } break;
417   }
418 
419   reorder(std::move(Clusters), BFs);
420 
421   std::unique_ptr<std::ofstream> FuncsFile;
422   if (!opts::GenerateFunctionOrderFile.empty()) {
423     FuncsFile = std::make_unique<std::ofstream>(opts::GenerateFunctionOrderFile,
424                                                 std::ios::out);
425     if (!FuncsFile) {
426       errs() << "BOLT-ERROR: ordered functions file "
427              << opts::GenerateFunctionOrderFile << " cannot be opened\n";
428       exit(1);
429     }
430   }
431 
432   std::unique_ptr<std::ofstream> LinkSectionsFile;
433   if (!opts::LinkSectionsFile.empty()) {
434     LinkSectionsFile =
435         std::make_unique<std::ofstream>(opts::LinkSectionsFile, std::ios::out);
436     if (!LinkSectionsFile) {
437       errs() << "BOLT-ERROR: link sections file " << opts::LinkSectionsFile
438              << " cannot be opened\n";
439       exit(1);
440     }
441   }
442 
443   if (FuncsFile || LinkSectionsFile) {
444     std::vector<BinaryFunction *> SortedFunctions(BFs.size());
445     llvm::transform(llvm::make_second_range(BFs), SortedFunctions.begin(),
446                     [](BinaryFunction &BF) { return &BF; });
447 
448     // Sort functions by index.
449     llvm::stable_sort(SortedFunctions,
450                       [](const BinaryFunction *A, const BinaryFunction *B) {
451                         if (A->hasValidIndex() && B->hasValidIndex())
452                           return A->getIndex() < B->getIndex();
453                         if (A->hasValidIndex() && !B->hasValidIndex())
454                           return true;
455                         if (!A->hasValidIndex() && B->hasValidIndex())
456                           return false;
457                         return A->getAddress() < B->getAddress();
458                       });
459 
460     for (const BinaryFunction *Func : SortedFunctions) {
461       if (!Func->hasValidIndex())
462         break;
463       if (Func->isPLTFunction())
464         continue;
465 
466       if (FuncsFile)
467         *FuncsFile << Func->getOneName().str() << '\n';
468 
469       if (LinkSectionsFile) {
470         const char *Indent = "";
471         std::vector<StringRef> AllNames = Func->getNames();
472         llvm::sort(AllNames);
473         for (StringRef Name : AllNames) {
474           const size_t SlashPos = Name.find('/');
475           if (SlashPos != std::string::npos) {
476             // Avoid duplicates for local functions.
477             if (Name.find('/', SlashPos + 1) != std::string::npos)
478               continue;
479             Name = Name.substr(0, SlashPos);
480           }
481           *LinkSectionsFile << Indent << ".text." << Name.str() << '\n';
482           Indent = " ";
483         }
484       }
485     }
486 
487     if (FuncsFile) {
488       FuncsFile->close();
489       outs() << "BOLT-INFO: dumped function order to "
490              << opts::GenerateFunctionOrderFile << '\n';
491     }
492 
493     if (LinkSectionsFile) {
494       LinkSectionsFile->close();
495       outs() << "BOLT-INFO: dumped linker section order to "
496              << opts::LinkSectionsFile << '\n';
497     }
498   }
499 }
500 
501 } // namespace bolt
502 } // namespace llvm
503