1b60736ecSDimitry Andric //===- CallGraphSort.cpp --------------------------------------------------===//
2b60736ecSDimitry Andric //
3b60736ecSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4b60736ecSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5b60736ecSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b60736ecSDimitry Andric //
7b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
8b60736ecSDimitry Andric ///
9b60736ecSDimitry Andric /// This is based on the ELF port, see ELF/CallGraphSort.cpp for the details
10b60736ecSDimitry Andric /// about the algorithm.
11b60736ecSDimitry Andric ///
12b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
13b60736ecSDimitry Andric
14b60736ecSDimitry Andric #include "CallGraphSort.h"
15c0981da4SDimitry Andric #include "COFFLinkerContext.h"
16b60736ecSDimitry Andric #include "InputFiles.h"
17b60736ecSDimitry Andric #include "SymbolTable.h"
18b60736ecSDimitry Andric #include "Symbols.h"
19b60736ecSDimitry Andric #include "lld/Common/ErrorHandler.h"
20b60736ecSDimitry Andric
21b60736ecSDimitry Andric #include <numeric>
22b60736ecSDimitry Andric
23b60736ecSDimitry Andric using namespace llvm;
24b60736ecSDimitry Andric using namespace lld;
25b60736ecSDimitry Andric using namespace lld::coff;
26b60736ecSDimitry Andric
27b60736ecSDimitry Andric namespace {
28b60736ecSDimitry Andric struct Edge {
29b60736ecSDimitry Andric int from;
30b60736ecSDimitry Andric uint64_t weight;
31b60736ecSDimitry Andric };
32b60736ecSDimitry Andric
33b60736ecSDimitry Andric struct Cluster {
Cluster__anonc063e9230111::Cluster34b60736ecSDimitry Andric Cluster(int sec, size_t s) : next(sec), prev(sec), size(s) {}
35b60736ecSDimitry Andric
getDensity__anonc063e9230111::Cluster36b60736ecSDimitry Andric double getDensity() const {
37b60736ecSDimitry Andric if (size == 0)
38b60736ecSDimitry Andric return 0;
39b60736ecSDimitry Andric return double(weight) / double(size);
40b60736ecSDimitry Andric }
41b60736ecSDimitry Andric
42b60736ecSDimitry Andric int next;
43b60736ecSDimitry Andric int prev;
44b60736ecSDimitry Andric uint64_t size;
45b60736ecSDimitry Andric uint64_t weight = 0;
46b60736ecSDimitry Andric uint64_t initialWeight = 0;
47b60736ecSDimitry Andric Edge bestPred = {-1, 0};
48b60736ecSDimitry Andric };
49b60736ecSDimitry Andric
50b60736ecSDimitry Andric class CallGraphSort {
51b60736ecSDimitry Andric public:
52c0981da4SDimitry Andric CallGraphSort(const COFFLinkerContext &ctx);
53b60736ecSDimitry Andric
54b60736ecSDimitry Andric DenseMap<const SectionChunk *, int> run();
55b60736ecSDimitry Andric
56b60736ecSDimitry Andric private:
57b60736ecSDimitry Andric std::vector<Cluster> clusters;
58b60736ecSDimitry Andric std::vector<const SectionChunk *> sections;
59e3b55780SDimitry Andric
60e3b55780SDimitry Andric const COFFLinkerContext &ctx;
61b60736ecSDimitry Andric };
62b60736ecSDimitry Andric
63b60736ecSDimitry Andric // Maximum amount the combined cluster density can be worse than the original
64b60736ecSDimitry Andric // cluster to consider merging.
65b60736ecSDimitry Andric constexpr int MAX_DENSITY_DEGRADATION = 8;
66b60736ecSDimitry Andric
67b60736ecSDimitry Andric // Maximum cluster size in bytes.
68b60736ecSDimitry Andric constexpr uint64_t MAX_CLUSTER_SIZE = 1024 * 1024;
69b60736ecSDimitry Andric } // end anonymous namespace
70b60736ecSDimitry Andric
71b60736ecSDimitry Andric using SectionPair = std::pair<const SectionChunk *, const SectionChunk *>;
72b60736ecSDimitry Andric
73b60736ecSDimitry Andric // Take the edge list in Config->CallGraphProfile, resolve symbol names to
74b60736ecSDimitry Andric // Symbols, and generate a graph between InputSections with the provided
75b60736ecSDimitry Andric // weights.
CallGraphSort(const COFFLinkerContext & ctx)76e3b55780SDimitry Andric CallGraphSort::CallGraphSort(const COFFLinkerContext &ctx) : ctx(ctx) {
77e3b55780SDimitry Andric const MapVector<SectionPair, uint64_t> &profile = ctx.config.callGraphProfile;
78b60736ecSDimitry Andric DenseMap<const SectionChunk *, int> secToCluster;
79b60736ecSDimitry Andric
80b60736ecSDimitry Andric auto getOrCreateNode = [&](const SectionChunk *isec) -> int {
81b60736ecSDimitry Andric auto res = secToCluster.try_emplace(isec, clusters.size());
82b60736ecSDimitry Andric if (res.second) {
83b60736ecSDimitry Andric sections.push_back(isec);
84b60736ecSDimitry Andric clusters.emplace_back(clusters.size(), isec->getSize());
85b60736ecSDimitry Andric }
86b60736ecSDimitry Andric return res.first->second;
87b60736ecSDimitry Andric };
88b60736ecSDimitry Andric
89b60736ecSDimitry Andric // Create the graph.
90e3b55780SDimitry Andric for (const std::pair<SectionPair, uint64_t> &c : profile) {
91b60736ecSDimitry Andric const auto *fromSec = cast<SectionChunk>(c.first.first->repl);
92b60736ecSDimitry Andric const auto *toSec = cast<SectionChunk>(c.first.second->repl);
93b60736ecSDimitry Andric uint64_t weight = c.second;
94b60736ecSDimitry Andric
95b60736ecSDimitry Andric // Ignore edges between input sections belonging to different output
96b60736ecSDimitry Andric // sections. This is done because otherwise we would end up with clusters
97b60736ecSDimitry Andric // containing input sections that can't actually be placed adjacently in the
98b60736ecSDimitry Andric // output. This messes with the cluster size and density calculations. We
99b60736ecSDimitry Andric // would also end up moving input sections in other output sections without
100b60736ecSDimitry Andric // moving them closer to what calls them.
101c0981da4SDimitry Andric if (ctx.getOutputSection(fromSec) != ctx.getOutputSection(toSec))
102b60736ecSDimitry Andric continue;
103b60736ecSDimitry Andric
104b60736ecSDimitry Andric int from = getOrCreateNode(fromSec);
105b60736ecSDimitry Andric int to = getOrCreateNode(toSec);
106b60736ecSDimitry Andric
107b60736ecSDimitry Andric clusters[to].weight += weight;
108b60736ecSDimitry Andric
109b60736ecSDimitry Andric if (from == to)
110b60736ecSDimitry Andric continue;
111b60736ecSDimitry Andric
112b60736ecSDimitry Andric // Remember the best edge.
113b60736ecSDimitry Andric Cluster &toC = clusters[to];
114b60736ecSDimitry Andric if (toC.bestPred.from == -1 || toC.bestPred.weight < weight) {
115b60736ecSDimitry Andric toC.bestPred.from = from;
116b60736ecSDimitry Andric toC.bestPred.weight = weight;
117b60736ecSDimitry Andric }
118b60736ecSDimitry Andric }
119b60736ecSDimitry Andric for (Cluster &c : clusters)
120b60736ecSDimitry Andric c.initialWeight = c.weight;
121b60736ecSDimitry Andric }
122b60736ecSDimitry Andric
123b60736ecSDimitry Andric // It's bad to merge clusters which would degrade the density too much.
isNewDensityBad(Cluster & a,Cluster & b)124b60736ecSDimitry Andric static bool isNewDensityBad(Cluster &a, Cluster &b) {
125b60736ecSDimitry Andric double newDensity = double(a.weight + b.weight) / double(a.size + b.size);
126b60736ecSDimitry Andric return newDensity < a.getDensity() / MAX_DENSITY_DEGRADATION;
127b60736ecSDimitry Andric }
128b60736ecSDimitry Andric
129b60736ecSDimitry Andric // Find the leader of V's belonged cluster (represented as an equivalence
130b60736ecSDimitry Andric // class). We apply union-find path-halving technique (simple to implement) in
131b60736ecSDimitry Andric // the meantime as it decreases depths and the time complexity.
getLeader(std::vector<int> & leaders,int v)132b60736ecSDimitry Andric static int getLeader(std::vector<int> &leaders, int v) {
133b60736ecSDimitry Andric while (leaders[v] != v) {
134b60736ecSDimitry Andric leaders[v] = leaders[leaders[v]];
135b60736ecSDimitry Andric v = leaders[v];
136b60736ecSDimitry Andric }
137b60736ecSDimitry Andric return v;
138b60736ecSDimitry Andric }
139b60736ecSDimitry Andric
mergeClusters(std::vector<Cluster> & cs,Cluster & into,int intoIdx,Cluster & from,int fromIdx)140b60736ecSDimitry Andric static void mergeClusters(std::vector<Cluster> &cs, Cluster &into, int intoIdx,
141b60736ecSDimitry Andric Cluster &from, int fromIdx) {
142b60736ecSDimitry Andric int tail1 = into.prev, tail2 = from.prev;
143b60736ecSDimitry Andric into.prev = tail2;
144b60736ecSDimitry Andric cs[tail2].next = intoIdx;
145b60736ecSDimitry Andric from.prev = tail1;
146b60736ecSDimitry Andric cs[tail1].next = fromIdx;
147b60736ecSDimitry Andric into.size += from.size;
148b60736ecSDimitry Andric into.weight += from.weight;
149b60736ecSDimitry Andric from.size = 0;
150b60736ecSDimitry Andric from.weight = 0;
151b60736ecSDimitry Andric }
152b60736ecSDimitry Andric
153b60736ecSDimitry Andric // Group InputSections into clusters using the Call-Chain Clustering heuristic
154b60736ecSDimitry Andric // then sort the clusters by density.
run()155b60736ecSDimitry Andric DenseMap<const SectionChunk *, int> CallGraphSort::run() {
156b60736ecSDimitry Andric std::vector<int> sorted(clusters.size());
157b60736ecSDimitry Andric std::vector<int> leaders(clusters.size());
158b60736ecSDimitry Andric
159b60736ecSDimitry Andric std::iota(leaders.begin(), leaders.end(), 0);
160b60736ecSDimitry Andric std::iota(sorted.begin(), sorted.end(), 0);
161b60736ecSDimitry Andric llvm::stable_sort(sorted, [&](int a, int b) {
162b60736ecSDimitry Andric return clusters[a].getDensity() > clusters[b].getDensity();
163b60736ecSDimitry Andric });
164b60736ecSDimitry Andric
165b60736ecSDimitry Andric for (int l : sorted) {
166b60736ecSDimitry Andric // The cluster index is the same as the index of its leader here because
167b60736ecSDimitry Andric // clusters[L] has not been merged into another cluster yet.
168b60736ecSDimitry Andric Cluster &c = clusters[l];
169b60736ecSDimitry Andric
170b60736ecSDimitry Andric // Don't consider merging if the edge is unlikely.
171b60736ecSDimitry Andric if (c.bestPred.from == -1 || c.bestPred.weight * 10 <= c.initialWeight)
172b60736ecSDimitry Andric continue;
173b60736ecSDimitry Andric
174b60736ecSDimitry Andric int predL = getLeader(leaders, c.bestPred.from);
175b60736ecSDimitry Andric if (l == predL)
176b60736ecSDimitry Andric continue;
177b60736ecSDimitry Andric
178b60736ecSDimitry Andric Cluster *predC = &clusters[predL];
179b60736ecSDimitry Andric if (c.size + predC->size > MAX_CLUSTER_SIZE)
180b60736ecSDimitry Andric continue;
181b60736ecSDimitry Andric
182b60736ecSDimitry Andric if (isNewDensityBad(*predC, c))
183b60736ecSDimitry Andric continue;
184b60736ecSDimitry Andric
185b60736ecSDimitry Andric leaders[l] = predL;
186b60736ecSDimitry Andric mergeClusters(clusters, *predC, predL, c, l);
187b60736ecSDimitry Andric }
188b60736ecSDimitry Andric
189b60736ecSDimitry Andric // Sort remaining non-empty clusters by density.
190b60736ecSDimitry Andric sorted.clear();
191b60736ecSDimitry Andric for (int i = 0, e = (int)clusters.size(); i != e; ++i)
192b60736ecSDimitry Andric if (clusters[i].size > 0)
193b60736ecSDimitry Andric sorted.push_back(i);
194b60736ecSDimitry Andric llvm::stable_sort(sorted, [&](int a, int b) {
195b60736ecSDimitry Andric return clusters[a].getDensity() > clusters[b].getDensity();
196b60736ecSDimitry Andric });
197b60736ecSDimitry Andric
198b60736ecSDimitry Andric DenseMap<const SectionChunk *, int> orderMap;
199b60736ecSDimitry Andric // Sections will be sorted by increasing order. Absent sections will have
200b60736ecSDimitry Andric // priority 0 and be placed at the end of sections.
201b60736ecSDimitry Andric int curOrder = INT_MIN;
202b60736ecSDimitry Andric for (int leader : sorted) {
203b60736ecSDimitry Andric for (int i = leader;;) {
204b60736ecSDimitry Andric orderMap[sections[i]] = curOrder++;
205b60736ecSDimitry Andric i = clusters[i].next;
206b60736ecSDimitry Andric if (i == leader)
207b60736ecSDimitry Andric break;
208b60736ecSDimitry Andric }
209b60736ecSDimitry Andric }
210e3b55780SDimitry Andric if (!ctx.config.printSymbolOrder.empty()) {
211b60736ecSDimitry Andric std::error_code ec;
212e3b55780SDimitry Andric raw_fd_ostream os(ctx.config.printSymbolOrder, ec, sys::fs::OF_None);
213b60736ecSDimitry Andric if (ec) {
214e3b55780SDimitry Andric error("cannot open " + ctx.config.printSymbolOrder + ": " + ec.message());
215b60736ecSDimitry Andric return orderMap;
216b60736ecSDimitry Andric }
217b60736ecSDimitry Andric // Print the symbols ordered by C3, in the order of increasing curOrder
218b60736ecSDimitry Andric // Instead of sorting all the orderMap, just repeat the loops above.
219b60736ecSDimitry Andric for (int leader : sorted)
220b60736ecSDimitry Andric for (int i = leader;;) {
221b60736ecSDimitry Andric const SectionChunk *sc = sections[i];
222b60736ecSDimitry Andric
223b60736ecSDimitry Andric // Search all the symbols in the file of the section
224b60736ecSDimitry Andric // and find out a DefinedCOFF symbol with name that is within the
225b60736ecSDimitry Andric // section.
226b60736ecSDimitry Andric for (Symbol *sym : sc->file->getSymbols())
227b60736ecSDimitry Andric if (auto *d = dyn_cast_or_null<DefinedCOFF>(sym))
228b60736ecSDimitry Andric // Filter out non-COMDAT symbols and section symbols.
229b60736ecSDimitry Andric if (d->isCOMDAT && !d->getCOFFSymbol().isSection() &&
230b60736ecSDimitry Andric sc == d->getChunk())
231b60736ecSDimitry Andric os << sym->getName() << "\n";
232b60736ecSDimitry Andric i = clusters[i].next;
233b60736ecSDimitry Andric if (i == leader)
234b60736ecSDimitry Andric break;
235b60736ecSDimitry Andric }
236b60736ecSDimitry Andric }
237b60736ecSDimitry Andric
238b60736ecSDimitry Andric return orderMap;
239b60736ecSDimitry Andric }
240b60736ecSDimitry Andric
241b60736ecSDimitry Andric // Sort sections by the profile data provided by /call-graph-ordering-file
242b60736ecSDimitry Andric //
243b60736ecSDimitry Andric // This first builds a call graph based on the profile data then merges sections
244b60736ecSDimitry Andric // according to the C³ heuristic. All clusters are then sorted by a density
245b60736ecSDimitry Andric // metric to further improve locality.
246c0981da4SDimitry Andric DenseMap<const SectionChunk *, int>
computeCallGraphProfileOrder(const COFFLinkerContext & ctx)247c0981da4SDimitry Andric coff::computeCallGraphProfileOrder(const COFFLinkerContext &ctx) {
248c0981da4SDimitry Andric return CallGraphSort(ctx).run();
249b60736ecSDimitry Andric }
250