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