xref: /openbsd-src/gnu/llvm/lld/ELF/CallGraphSort.cpp (revision dfe94b169149f14cc1aee2cf6dad58a8d9a1860c)
1ece8a530Spatrick //===- CallGraphSort.cpp --------------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick ///
9ece8a530Spatrick /// Implementation of Call-Chain Clustering from: Optimizing Function Placement
10ece8a530Spatrick /// for Large-Scale Data-Center Applications
11ece8a530Spatrick /// https://research.fb.com/wp-content/uploads/2017/01/cgo2017-hfsort-final1.pdf
12ece8a530Spatrick ///
13ece8a530Spatrick /// The goal of this algorithm is to improve runtime performance of the final
14ece8a530Spatrick /// executable by arranging code sections such that page table and i-cache
15ece8a530Spatrick /// misses are minimized.
16ece8a530Spatrick ///
17ece8a530Spatrick /// Definitions:
18ece8a530Spatrick /// * Cluster
19ece8a530Spatrick ///   * An ordered list of input sections which are laid out as a unit. At the
20ece8a530Spatrick ///     beginning of the algorithm each input section has its own cluster and
21ece8a530Spatrick ///     the weight of the cluster is the sum of the weight of all incoming
22ece8a530Spatrick ///     edges.
23ece8a530Spatrick /// * Call-Chain Clustering (C³) Heuristic
24ece8a530Spatrick ///   * Defines when and how clusters are combined. Pick the highest weighted
25ece8a530Spatrick ///     input section then add it to its most likely predecessor if it wouldn't
26ece8a530Spatrick ///     penalize it too much.
27ece8a530Spatrick /// * Density
28ece8a530Spatrick ///   * The weight of the cluster divided by the size of the cluster. This is a
29ece8a530Spatrick ///     proxy for the amount of execution time spent per byte of the cluster.
30ece8a530Spatrick ///
31ece8a530Spatrick /// It does so given a call graph profile by the following:
32ece8a530Spatrick /// * Build a weighted call graph from the call graph profile
33ece8a530Spatrick /// * Sort input sections by weight
34ece8a530Spatrick /// * For each input section starting with the highest weight
35ece8a530Spatrick ///   * Find its most likely predecessor cluster
36ece8a530Spatrick ///   * Check if the combined cluster would be too large, or would have too low
37ece8a530Spatrick ///     a density.
38ece8a530Spatrick ///   * If not, then combine the clusters.
39ece8a530Spatrick /// * Sort non-empty clusters by density
40ece8a530Spatrick ///
41ece8a530Spatrick //===----------------------------------------------------------------------===//
42ece8a530Spatrick 
43ece8a530Spatrick #include "CallGraphSort.h"
44*dfe94b16Srobert #include "InputFiles.h"
45*dfe94b16Srobert #include "InputSection.h"
46ece8a530Spatrick #include "Symbols.h"
47*dfe94b16Srobert #include "llvm/Support/FileSystem.h"
48ece8a530Spatrick 
49ece8a530Spatrick #include <numeric>
50ece8a530Spatrick 
51ece8a530Spatrick using namespace llvm;
52bb684c34Spatrick using namespace lld;
53bb684c34Spatrick using namespace lld::elf;
54ece8a530Spatrick 
55ece8a530Spatrick namespace {
56ece8a530Spatrick struct Edge {
57ece8a530Spatrick   int from;
58ece8a530Spatrick   uint64_t weight;
59ece8a530Spatrick };
60ece8a530Spatrick 
61ece8a530Spatrick struct Cluster {
Cluster__anon3022afde0111::Cluster62ece8a530Spatrick   Cluster(int sec, size_t s) : next(sec), prev(sec), size(s) {}
63ece8a530Spatrick 
getDensity__anon3022afde0111::Cluster64ece8a530Spatrick   double getDensity() const {
65ece8a530Spatrick     if (size == 0)
66ece8a530Spatrick       return 0;
67ece8a530Spatrick     return double(weight) / double(size);
68ece8a530Spatrick   }
69ece8a530Spatrick 
70ece8a530Spatrick   int next;
71ece8a530Spatrick   int prev;
721cf9926bSpatrick   uint64_t size;
73ece8a530Spatrick   uint64_t weight = 0;
74ece8a530Spatrick   uint64_t initialWeight = 0;
75ece8a530Spatrick   Edge bestPred = {-1, 0};
76ece8a530Spatrick };
77ece8a530Spatrick 
78ece8a530Spatrick class CallGraphSort {
79ece8a530Spatrick public:
80ece8a530Spatrick   CallGraphSort();
81ece8a530Spatrick 
82ece8a530Spatrick   DenseMap<const InputSectionBase *, int> run();
83ece8a530Spatrick 
84ece8a530Spatrick private:
85ece8a530Spatrick   std::vector<Cluster> clusters;
86ece8a530Spatrick   std::vector<const InputSectionBase *> sections;
87ece8a530Spatrick };
88ece8a530Spatrick 
89ece8a530Spatrick // Maximum amount the combined cluster density can be worse than the original
90ece8a530Spatrick // cluster to consider merging.
91ece8a530Spatrick constexpr int MAX_DENSITY_DEGRADATION = 8;
92ece8a530Spatrick 
93ece8a530Spatrick // Maximum cluster size in bytes.
94ece8a530Spatrick constexpr uint64_t MAX_CLUSTER_SIZE = 1024 * 1024;
95ece8a530Spatrick } // end anonymous namespace
96ece8a530Spatrick 
97ece8a530Spatrick using SectionPair =
98ece8a530Spatrick     std::pair<const InputSectionBase *, const InputSectionBase *>;
99ece8a530Spatrick 
100ece8a530Spatrick // Take the edge list in Config->CallGraphProfile, resolve symbol names to
101ece8a530Spatrick // Symbols, and generate a graph between InputSections with the provided
102ece8a530Spatrick // weights.
CallGraphSort()103ece8a530Spatrick CallGraphSort::CallGraphSort() {
104ece8a530Spatrick   MapVector<SectionPair, uint64_t> &profile = config->callGraphProfile;
105ece8a530Spatrick   DenseMap<const InputSectionBase *, int> secToCluster;
106ece8a530Spatrick 
107ece8a530Spatrick   auto getOrCreateNode = [&](const InputSectionBase *isec) -> int {
108ece8a530Spatrick     auto res = secToCluster.try_emplace(isec, clusters.size());
109ece8a530Spatrick     if (res.second) {
110ece8a530Spatrick       sections.push_back(isec);
111ece8a530Spatrick       clusters.emplace_back(clusters.size(), isec->getSize());
112ece8a530Spatrick     }
113ece8a530Spatrick     return res.first->second;
114ece8a530Spatrick   };
115ece8a530Spatrick 
116ece8a530Spatrick   // Create the graph.
117ece8a530Spatrick   for (std::pair<SectionPair, uint64_t> &c : profile) {
118*dfe94b16Srobert     const auto *fromSB = cast<InputSectionBase>(c.first.first);
119*dfe94b16Srobert     const auto *toSB = cast<InputSectionBase>(c.first.second);
120ece8a530Spatrick     uint64_t weight = c.second;
121ece8a530Spatrick 
122ece8a530Spatrick     // Ignore edges between input sections belonging to different output
123ece8a530Spatrick     // sections.  This is done because otherwise we would end up with clusters
124ece8a530Spatrick     // containing input sections that can't actually be placed adjacently in the
125ece8a530Spatrick     // output.  This messes with the cluster size and density calculations.  We
126ece8a530Spatrick     // would also end up moving input sections in other output sections without
127ece8a530Spatrick     // moving them closer to what calls them.
128ece8a530Spatrick     if (fromSB->getOutputSection() != toSB->getOutputSection())
129ece8a530Spatrick       continue;
130ece8a530Spatrick 
131ece8a530Spatrick     int from = getOrCreateNode(fromSB);
132ece8a530Spatrick     int to = getOrCreateNode(toSB);
133ece8a530Spatrick 
134ece8a530Spatrick     clusters[to].weight += weight;
135ece8a530Spatrick 
136ece8a530Spatrick     if (from == to)
137ece8a530Spatrick       continue;
138ece8a530Spatrick 
139ece8a530Spatrick     // Remember the best edge.
140ece8a530Spatrick     Cluster &toC = clusters[to];
141ece8a530Spatrick     if (toC.bestPred.from == -1 || toC.bestPred.weight < weight) {
142ece8a530Spatrick       toC.bestPred.from = from;
143ece8a530Spatrick       toC.bestPred.weight = weight;
144ece8a530Spatrick     }
145ece8a530Spatrick   }
146ece8a530Spatrick   for (Cluster &c : clusters)
147ece8a530Spatrick     c.initialWeight = c.weight;
148ece8a530Spatrick }
149ece8a530Spatrick 
150ece8a530Spatrick // It's bad to merge clusters which would degrade the density too much.
isNewDensityBad(Cluster & a,Cluster & b)151ece8a530Spatrick static bool isNewDensityBad(Cluster &a, Cluster &b) {
152ece8a530Spatrick   double newDensity = double(a.weight + b.weight) / double(a.size + b.size);
153ece8a530Spatrick   return newDensity < a.getDensity() / MAX_DENSITY_DEGRADATION;
154ece8a530Spatrick }
155ece8a530Spatrick 
156ece8a530Spatrick // Find the leader of V's belonged cluster (represented as an equivalence
157ece8a530Spatrick // class). We apply union-find path-halving technique (simple to implement) in
158ece8a530Spatrick // the meantime as it decreases depths and the time complexity.
getLeader(int * leaders,int v)159*dfe94b16Srobert static int getLeader(int *leaders, int v) {
160ece8a530Spatrick   while (leaders[v] != v) {
161ece8a530Spatrick     leaders[v] = leaders[leaders[v]];
162ece8a530Spatrick     v = leaders[v];
163ece8a530Spatrick   }
164ece8a530Spatrick   return v;
165ece8a530Spatrick }
166ece8a530Spatrick 
mergeClusters(std::vector<Cluster> & cs,Cluster & into,int intoIdx,Cluster & from,int fromIdx)167ece8a530Spatrick static void mergeClusters(std::vector<Cluster> &cs, Cluster &into, int intoIdx,
168ece8a530Spatrick                           Cluster &from, int fromIdx) {
169ece8a530Spatrick   int tail1 = into.prev, tail2 = from.prev;
170ece8a530Spatrick   into.prev = tail2;
171ece8a530Spatrick   cs[tail2].next = intoIdx;
172ece8a530Spatrick   from.prev = tail1;
173ece8a530Spatrick   cs[tail1].next = fromIdx;
174ece8a530Spatrick   into.size += from.size;
175ece8a530Spatrick   into.weight += from.weight;
176ece8a530Spatrick   from.size = 0;
177ece8a530Spatrick   from.weight = 0;
178ece8a530Spatrick }
179ece8a530Spatrick 
180ece8a530Spatrick // Group InputSections into clusters using the Call-Chain Clustering heuristic
181ece8a530Spatrick // then sort the clusters by density.
run()182ece8a530Spatrick DenseMap<const InputSectionBase *, int> CallGraphSort::run() {
183ece8a530Spatrick   std::vector<int> sorted(clusters.size());
184*dfe94b16Srobert   std::unique_ptr<int[]> leaders(new int[clusters.size()]);
185ece8a530Spatrick 
186*dfe94b16Srobert   std::iota(leaders.get(), leaders.get() + clusters.size(), 0);
187ece8a530Spatrick   std::iota(sorted.begin(), sorted.end(), 0);
188ece8a530Spatrick   llvm::stable_sort(sorted, [&](int a, int b) {
189ece8a530Spatrick     return clusters[a].getDensity() > clusters[b].getDensity();
190ece8a530Spatrick   });
191ece8a530Spatrick 
192ece8a530Spatrick   for (int l : sorted) {
193ece8a530Spatrick     // The cluster index is the same as the index of its leader here because
194ece8a530Spatrick     // clusters[L] has not been merged into another cluster yet.
195ece8a530Spatrick     Cluster &c = clusters[l];
196ece8a530Spatrick 
197ece8a530Spatrick     // Don't consider merging if the edge is unlikely.
198ece8a530Spatrick     if (c.bestPred.from == -1 || c.bestPred.weight * 10 <= c.initialWeight)
199ece8a530Spatrick       continue;
200ece8a530Spatrick 
201*dfe94b16Srobert     int predL = getLeader(leaders.get(), c.bestPred.from);
202ece8a530Spatrick     if (l == predL)
203ece8a530Spatrick       continue;
204ece8a530Spatrick 
205ece8a530Spatrick     Cluster *predC = &clusters[predL];
206ece8a530Spatrick     if (c.size + predC->size > MAX_CLUSTER_SIZE)
207ece8a530Spatrick       continue;
208ece8a530Spatrick 
209ece8a530Spatrick     if (isNewDensityBad(*predC, c))
210ece8a530Spatrick       continue;
211ece8a530Spatrick 
212ece8a530Spatrick     leaders[l] = predL;
213ece8a530Spatrick     mergeClusters(clusters, *predC, predL, c, l);
214ece8a530Spatrick   }
215ece8a530Spatrick 
216ece8a530Spatrick   // Sort remaining non-empty clusters by density.
217ece8a530Spatrick   sorted.clear();
218ece8a530Spatrick   for (int i = 0, e = (int)clusters.size(); i != e; ++i)
219ece8a530Spatrick     if (clusters[i].size > 0)
220ece8a530Spatrick       sorted.push_back(i);
221ece8a530Spatrick   llvm::stable_sort(sorted, [&](int a, int b) {
222ece8a530Spatrick     return clusters[a].getDensity() > clusters[b].getDensity();
223ece8a530Spatrick   });
224ece8a530Spatrick 
225ece8a530Spatrick   DenseMap<const InputSectionBase *, int> orderMap;
226ece8a530Spatrick   int curOrder = 1;
2271cf9926bSpatrick   for (int leader : sorted) {
228ece8a530Spatrick     for (int i = leader;;) {
229ece8a530Spatrick       orderMap[sections[i]] = curOrder++;
230ece8a530Spatrick       i = clusters[i].next;
231ece8a530Spatrick       if (i == leader)
232ece8a530Spatrick         break;
233ece8a530Spatrick     }
2341cf9926bSpatrick   }
235ece8a530Spatrick   if (!config->printSymbolOrder.empty()) {
236ece8a530Spatrick     std::error_code ec;
237ece8a530Spatrick     raw_fd_ostream os(config->printSymbolOrder, ec, sys::fs::OF_None);
238ece8a530Spatrick     if (ec) {
239ece8a530Spatrick       error("cannot open " + config->printSymbolOrder + ": " + ec.message());
240ece8a530Spatrick       return orderMap;
241ece8a530Spatrick     }
242ece8a530Spatrick 
243ece8a530Spatrick     // Print the symbols ordered by C3, in the order of increasing curOrder
244ece8a530Spatrick     // Instead of sorting all the orderMap, just repeat the loops above.
245ece8a530Spatrick     for (int leader : sorted)
246ece8a530Spatrick       for (int i = leader;;) {
247ece8a530Spatrick         // Search all the symbols in the file of the section
248ece8a530Spatrick         // and find out a Defined symbol with name that is within the section.
249ece8a530Spatrick         for (Symbol *sym : sections[i]->file->getSymbols())
250ece8a530Spatrick           if (!sym->isSection()) // Filter out section-type symbols here.
251ece8a530Spatrick             if (auto *d = dyn_cast<Defined>(sym))
252ece8a530Spatrick               if (sections[i] == d->section)
253ece8a530Spatrick                 os << sym->getName() << "\n";
254ece8a530Spatrick         i = clusters[i].next;
255ece8a530Spatrick         if (i == leader)
256ece8a530Spatrick           break;
257ece8a530Spatrick       }
258ece8a530Spatrick   }
259ece8a530Spatrick 
260ece8a530Spatrick   return orderMap;
261ece8a530Spatrick }
262ece8a530Spatrick 
263*dfe94b16Srobert // Sort sections by the profile data provided by --callgraph-profile-file.
264ece8a530Spatrick //
265ece8a530Spatrick // This first builds a call graph based on the profile data then merges sections
266bb684c34Spatrick // according to the C³ heuristic. All clusters are then sorted by a density
267ece8a530Spatrick // metric to further improve locality.
computeCallGraphProfileOrder()268bb684c34Spatrick DenseMap<const InputSectionBase *, int> elf::computeCallGraphProfileOrder() {
269ece8a530Spatrick   return CallGraphSort().run();
270ece8a530Spatrick }
271