1763671f3SZequan Wu //===- CallGraphSort.cpp --------------------------------------------------===//
2763671f3SZequan Wu //
3763671f3SZequan Wu // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4763671f3SZequan Wu // See https://llvm.org/LICENSE.txt for license information.
5763671f3SZequan Wu // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6763671f3SZequan Wu //
7763671f3SZequan Wu //===----------------------------------------------------------------------===//
8763671f3SZequan Wu ///
9763671f3SZequan Wu /// This is based on the ELF port, see ELF/CallGraphSort.cpp for the details
10763671f3SZequan Wu /// about the algorithm.
11763671f3SZequan Wu ///
12763671f3SZequan Wu //===----------------------------------------------------------------------===//
13763671f3SZequan Wu
14763671f3SZequan Wu #include "CallGraphSort.h"
15*6f7483b1SAmy Huang #include "COFFLinkerContext.h"
16763671f3SZequan Wu #include "InputFiles.h"
17763671f3SZequan Wu #include "SymbolTable.h"
18763671f3SZequan Wu #include "Symbols.h"
19763671f3SZequan Wu #include "lld/Common/ErrorHandler.h"
20763671f3SZequan Wu
21763671f3SZequan Wu #include <numeric>
22763671f3SZequan Wu
23763671f3SZequan Wu using namespace llvm;
24763671f3SZequan Wu using namespace lld;
25763671f3SZequan Wu using namespace lld::coff;
26763671f3SZequan Wu
27763671f3SZequan Wu namespace {
28763671f3SZequan Wu struct Edge {
29763671f3SZequan Wu int from;
30763671f3SZequan Wu uint64_t weight;
31763671f3SZequan Wu };
32763671f3SZequan Wu
33763671f3SZequan Wu struct Cluster {
Cluster__anon8286af9e0111::Cluster34763671f3SZequan Wu Cluster(int sec, size_t s) : next(sec), prev(sec), size(s) {}
35763671f3SZequan Wu
getDensity__anon8286af9e0111::Cluster36763671f3SZequan Wu double getDensity() const {
37763671f3SZequan Wu if (size == 0)
38763671f3SZequan Wu return 0;
39763671f3SZequan Wu return double(weight) / double(size);
40763671f3SZequan Wu }
41763671f3SZequan Wu
42763671f3SZequan Wu int next;
43763671f3SZequan Wu int prev;
44763671f3SZequan Wu uint64_t size;
45763671f3SZequan Wu uint64_t weight = 0;
46763671f3SZequan Wu uint64_t initialWeight = 0;
47763671f3SZequan Wu Edge bestPred = {-1, 0};
48763671f3SZequan Wu };
49763671f3SZequan Wu
50763671f3SZequan Wu class CallGraphSort {
51763671f3SZequan Wu public:
52*6f7483b1SAmy Huang CallGraphSort(const COFFLinkerContext &ctx);
53763671f3SZequan Wu
54763671f3SZequan Wu DenseMap<const SectionChunk *, int> run();
55763671f3SZequan Wu
56763671f3SZequan Wu private:
57763671f3SZequan Wu std::vector<Cluster> clusters;
58763671f3SZequan Wu std::vector<const SectionChunk *> sections;
59763671f3SZequan Wu };
60763671f3SZequan Wu
61763671f3SZequan Wu // Maximum amount the combined cluster density can be worse than the original
62763671f3SZequan Wu // cluster to consider merging.
63763671f3SZequan Wu constexpr int MAX_DENSITY_DEGRADATION = 8;
64763671f3SZequan Wu
65763671f3SZequan Wu // Maximum cluster size in bytes.
66763671f3SZequan Wu constexpr uint64_t MAX_CLUSTER_SIZE = 1024 * 1024;
67763671f3SZequan Wu } // end anonymous namespace
68763671f3SZequan Wu
69763671f3SZequan Wu using SectionPair = std::pair<const SectionChunk *, const SectionChunk *>;
70763671f3SZequan Wu
71763671f3SZequan Wu // Take the edge list in Config->CallGraphProfile, resolve symbol names to
72763671f3SZequan Wu // Symbols, and generate a graph between InputSections with the provided
73763671f3SZequan Wu // weights.
CallGraphSort(const COFFLinkerContext & ctx)74*6f7483b1SAmy Huang CallGraphSort::CallGraphSort(const COFFLinkerContext &ctx) {
75763671f3SZequan Wu MapVector<SectionPair, uint64_t> &profile = config->callGraphProfile;
76763671f3SZequan Wu DenseMap<const SectionChunk *, int> secToCluster;
77763671f3SZequan Wu
78763671f3SZequan Wu auto getOrCreateNode = [&](const SectionChunk *isec) -> int {
79763671f3SZequan Wu auto res = secToCluster.try_emplace(isec, clusters.size());
80763671f3SZequan Wu if (res.second) {
81763671f3SZequan Wu sections.push_back(isec);
82763671f3SZequan Wu clusters.emplace_back(clusters.size(), isec->getSize());
83763671f3SZequan Wu }
84763671f3SZequan Wu return res.first->second;
85763671f3SZequan Wu };
86763671f3SZequan Wu
87763671f3SZequan Wu // Create the graph.
88763671f3SZequan Wu for (std::pair<SectionPair, uint64_t> &c : profile) {
89763671f3SZequan Wu const auto *fromSec = cast<SectionChunk>(c.first.first->repl);
90763671f3SZequan Wu const auto *toSec = cast<SectionChunk>(c.first.second->repl);
91763671f3SZequan Wu uint64_t weight = c.second;
92763671f3SZequan Wu
93763671f3SZequan Wu // Ignore edges between input sections belonging to different output
94763671f3SZequan Wu // sections. This is done because otherwise we would end up with clusters
95763671f3SZequan Wu // containing input sections that can't actually be placed adjacently in the
96763671f3SZequan Wu // output. This messes with the cluster size and density calculations. We
97763671f3SZequan Wu // would also end up moving input sections in other output sections without
98763671f3SZequan Wu // moving them closer to what calls them.
99*6f7483b1SAmy Huang if (ctx.getOutputSection(fromSec) != ctx.getOutputSection(toSec))
100763671f3SZequan Wu continue;
101763671f3SZequan Wu
102763671f3SZequan Wu int from = getOrCreateNode(fromSec);
103763671f3SZequan Wu int to = getOrCreateNode(toSec);
104763671f3SZequan Wu
105763671f3SZequan Wu clusters[to].weight += weight;
106763671f3SZequan Wu
107763671f3SZequan Wu if (from == to)
108763671f3SZequan Wu continue;
109763671f3SZequan Wu
110763671f3SZequan Wu // Remember the best edge.
111763671f3SZequan Wu Cluster &toC = clusters[to];
112763671f3SZequan Wu if (toC.bestPred.from == -1 || toC.bestPred.weight < weight) {
113763671f3SZequan Wu toC.bestPred.from = from;
114763671f3SZequan Wu toC.bestPred.weight = weight;
115763671f3SZequan Wu }
116763671f3SZequan Wu }
117763671f3SZequan Wu for (Cluster &c : clusters)
118763671f3SZequan Wu c.initialWeight = c.weight;
119763671f3SZequan Wu }
120763671f3SZequan Wu
121763671f3SZequan Wu // It's bad to merge clusters which would degrade the density too much.
isNewDensityBad(Cluster & a,Cluster & b)122763671f3SZequan Wu static bool isNewDensityBad(Cluster &a, Cluster &b) {
123763671f3SZequan Wu double newDensity = double(a.weight + b.weight) / double(a.size + b.size);
124763671f3SZequan Wu return newDensity < a.getDensity() / MAX_DENSITY_DEGRADATION;
125763671f3SZequan Wu }
126763671f3SZequan Wu
127763671f3SZequan Wu // Find the leader of V's belonged cluster (represented as an equivalence
128763671f3SZequan Wu // class). We apply union-find path-halving technique (simple to implement) in
129763671f3SZequan Wu // the meantime as it decreases depths and the time complexity.
getLeader(std::vector<int> & leaders,int v)130763671f3SZequan Wu static int getLeader(std::vector<int> &leaders, int v) {
131763671f3SZequan Wu while (leaders[v] != v) {
132763671f3SZequan Wu leaders[v] = leaders[leaders[v]];
133763671f3SZequan Wu v = leaders[v];
134763671f3SZequan Wu }
135763671f3SZequan Wu return v;
136763671f3SZequan Wu }
137763671f3SZequan Wu
mergeClusters(std::vector<Cluster> & cs,Cluster & into,int intoIdx,Cluster & from,int fromIdx)138763671f3SZequan Wu static void mergeClusters(std::vector<Cluster> &cs, Cluster &into, int intoIdx,
139763671f3SZequan Wu Cluster &from, int fromIdx) {
140763671f3SZequan Wu int tail1 = into.prev, tail2 = from.prev;
141763671f3SZequan Wu into.prev = tail2;
142763671f3SZequan Wu cs[tail2].next = intoIdx;
143763671f3SZequan Wu from.prev = tail1;
144763671f3SZequan Wu cs[tail1].next = fromIdx;
145763671f3SZequan Wu into.size += from.size;
146763671f3SZequan Wu into.weight += from.weight;
147763671f3SZequan Wu from.size = 0;
148763671f3SZequan Wu from.weight = 0;
149763671f3SZequan Wu }
150763671f3SZequan Wu
151763671f3SZequan Wu // Group InputSections into clusters using the Call-Chain Clustering heuristic
152763671f3SZequan Wu // then sort the clusters by density.
run()153763671f3SZequan Wu DenseMap<const SectionChunk *, int> CallGraphSort::run() {
154763671f3SZequan Wu std::vector<int> sorted(clusters.size());
155763671f3SZequan Wu std::vector<int> leaders(clusters.size());
156763671f3SZequan Wu
157763671f3SZequan Wu std::iota(leaders.begin(), leaders.end(), 0);
158763671f3SZequan Wu std::iota(sorted.begin(), sorted.end(), 0);
159763671f3SZequan Wu llvm::stable_sort(sorted, [&](int a, int b) {
160763671f3SZequan Wu return clusters[a].getDensity() > clusters[b].getDensity();
161763671f3SZequan Wu });
162763671f3SZequan Wu
163763671f3SZequan Wu for (int l : sorted) {
164763671f3SZequan Wu // The cluster index is the same as the index of its leader here because
165763671f3SZequan Wu // clusters[L] has not been merged into another cluster yet.
166763671f3SZequan Wu Cluster &c = clusters[l];
167763671f3SZequan Wu
168763671f3SZequan Wu // Don't consider merging if the edge is unlikely.
169763671f3SZequan Wu if (c.bestPred.from == -1 || c.bestPred.weight * 10 <= c.initialWeight)
170763671f3SZequan Wu continue;
171763671f3SZequan Wu
172763671f3SZequan Wu int predL = getLeader(leaders, c.bestPred.from);
173763671f3SZequan Wu if (l == predL)
174763671f3SZequan Wu continue;
175763671f3SZequan Wu
176763671f3SZequan Wu Cluster *predC = &clusters[predL];
177763671f3SZequan Wu if (c.size + predC->size > MAX_CLUSTER_SIZE)
178763671f3SZequan Wu continue;
179763671f3SZequan Wu
180763671f3SZequan Wu if (isNewDensityBad(*predC, c))
181763671f3SZequan Wu continue;
182763671f3SZequan Wu
183763671f3SZequan Wu leaders[l] = predL;
184763671f3SZequan Wu mergeClusters(clusters, *predC, predL, c, l);
185763671f3SZequan Wu }
186763671f3SZequan Wu
187763671f3SZequan Wu // Sort remaining non-empty clusters by density.
188763671f3SZequan Wu sorted.clear();
189763671f3SZequan Wu for (int i = 0, e = (int)clusters.size(); i != e; ++i)
190763671f3SZequan Wu if (clusters[i].size > 0)
191763671f3SZequan Wu sorted.push_back(i);
192763671f3SZequan Wu llvm::stable_sort(sorted, [&](int a, int b) {
193763671f3SZequan Wu return clusters[a].getDensity() > clusters[b].getDensity();
194763671f3SZequan Wu });
195763671f3SZequan Wu
196763671f3SZequan Wu DenseMap<const SectionChunk *, int> orderMap;
197763671f3SZequan Wu // Sections will be sorted by increasing order. Absent sections will have
198763671f3SZequan Wu // priority 0 and be placed at the end of sections.
199763671f3SZequan Wu int curOrder = INT_MIN;
200763671f3SZequan Wu for (int leader : sorted) {
201763671f3SZequan Wu for (int i = leader;;) {
202763671f3SZequan Wu orderMap[sections[i]] = curOrder++;
203763671f3SZequan Wu i = clusters[i].next;
204763671f3SZequan Wu if (i == leader)
205763671f3SZequan Wu break;
206763671f3SZequan Wu }
207763671f3SZequan Wu }
208763671f3SZequan Wu if (!config->printSymbolOrder.empty()) {
209763671f3SZequan Wu std::error_code ec;
210763671f3SZequan Wu raw_fd_ostream os(config->printSymbolOrder, ec, sys::fs::OF_None);
211763671f3SZequan Wu if (ec) {
212763671f3SZequan Wu error("cannot open " + config->printSymbolOrder + ": " + ec.message());
213763671f3SZequan Wu return orderMap;
214763671f3SZequan Wu }
215763671f3SZequan Wu // Print the symbols ordered by C3, in the order of increasing curOrder
216763671f3SZequan Wu // Instead of sorting all the orderMap, just repeat the loops above.
217763671f3SZequan Wu for (int leader : sorted)
218763671f3SZequan Wu for (int i = leader;;) {
219763671f3SZequan Wu const SectionChunk *sc = sections[i];
220763671f3SZequan Wu
221763671f3SZequan Wu // Search all the symbols in the file of the section
222763671f3SZequan Wu // and find out a DefinedCOFF symbol with name that is within the
223763671f3SZequan Wu // section.
224763671f3SZequan Wu for (Symbol *sym : sc->file->getSymbols())
225763671f3SZequan Wu if (auto *d = dyn_cast_or_null<DefinedCOFF>(sym))
226763671f3SZequan Wu // Filter out non-COMDAT symbols and section symbols.
227763671f3SZequan Wu if (d->isCOMDAT && !d->getCOFFSymbol().isSection() &&
228763671f3SZequan Wu sc == d->getChunk())
229763671f3SZequan Wu os << sym->getName() << "\n";
230763671f3SZequan Wu i = clusters[i].next;
231763671f3SZequan Wu if (i == leader)
232763671f3SZequan Wu break;
233763671f3SZequan Wu }
234763671f3SZequan Wu }
235763671f3SZequan Wu
236763671f3SZequan Wu return orderMap;
237763671f3SZequan Wu }
238763671f3SZequan Wu
239763671f3SZequan Wu // Sort sections by the profile data provided by /call-graph-ordering-file
240763671f3SZequan Wu //
241763671f3SZequan Wu // This first builds a call graph based on the profile data then merges sections
242763671f3SZequan Wu // according to the C³ heuristic. All clusters are then sorted by a density
243763671f3SZequan Wu // metric to further improve locality.
244*6f7483b1SAmy Huang DenseMap<const SectionChunk *, int>
computeCallGraphProfileOrder(const COFFLinkerContext & ctx)245*6f7483b1SAmy Huang coff::computeCallGraphProfileOrder(const COFFLinkerContext &ctx) {
246*6f7483b1SAmy Huang return CallGraphSort(ctx).run();
247763671f3SZequan Wu }
248