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