1f23d57a6SLeonard Grey //===- SectionPriorities.cpp ----------------------------------------------===//
2f23d57a6SLeonard Grey //
3f23d57a6SLeonard Grey // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4f23d57a6SLeonard Grey // See https://llvm.org/LICENSE.txt for license information.
5f23d57a6SLeonard Grey // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f23d57a6SLeonard Grey //
7f23d57a6SLeonard Grey //===----------------------------------------------------------------------===//
8f23d57a6SLeonard Grey ///
9f23d57a6SLeonard Grey /// This is based on the ELF port, see ELF/CallGraphSort.cpp for the details
10f23d57a6SLeonard Grey /// about the algorithm.
11f23d57a6SLeonard Grey ///
12f23d57a6SLeonard Grey //===----------------------------------------------------------------------===//
13f23d57a6SLeonard Grey 
14f23d57a6SLeonard Grey #include "SectionPriorities.h"
15f23d57a6SLeonard Grey #include "Config.h"
16f23d57a6SLeonard Grey #include "InputFiles.h"
17f23d57a6SLeonard Grey #include "Symbols.h"
18f23d57a6SLeonard Grey #include "Target.h"
19*a52b9102SLeonard Grey 
20a5c9d717SLeonard Grey #include "lld/Common/Args.h"
21a5c9d717SLeonard Grey #include "lld/Common/CommonLinkerContext.h"
22f23d57a6SLeonard Grey #include "lld/Common/ErrorHandler.h"
23f23d57a6SLeonard Grey #include "llvm/ADT/DenseMap.h"
24f23d57a6SLeonard Grey #include "llvm/ADT/MapVector.h"
25a5c9d717SLeonard Grey #include "llvm/ADT/Optional.h"
26a5c9d717SLeonard Grey #include "llvm/Support/Path.h"
27f23d57a6SLeonard Grey #include "llvm/Support/TimeProfiler.h"
28f23d57a6SLeonard Grey #include "llvm/Support/raw_ostream.h"
29f23d57a6SLeonard Grey #include <numeric>
30f23d57a6SLeonard Grey 
31f23d57a6SLeonard Grey using namespace llvm;
32a5c9d717SLeonard Grey using namespace llvm::MachO;
33a5c9d717SLeonard Grey using namespace llvm::sys;
34f23d57a6SLeonard Grey using namespace lld;
35f23d57a6SLeonard Grey using namespace lld::macho;
36f23d57a6SLeonard Grey 
37f23d57a6SLeonard Grey namespace {
38*a52b9102SLeonard Grey 
39*a52b9102SLeonard Grey size_t lowestPriority = std::numeric_limits<size_t>::max();
40*a52b9102SLeonard Grey 
41f23d57a6SLeonard Grey struct Edge {
42f23d57a6SLeonard Grey   int from;
43f23d57a6SLeonard Grey   uint64_t weight;
44f23d57a6SLeonard Grey };
45f23d57a6SLeonard Grey 
46f23d57a6SLeonard Grey struct Cluster {
47f23d57a6SLeonard Grey   Cluster(int sec, size_t s) : next(sec), prev(sec), size(s) {}
48f23d57a6SLeonard Grey 
49f23d57a6SLeonard Grey   double getDensity() const {
50f23d57a6SLeonard Grey     if (size == 0)
51f23d57a6SLeonard Grey       return 0;
52f23d57a6SLeonard Grey     return double(weight) / double(size);
53f23d57a6SLeonard Grey   }
54f23d57a6SLeonard Grey 
55f23d57a6SLeonard Grey   int next;
56f23d57a6SLeonard Grey   int prev;
57f23d57a6SLeonard Grey   uint64_t size;
58f23d57a6SLeonard Grey   uint64_t weight = 0;
59f23d57a6SLeonard Grey   uint64_t initialWeight = 0;
60f23d57a6SLeonard Grey   Edge bestPred = {-1, 0};
61f23d57a6SLeonard Grey };
62f23d57a6SLeonard Grey 
63f23d57a6SLeonard Grey class CallGraphSort {
64f23d57a6SLeonard Grey public:
65f23d57a6SLeonard Grey   CallGraphSort();
66f23d57a6SLeonard Grey 
67f23d57a6SLeonard Grey   DenseMap<const InputSection *, size_t> run();
68f23d57a6SLeonard Grey 
69f23d57a6SLeonard Grey private:
70f23d57a6SLeonard Grey   std::vector<Cluster> clusters;
71f23d57a6SLeonard Grey   std::vector<const InputSection *> sections;
72f23d57a6SLeonard Grey };
73f23d57a6SLeonard Grey // Maximum amount the combined cluster density can be worse than the original
74f23d57a6SLeonard Grey // cluster to consider merging.
75f23d57a6SLeonard Grey constexpr int MAX_DENSITY_DEGRADATION = 8;
76f23d57a6SLeonard Grey } // end anonymous namespace
77f23d57a6SLeonard Grey 
78f23d57a6SLeonard Grey using SectionPair = std::pair<const InputSection *, const InputSection *>;
79f23d57a6SLeonard Grey 
80f23d57a6SLeonard Grey // Take the edge list in config->callGraphProfile, resolve symbol names to
81f23d57a6SLeonard Grey // Symbols, and generate a graph between InputSections with the provided
82f23d57a6SLeonard Grey // weights.
83f23d57a6SLeonard Grey CallGraphSort::CallGraphSort() {
84f23d57a6SLeonard Grey   MapVector<SectionPair, uint64_t> &profile = config->callGraphProfile;
85f23d57a6SLeonard Grey   DenseMap<const InputSection *, int> secToCluster;
86f23d57a6SLeonard Grey 
87f23d57a6SLeonard Grey   auto getOrCreateCluster = [&](const InputSection *isec) -> int {
88f23d57a6SLeonard Grey     auto res = secToCluster.try_emplace(isec, clusters.size());
89f23d57a6SLeonard Grey     if (res.second) {
90f23d57a6SLeonard Grey       sections.push_back(isec);
91f23d57a6SLeonard Grey       clusters.emplace_back(clusters.size(), isec->getSize());
92f23d57a6SLeonard Grey     }
93f23d57a6SLeonard Grey     return res.first->second;
94f23d57a6SLeonard Grey   };
95f23d57a6SLeonard Grey 
96f23d57a6SLeonard Grey   // Create the graph
97f23d57a6SLeonard Grey   for (std::pair<SectionPair, uint64_t> &c : profile) {
98f23d57a6SLeonard Grey     const auto fromSec = c.first.first->canonical();
99f23d57a6SLeonard Grey     const auto toSec = c.first.second->canonical();
100f23d57a6SLeonard Grey     uint64_t weight = c.second;
101f23d57a6SLeonard Grey     // Ignore edges between input sections belonging to different output
102f23d57a6SLeonard Grey     // sections.  This is done because otherwise we would end up with clusters
103f23d57a6SLeonard Grey     // containing input sections that can't actually be placed adjacently in the
104f23d57a6SLeonard Grey     // output.  This messes with the cluster size and density calculations.  We
105f23d57a6SLeonard Grey     // would also end up moving input sections in other output sections without
106f23d57a6SLeonard Grey     // moving them closer to what calls them.
107f23d57a6SLeonard Grey     if (fromSec->parent != toSec->parent)
108f23d57a6SLeonard Grey       continue;
109f23d57a6SLeonard Grey 
110f23d57a6SLeonard Grey     int from = getOrCreateCluster(fromSec);
111f23d57a6SLeonard Grey     int to = getOrCreateCluster(toSec);
112f23d57a6SLeonard Grey 
113f23d57a6SLeonard Grey     clusters[to].weight += weight;
114f23d57a6SLeonard Grey 
115f23d57a6SLeonard Grey     if (from == to)
116f23d57a6SLeonard Grey       continue;
117f23d57a6SLeonard Grey 
118f23d57a6SLeonard Grey     // Remember the best edge.
119f23d57a6SLeonard Grey     Cluster &toC = clusters[to];
120f23d57a6SLeonard Grey     if (toC.bestPred.from == -1 || toC.bestPred.weight < weight) {
121f23d57a6SLeonard Grey       toC.bestPred.from = from;
122f23d57a6SLeonard Grey       toC.bestPred.weight = weight;
123f23d57a6SLeonard Grey     }
124f23d57a6SLeonard Grey   }
125f23d57a6SLeonard Grey   for (Cluster &c : clusters)
126f23d57a6SLeonard Grey     c.initialWeight = c.weight;
127f23d57a6SLeonard Grey }
128f23d57a6SLeonard Grey 
129f23d57a6SLeonard Grey // It's bad to merge clusters which would degrade the density too much.
130f23d57a6SLeonard Grey static bool isNewDensityBad(Cluster &a, Cluster &b) {
131f23d57a6SLeonard Grey   double newDensity = double(a.weight + b.weight) / double(a.size + b.size);
132f23d57a6SLeonard Grey   return newDensity < a.getDensity() / MAX_DENSITY_DEGRADATION;
133f23d57a6SLeonard Grey }
134f23d57a6SLeonard Grey 
135f23d57a6SLeonard Grey // Find the leader of V's belonged cluster (represented as an equivalence
136f23d57a6SLeonard Grey // class). We apply union-find path-halving technique (simple to implement) in
137f23d57a6SLeonard Grey // the meantime as it decreases depths and the time complexity.
138f23d57a6SLeonard Grey static int getLeader(std::vector<int> &leaders, int v) {
139f23d57a6SLeonard Grey   while (leaders[v] != v) {
140f23d57a6SLeonard Grey     leaders[v] = leaders[leaders[v]];
141f23d57a6SLeonard Grey     v = leaders[v];
142f23d57a6SLeonard Grey   }
143f23d57a6SLeonard Grey   return v;
144f23d57a6SLeonard Grey }
145f23d57a6SLeonard Grey 
146f23d57a6SLeonard Grey static void mergeClusters(std::vector<Cluster> &cs, Cluster &into, int intoIdx,
147f23d57a6SLeonard Grey                           Cluster &from, int fromIdx) {
148f23d57a6SLeonard Grey   int tail1 = into.prev, tail2 = from.prev;
149f23d57a6SLeonard Grey   into.prev = tail2;
150f23d57a6SLeonard Grey   cs[tail2].next = intoIdx;
151f23d57a6SLeonard Grey   from.prev = tail1;
152f23d57a6SLeonard Grey   cs[tail1].next = fromIdx;
153f23d57a6SLeonard Grey   into.size += from.size;
154f23d57a6SLeonard Grey   into.weight += from.weight;
155f23d57a6SLeonard Grey   from.size = 0;
156f23d57a6SLeonard Grey   from.weight = 0;
157f23d57a6SLeonard Grey }
158f23d57a6SLeonard Grey 
159f23d57a6SLeonard Grey // Group InputSections into clusters using the Call-Chain Clustering heuristic
160f23d57a6SLeonard Grey // then sort the clusters by density.
161f23d57a6SLeonard Grey DenseMap<const InputSection *, size_t> CallGraphSort::run() {
162f23d57a6SLeonard Grey   const uint64_t maxClusterSize = target->getPageSize();
163f23d57a6SLeonard Grey 
164f23d57a6SLeonard Grey   // Cluster indices sorted by density.
165f23d57a6SLeonard Grey   std::vector<int> sorted(clusters.size());
166f23d57a6SLeonard Grey   // For union-find.
167f23d57a6SLeonard Grey   std::vector<int> leaders(clusters.size());
168f23d57a6SLeonard Grey 
169f23d57a6SLeonard Grey   std::iota(leaders.begin(), leaders.end(), 0);
170f23d57a6SLeonard Grey   std::iota(sorted.begin(), sorted.end(), 0);
171f23d57a6SLeonard Grey 
172f23d57a6SLeonard Grey   llvm::stable_sort(sorted, [&](int a, int b) {
173f23d57a6SLeonard Grey     return clusters[a].getDensity() > clusters[b].getDensity();
174f23d57a6SLeonard Grey   });
175f23d57a6SLeonard Grey 
176f23d57a6SLeonard Grey   for (int l : sorted) {
177f23d57a6SLeonard Grey     // The cluster index is the same as the index of its leader here because
178f23d57a6SLeonard Grey     // clusters[L] has not been merged into another cluster yet.
179f23d57a6SLeonard Grey     Cluster &c = clusters[l];
180f23d57a6SLeonard Grey 
181f23d57a6SLeonard Grey     // Don't consider merging if the edge is unlikely.
182f23d57a6SLeonard Grey     if (c.bestPred.from == -1 || c.bestPred.weight * 10 <= c.initialWeight)
183f23d57a6SLeonard Grey       continue;
184f23d57a6SLeonard Grey 
185f23d57a6SLeonard Grey     int predL = getLeader(leaders, c.bestPred.from);
186f23d57a6SLeonard Grey     // Already in the same cluster.
187f23d57a6SLeonard Grey     if (l == predL)
188f23d57a6SLeonard Grey       continue;
189f23d57a6SLeonard Grey 
190f23d57a6SLeonard Grey     Cluster *predC = &clusters[predL];
191f23d57a6SLeonard Grey     if (c.size + predC->size > maxClusterSize)
192f23d57a6SLeonard Grey       continue;
193f23d57a6SLeonard Grey 
194f23d57a6SLeonard Grey     if (isNewDensityBad(*predC, c))
195f23d57a6SLeonard Grey       continue;
196f23d57a6SLeonard Grey 
197f23d57a6SLeonard Grey     leaders[l] = predL;
198f23d57a6SLeonard Grey     mergeClusters(clusters, *predC, predL, c, l);
199f23d57a6SLeonard Grey   }
200f23d57a6SLeonard Grey   // Sort remaining non-empty clusters by density.
201f23d57a6SLeonard Grey   sorted.clear();
202f23d57a6SLeonard Grey   for (int i = 0, e = (int)clusters.size(); i != e; ++i)
203f23d57a6SLeonard Grey     if (clusters[i].size > 0)
204f23d57a6SLeonard Grey       sorted.push_back(i);
205f23d57a6SLeonard Grey   llvm::stable_sort(sorted, [&](int a, int b) {
206f23d57a6SLeonard Grey     return clusters[a].getDensity() > clusters[b].getDensity();
207f23d57a6SLeonard Grey   });
208f23d57a6SLeonard Grey 
209f23d57a6SLeonard Grey   DenseMap<const InputSection *, size_t> orderMap;
210f23d57a6SLeonard Grey 
211f23d57a6SLeonard Grey   // Sections will be sorted by decreasing order. Absent sections will have
212f23d57a6SLeonard Grey   // priority 0 and be placed at the end of sections.
213f23d57a6SLeonard Grey   // NB: This is opposite from COFF/ELF to be compatible with the existing
214f23d57a6SLeonard Grey   // order-file code.
215*a52b9102SLeonard Grey   int curOrder = lowestPriority;
216f23d57a6SLeonard Grey   for (int leader : sorted) {
217f23d57a6SLeonard Grey     for (int i = leader;;) {
218f23d57a6SLeonard Grey       orderMap[sections[i]] = curOrder--;
219f23d57a6SLeonard Grey       i = clusters[i].next;
220f23d57a6SLeonard Grey       if (i == leader)
221f23d57a6SLeonard Grey         break;
222f23d57a6SLeonard Grey     }
223f23d57a6SLeonard Grey   }
224f23d57a6SLeonard Grey   if (!config->printSymbolOrder.empty()) {
225f23d57a6SLeonard Grey     std::error_code ec;
226f23d57a6SLeonard Grey     raw_fd_ostream os(config->printSymbolOrder, ec, sys::fs::OF_None);
227f23d57a6SLeonard Grey     if (ec) {
228f23d57a6SLeonard Grey       error("cannot open " + config->printSymbolOrder + ": " + ec.message());
229f23d57a6SLeonard Grey       return orderMap;
230f23d57a6SLeonard Grey     }
231f23d57a6SLeonard Grey     // Print the symbols ordered by C3, in the order of decreasing curOrder
232f23d57a6SLeonard Grey     // Instead of sorting all the orderMap, just repeat the loops above.
233f23d57a6SLeonard Grey     for (int leader : sorted)
234f23d57a6SLeonard Grey       for (int i = leader;;) {
235f23d57a6SLeonard Grey         const InputSection *isec = sections[i];
236f23d57a6SLeonard Grey         // Search all the symbols in the file of the section
237f23d57a6SLeonard Grey         // and find out a Defined symbol with name that is within the
238f23d57a6SLeonard Grey         // section.
239f23d57a6SLeonard Grey         for (Symbol *sym : isec->getFile()->symbols) {
240f23d57a6SLeonard Grey           if (auto *d = dyn_cast_or_null<Defined>(sym)) {
241f23d57a6SLeonard Grey             if (d->isec == isec)
242f23d57a6SLeonard Grey               os << sym->getName() << "\n";
243f23d57a6SLeonard Grey           }
244f23d57a6SLeonard Grey         }
245f23d57a6SLeonard Grey         i = clusters[i].next;
246f23d57a6SLeonard Grey         if (i == leader)
247f23d57a6SLeonard Grey           break;
248f23d57a6SLeonard Grey       }
249f23d57a6SLeonard Grey   }
250f23d57a6SLeonard Grey 
251f23d57a6SLeonard Grey   return orderMap;
252f23d57a6SLeonard Grey }
253f23d57a6SLeonard Grey 
254*a52b9102SLeonard Grey static Optional<size_t> getSymbolPriority(const Defined *sym) {
255*a52b9102SLeonard Grey   if (sym->isAbsolute())
256*a52b9102SLeonard Grey     return None;
257*a52b9102SLeonard Grey 
258*a52b9102SLeonard Grey   auto it = config->priorities.find(sym->getName());
259*a52b9102SLeonard Grey   if (it == config->priorities.end())
260*a52b9102SLeonard Grey     return None;
261*a52b9102SLeonard Grey   const SymbolPriorityEntry &entry = it->second;
262*a52b9102SLeonard Grey   const InputFile *f = sym->isec->getFile();
263*a52b9102SLeonard Grey   if (!f)
264*a52b9102SLeonard Grey     return entry.anyObjectFile;
265a5c9d717SLeonard Grey   // We don't use toString(InputFile *) here because it returns the full path
266a5c9d717SLeonard Grey   // for object files, and we only want the basename.
267a5c9d717SLeonard Grey   StringRef filename;
268a5c9d717SLeonard Grey   if (f->archiveName.empty())
269a5c9d717SLeonard Grey     filename = path::filename(f->getName());
270a5c9d717SLeonard Grey   else
271a5c9d717SLeonard Grey     filename = saver().save(path::filename(f->archiveName) + "(" +
272a5c9d717SLeonard Grey                             path::filename(f->getName()) + ")");
273a5c9d717SLeonard Grey   return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile);
274a5c9d717SLeonard Grey }
275a5c9d717SLeonard Grey 
276a5c9d717SLeonard Grey void macho::extractCallGraphProfile() {
277a5c9d717SLeonard Grey   TimeTraceScope timeScope("Extract call graph profile");
278*a52b9102SLeonard Grey   bool hasOrderFile = !config->priorities.empty();
279a5c9d717SLeonard Grey   for (const InputFile *file : inputFiles) {
280a5c9d717SLeonard Grey     auto *obj = dyn_cast_or_null<ObjFile>(file);
281a5c9d717SLeonard Grey     if (!obj)
282a5c9d717SLeonard Grey       continue;
283a5c9d717SLeonard Grey     for (const CallGraphEntry &entry : obj->callGraph) {
284a5c9d717SLeonard Grey       assert(entry.fromIndex < obj->symbols.size() &&
285a5c9d717SLeonard Grey              entry.toIndex < obj->symbols.size());
286a5c9d717SLeonard Grey       auto *fromSym = dyn_cast_or_null<Defined>(obj->symbols[entry.fromIndex]);
287a5c9d717SLeonard Grey       auto *toSym = dyn_cast_or_null<Defined>(obj->symbols[entry.toIndex]);
288*a52b9102SLeonard Grey       if (!fromSym || !toSym ||
289*a52b9102SLeonard Grey           (hasOrderFile &&
290*a52b9102SLeonard Grey            (getSymbolPriority(fromSym) || getSymbolPriority(toSym))))
291a5c9d717SLeonard Grey         continue;
292a5c9d717SLeonard Grey       config->callGraphProfile[{fromSym->isec, toSym->isec}] += entry.count;
293a5c9d717SLeonard Grey     }
294a5c9d717SLeonard Grey   }
295a5c9d717SLeonard Grey }
296a5c9d717SLeonard Grey 
297a5c9d717SLeonard Grey void macho::parseOrderFile(StringRef path) {
298*a52b9102SLeonard Grey   assert(config->callGraphProfile.empty() &&
299*a52b9102SLeonard Grey          "Order file must be parsed before call graph profile is processed");
300a5c9d717SLeonard Grey   Optional<MemoryBufferRef> buffer = readFile(path);
301a5c9d717SLeonard Grey   if (!buffer) {
302a5c9d717SLeonard Grey     error("Could not read order file at " + path);
303a5c9d717SLeonard Grey     return;
304a5c9d717SLeonard Grey   }
305a5c9d717SLeonard Grey 
306a5c9d717SLeonard Grey   MemoryBufferRef mbref = *buffer;
307a5c9d717SLeonard Grey   size_t priority = std::numeric_limits<size_t>::max();
308a5c9d717SLeonard Grey   for (StringRef line : args::getLines(mbref)) {
309a5c9d717SLeonard Grey     StringRef objectFile, symbol;
310a5c9d717SLeonard Grey     line = line.take_until([](char c) { return c == '#'; }); // ignore comments
311a5c9d717SLeonard Grey     line = line.ltrim();
312a5c9d717SLeonard Grey 
313a5c9d717SLeonard Grey     CPUType cpuType = StringSwitch<CPUType>(line)
314a5c9d717SLeonard Grey                           .StartsWith("i386:", CPU_TYPE_I386)
315a5c9d717SLeonard Grey                           .StartsWith("x86_64:", CPU_TYPE_X86_64)
316a5c9d717SLeonard Grey                           .StartsWith("arm:", CPU_TYPE_ARM)
317a5c9d717SLeonard Grey                           .StartsWith("arm64:", CPU_TYPE_ARM64)
318a5c9d717SLeonard Grey                           .StartsWith("ppc:", CPU_TYPE_POWERPC)
319a5c9d717SLeonard Grey                           .StartsWith("ppc64:", CPU_TYPE_POWERPC64)
320a5c9d717SLeonard Grey                           .Default(CPU_TYPE_ANY);
321a5c9d717SLeonard Grey 
322a5c9d717SLeonard Grey     if (cpuType != CPU_TYPE_ANY && cpuType != target->cpuType)
323a5c9d717SLeonard Grey       continue;
324a5c9d717SLeonard Grey 
325a5c9d717SLeonard Grey     // Drop the CPU type as well as the colon
326a5c9d717SLeonard Grey     if (cpuType != CPU_TYPE_ANY)
327a5c9d717SLeonard Grey       line = line.drop_until([](char c) { return c == ':'; }).drop_front();
328a5c9d717SLeonard Grey 
329a5c9d717SLeonard Grey     constexpr std::array<StringRef, 2> fileEnds = {".o:", ".o):"};
330a5c9d717SLeonard Grey     for (StringRef fileEnd : fileEnds) {
331a5c9d717SLeonard Grey       size_t pos = line.find(fileEnd);
332a5c9d717SLeonard Grey       if (pos != StringRef::npos) {
333a5c9d717SLeonard Grey         // Split the string around the colon
334a5c9d717SLeonard Grey         objectFile = line.take_front(pos + fileEnd.size() - 1);
335a5c9d717SLeonard Grey         line = line.drop_front(pos + fileEnd.size());
336a5c9d717SLeonard Grey         break;
337a5c9d717SLeonard Grey       }
338a5c9d717SLeonard Grey     }
339a5c9d717SLeonard Grey     symbol = line.trim();
340a5c9d717SLeonard Grey 
341a5c9d717SLeonard Grey     if (!symbol.empty()) {
342a5c9d717SLeonard Grey       SymbolPriorityEntry &entry = config->priorities[symbol];
343a5c9d717SLeonard Grey       if (!objectFile.empty())
344a5c9d717SLeonard Grey         entry.objectFiles.insert(std::make_pair(objectFile, priority));
345a5c9d717SLeonard Grey       else
346a5c9d717SLeonard Grey         entry.anyObjectFile = std::max(entry.anyObjectFile, priority);
347a5c9d717SLeonard Grey     }
348a5c9d717SLeonard Grey 
349a5c9d717SLeonard Grey     --priority;
350a5c9d717SLeonard Grey   }
351*a52b9102SLeonard Grey   lowestPriority = priority;
352a5c9d717SLeonard Grey }
353a5c9d717SLeonard Grey 
354f23d57a6SLeonard Grey // Sort sections by the profile data provided by __LLVM,__cg_profile sections.
355f23d57a6SLeonard Grey //
356f23d57a6SLeonard Grey // This first builds a call graph based on the profile data then merges sections
357f23d57a6SLeonard Grey // according to the C³ heuristic. All clusters are then sorted by a density
358f23d57a6SLeonard Grey // metric to further improve locality.
359a5c9d717SLeonard Grey static DenseMap<const InputSection *, size_t> computeCallGraphProfileOrder() {
360f23d57a6SLeonard Grey   TimeTraceScope timeScope("Call graph profile sort");
361f23d57a6SLeonard Grey   return CallGraphSort().run();
362f23d57a6SLeonard Grey }
363a5c9d717SLeonard Grey 
364a5c9d717SLeonard Grey DenseMap<const InputSection *, size_t> macho::buildInputSectionPriorities() {
365a5c9d717SLeonard Grey   DenseMap<const InputSection *, size_t> sectionPriorities;
366*a52b9102SLeonard Grey   if (config->callGraphProfileSort)
367*a52b9102SLeonard Grey     sectionPriorities = computeCallGraphProfileOrder();
368a5c9d717SLeonard Grey 
369a5c9d717SLeonard Grey   if (config->priorities.empty())
370a5c9d717SLeonard Grey     return sectionPriorities;
371a5c9d717SLeonard Grey 
372*a52b9102SLeonard Grey   auto addSym = [&](const Defined *sym) {
373*a52b9102SLeonard Grey     Optional<size_t> symbolPriority = getSymbolPriority(sym);
374*a52b9102SLeonard Grey     if (!symbolPriority.hasValue())
375a5c9d717SLeonard Grey       return;
376*a52b9102SLeonard Grey     size_t &priority = sectionPriorities[sym->isec];
377*a52b9102SLeonard Grey     priority = std::max(priority, symbolPriority.getValue());
378a5c9d717SLeonard Grey   };
379a5c9d717SLeonard Grey 
380a5c9d717SLeonard Grey   // TODO: Make sure this handles weak symbols correctly.
381a5c9d717SLeonard Grey   for (const InputFile *file : inputFiles) {
382a5c9d717SLeonard Grey     if (isa<ObjFile>(file))
383a5c9d717SLeonard Grey       for (Symbol *sym : file->symbols)
384a5c9d717SLeonard Grey         if (auto *d = dyn_cast_or_null<Defined>(sym))
385*a52b9102SLeonard Grey           addSym(d);
386a5c9d717SLeonard Grey   }
387a5c9d717SLeonard Grey 
388a5c9d717SLeonard Grey   return sectionPriorities;
389a5c9d717SLeonard Grey }
390