1 //===- ICF.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 #include "ICF.h" 10 #include "ConcatOutputSection.h" 11 #include "InputSection.h" 12 #include "Symbols.h" 13 #include "UnwindInfoSection.h" 14 15 #include "lld/Common/CommonLinkerContext.h" 16 #include "llvm/Support/Parallel.h" 17 #include "llvm/Support/TimeProfiler.h" 18 #include "llvm/Support/xxhash.h" 19 20 #include <atomic> 21 22 using namespace llvm; 23 using namespace lld; 24 using namespace lld::macho; 25 26 static constexpr bool verboseDiagnostics = false; 27 28 class ICF { 29 public: 30 ICF(std::vector<ConcatInputSection *> &inputs); 31 void run(); 32 33 using EqualsFn = bool (ICF::*)(const ConcatInputSection *, 34 const ConcatInputSection *); 35 void segregate(size_t begin, size_t end, EqualsFn); 36 size_t findBoundary(size_t begin, size_t end); 37 void forEachClassRange(size_t begin, size_t end, 38 llvm::function_ref<void(size_t, size_t)> func); 39 void forEachClass(llvm::function_ref<void(size_t, size_t)> func); 40 41 bool equalsConstant(const ConcatInputSection *ia, 42 const ConcatInputSection *ib); 43 bool equalsVariable(const ConcatInputSection *ia, 44 const ConcatInputSection *ib); 45 46 // ICF needs a copy of the inputs vector because its equivalence-class 47 // segregation algorithm destroys the proper sequence. 48 std::vector<ConcatInputSection *> icfInputs; 49 50 unsigned icfPass = 0; 51 std::atomic<bool> icfRepeat{false}; 52 std::atomic<uint64_t> equalsConstantCount{0}; 53 std::atomic<uint64_t> equalsVariableCount{0}; 54 }; 55 56 ICF::ICF(std::vector<ConcatInputSection *> &inputs) { 57 icfInputs.assign(inputs.begin(), inputs.end()); 58 } 59 60 // ICF = Identical Code Folding 61 // 62 // We only fold __TEXT,__text, so this is really "code" folding, and not 63 // "COMDAT" folding. String and scalar constant literals are deduplicated 64 // elsewhere. 65 // 66 // Summary of segments & sections: 67 // 68 // The __TEXT segment is readonly at the MMU. Some sections are already 69 // deduplicated elsewhere (__TEXT,__cstring & __TEXT,__literal*) and some are 70 // synthetic and inherently free of duplicates (__TEXT,__stubs & 71 // __TEXT,__unwind_info). Note that we don't yet run ICF on __TEXT,__const, 72 // because doing so induces many test failures. 73 // 74 // The __LINKEDIT segment is readonly at the MMU, yet entirely synthetic, and 75 // thus ineligible for ICF. 76 // 77 // The __DATA_CONST segment is read/write at the MMU, but is logically const to 78 // the application after dyld applies fixups to pointer data. We currently 79 // fold only the __DATA_CONST,__cfstring section. 80 // 81 // The __DATA segment is read/write at the MMU, and as application-writeable 82 // data, none of its sections are eligible for ICF. 83 // 84 // Please see the large block comment in lld/ELF/ICF.cpp for an explanation 85 // of the segregation algorithm. 86 // 87 // FIXME(gkm): implement keep-unique attributes 88 // FIXME(gkm): implement address-significance tables for MachO object files 89 90 // Compare "non-moving" parts of two ConcatInputSections, namely everything 91 // except references to other ConcatInputSections. 92 bool ICF::equalsConstant(const ConcatInputSection *ia, 93 const ConcatInputSection *ib) { 94 if (verboseDiagnostics) 95 ++equalsConstantCount; 96 // We can only fold within the same OutputSection. 97 if (ia->parent != ib->parent) 98 return false; 99 if (ia->data.size() != ib->data.size()) 100 return false; 101 if (ia->data != ib->data) 102 return false; 103 if (ia->relocs.size() != ib->relocs.size()) 104 return false; 105 auto f = [](const Reloc &ra, const Reloc &rb) { 106 if (ra.type != rb.type) 107 return false; 108 if (ra.pcrel != rb.pcrel) 109 return false; 110 if (ra.length != rb.length) 111 return false; 112 if (ra.offset != rb.offset) 113 return false; 114 if (ra.addend != rb.addend) 115 return false; 116 if (ra.referent.is<Symbol *>() != rb.referent.is<Symbol *>()) 117 return false; 118 119 InputSection *isecA, *isecB; 120 121 uint64_t valueA = 0; 122 uint64_t valueB = 0; 123 if (ra.referent.is<Symbol *>()) { 124 const auto *sa = ra.referent.get<Symbol *>(); 125 const auto *sb = rb.referent.get<Symbol *>(); 126 if (sa->kind() != sb->kind()) 127 return false; 128 if (!isa<Defined>(sa)) { 129 // ICF runs before Undefineds are reported. 130 assert(isa<DylibSymbol>(sa) || isa<Undefined>(sa)); 131 return sa == sb; 132 } 133 const auto *da = cast<Defined>(sa); 134 const auto *db = cast<Defined>(sb); 135 if (!da->isec || !db->isec) { 136 assert(da->isAbsolute() && db->isAbsolute()); 137 return da->value == db->value; 138 } 139 isecA = da->isec; 140 valueA = da->value; 141 isecB = db->isec; 142 valueB = db->value; 143 } else { 144 isecA = ra.referent.get<InputSection *>(); 145 isecB = rb.referent.get<InputSection *>(); 146 } 147 148 if (isecA->parent != isecB->parent) 149 return false; 150 // Sections with identical parents should be of the same kind. 151 assert(isecA->kind() == isecB->kind()); 152 // We will compare ConcatInputSection contents in equalsVariable. 153 if (isa<ConcatInputSection>(isecA)) 154 return true; 155 // Else we have two literal sections. References to them are equal iff their 156 // offsets in the output section are equal. 157 return isecA->getOffset(valueA + ra.addend) == 158 isecB->getOffset(valueB + rb.addend); 159 }; 160 return std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(), 161 f); 162 } 163 164 // Compare the "moving" parts of two ConcatInputSections -- i.e. everything not 165 // handled by equalsConstant(). 166 bool ICF::equalsVariable(const ConcatInputSection *ia, 167 const ConcatInputSection *ib) { 168 if (verboseDiagnostics) 169 ++equalsVariableCount; 170 assert(ia->relocs.size() == ib->relocs.size()); 171 auto f = [this](const Reloc &ra, const Reloc &rb) { 172 // We already filtered out mismatching values/addends in equalsConstant. 173 if (ra.referent == rb.referent) 174 return true; 175 const ConcatInputSection *isecA, *isecB; 176 if (ra.referent.is<Symbol *>()) { 177 // Matching DylibSymbols are already filtered out by the 178 // identical-referent check above. Non-matching DylibSymbols were filtered 179 // out in equalsConstant(). So we can safely cast to Defined here. 180 const auto *da = cast<Defined>(ra.referent.get<Symbol *>()); 181 const auto *db = cast<Defined>(rb.referent.get<Symbol *>()); 182 if (da->isAbsolute()) 183 return true; 184 isecA = dyn_cast<ConcatInputSection>(da->isec); 185 if (!isecA) 186 return true; // literal sections were checked in equalsConstant. 187 isecB = cast<ConcatInputSection>(db->isec); 188 } else { 189 const auto *sa = ra.referent.get<InputSection *>(); 190 const auto *sb = rb.referent.get<InputSection *>(); 191 isecA = dyn_cast<ConcatInputSection>(sa); 192 if (!isecA) 193 return true; 194 isecB = cast<ConcatInputSection>(sb); 195 } 196 return isecA->icfEqClass[icfPass % 2] == isecB->icfEqClass[icfPass % 2]; 197 }; 198 if (!std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(), f)) 199 return false; 200 201 // If there are symbols with associated unwind info, check that the unwind 202 // info matches. For simplicity, we only handle the case where there are only 203 // symbols at offset zero within the section (which is typically the case with 204 // .subsections_via_symbols.) 205 auto hasCU = [](Defined *d) { return d->unwindEntry != nullptr; }; 206 auto itA = std::find_if(ia->symbols.begin(), ia->symbols.end(), hasCU); 207 auto itB = std::find_if(ib->symbols.begin(), ib->symbols.end(), hasCU); 208 if (itA == ia->symbols.end()) 209 return itB == ib->symbols.end(); 210 if (itB == ib->symbols.end()) 211 return false; 212 const Defined *da = *itA; 213 const Defined *db = *itB; 214 if (da->unwindEntry->icfEqClass[icfPass % 2] != 215 db->unwindEntry->icfEqClass[icfPass % 2] || 216 da->value != 0 || db->value != 0) 217 return false; 218 auto isZero = [](Defined *d) { return d->value == 0; }; 219 return std::find_if_not(std::next(itA), ia->symbols.end(), isZero) == 220 ia->symbols.end() && 221 std::find_if_not(std::next(itB), ib->symbols.end(), isZero) == 222 ib->symbols.end(); 223 } 224 225 // Find the first InputSection after BEGIN whose equivalence class differs 226 size_t ICF::findBoundary(size_t begin, size_t end) { 227 uint64_t beginHash = icfInputs[begin]->icfEqClass[icfPass % 2]; 228 for (size_t i = begin + 1; i < end; ++i) 229 if (beginHash != icfInputs[i]->icfEqClass[icfPass % 2]) 230 return i; 231 return end; 232 } 233 234 // Invoke FUNC on subranges with matching equivalence class 235 void ICF::forEachClassRange(size_t begin, size_t end, 236 llvm::function_ref<void(size_t, size_t)> func) { 237 while (begin < end) { 238 size_t mid = findBoundary(begin, end); 239 func(begin, mid); 240 begin = mid; 241 } 242 } 243 244 // Split icfInputs into shards, then parallelize invocation of FUNC on subranges 245 // with matching equivalence class 246 void ICF::forEachClass(llvm::function_ref<void(size_t, size_t)> func) { 247 // Only use threads when the benefits outweigh the overhead. 248 const size_t threadingThreshold = 1024; 249 if (icfInputs.size() < threadingThreshold) { 250 forEachClassRange(0, icfInputs.size(), func); 251 ++icfPass; 252 return; 253 } 254 255 // Shard into non-overlapping intervals, and call FUNC in parallel. The 256 // sharding must be completed before any calls to FUNC are made so that FUNC 257 // can modify the InputSection in its shard without causing data races. 258 const size_t shards = 256; 259 size_t step = icfInputs.size() / shards; 260 size_t boundaries[shards + 1]; 261 boundaries[0] = 0; 262 boundaries[shards] = icfInputs.size(); 263 parallelForEachN(1, shards, [&](size_t i) { 264 boundaries[i] = findBoundary((i - 1) * step, icfInputs.size()); 265 }); 266 parallelForEachN(1, shards + 1, [&](size_t i) { 267 if (boundaries[i - 1] < boundaries[i]) { 268 forEachClassRange(boundaries[i - 1], boundaries[i], func); 269 } 270 }); 271 ++icfPass; 272 } 273 274 void ICF::run() { 275 // Into each origin-section hash, combine all reloc referent section hashes. 276 for (icfPass = 0; icfPass < 2; ++icfPass) { 277 parallelForEach(icfInputs, [&](ConcatInputSection *isec) { 278 uint32_t hash = isec->icfEqClass[icfPass % 2]; 279 for (const Reloc &r : isec->relocs) { 280 if (auto *sym = r.referent.dyn_cast<Symbol *>()) { 281 if (auto *defined = dyn_cast<Defined>(sym)) { 282 if (defined->isec) { 283 if (auto referentIsec = 284 dyn_cast<ConcatInputSection>(defined->isec)) 285 hash += defined->value + referentIsec->icfEqClass[icfPass % 2]; 286 else 287 hash += defined->isec->kind() + 288 defined->isec->getOffset(defined->value); 289 } else { 290 hash += defined->value; 291 } 292 } else { 293 // ICF runs before Undefined diags 294 assert(isa<Undefined>(sym) || isa<DylibSymbol>(sym)); 295 } 296 } 297 } 298 // Set MSB to 1 to avoid collisions with non-hashed classes. 299 isec->icfEqClass[(icfPass + 1) % 2] = hash | (1ull << 31); 300 }); 301 } 302 303 llvm::stable_sort( 304 icfInputs, [](const ConcatInputSection *a, const ConcatInputSection *b) { 305 return a->icfEqClass[0] < b->icfEqClass[0]; 306 }); 307 forEachClass([&](size_t begin, size_t end) { 308 segregate(begin, end, &ICF::equalsConstant); 309 }); 310 311 // Split equivalence groups by comparing relocations until convergence 312 do { 313 icfRepeat = false; 314 forEachClass([&](size_t begin, size_t end) { 315 segregate(begin, end, &ICF::equalsVariable); 316 }); 317 } while (icfRepeat); 318 log("ICF needed " + Twine(icfPass) + " iterations"); 319 if (verboseDiagnostics) { 320 log("equalsConstant() called " + Twine(equalsConstantCount) + " times"); 321 log("equalsVariable() called " + Twine(equalsVariableCount) + " times"); 322 } 323 324 // Fold sections within equivalence classes 325 forEachClass([&](size_t begin, size_t end) { 326 if (end - begin < 2) 327 return; 328 ConcatInputSection *beginIsec = icfInputs[begin]; 329 for (size_t i = begin + 1; i < end; ++i) 330 beginIsec->foldIdentical(icfInputs[i]); 331 }); 332 } 333 334 // Split an equivalence class into smaller classes. 335 void ICF::segregate(size_t begin, size_t end, EqualsFn equals) { 336 while (begin < end) { 337 // Divide [begin, end) into two. Let mid be the start index of the 338 // second group. 339 auto bound = std::stable_partition( 340 icfInputs.begin() + begin + 1, icfInputs.begin() + end, 341 [&](ConcatInputSection *isec) { 342 return (this->*equals)(icfInputs[begin], isec); 343 }); 344 size_t mid = bound - icfInputs.begin(); 345 346 // Split [begin, end) into [begin, mid) and [mid, end). We use mid as an 347 // equivalence class ID because every group ends with a unique index. 348 for (size_t i = begin; i < mid; ++i) 349 icfInputs[i]->icfEqClass[(icfPass + 1) % 2] = mid; 350 351 // If we created a group, we need to iterate the main loop again. 352 if (mid != end) 353 icfRepeat = true; 354 355 begin = mid; 356 } 357 } 358 359 void macho::foldIdenticalSections() { 360 TimeTraceScope timeScope("Fold Identical Code Sections"); 361 // The ICF equivalence-class segregation algorithm relies on pre-computed 362 // hashes of InputSection::data for the ConcatOutputSection::inputs and all 363 // sections referenced by their relocs. We could recursively traverse the 364 // relocs to find every referenced InputSection, but that precludes easy 365 // parallelization. Therefore, we hash every InputSection here where we have 366 // them all accessible as simple vectors. 367 368 // If an InputSection is ineligible for ICF, we give it a unique ID to force 369 // it into an unfoldable singleton equivalence class. Begin the unique-ID 370 // space at inputSections.size(), so that it will never intersect with 371 // equivalence-class IDs which begin at 0. Since hashes & unique IDs never 372 // coexist with equivalence-class IDs, this is not necessary, but might help 373 // someone keep the numbers straight in case we ever need to debug the 374 // ICF::segregate() 375 std::vector<ConcatInputSection *> hashable; 376 uint64_t icfUniqueID = inputSections.size(); 377 for (ConcatInputSection *isec : inputSections) { 378 // FIXME: consider non-code __text sections as hashable? 379 bool isHashable = (isCodeSection(isec) || isCfStringSection(isec)) && 380 !isec->shouldOmitFromOutput() && 381 sectionType(isec->getFlags()) == MachO::S_REGULAR; 382 if (isHashable) { 383 hashable.push_back(isec); 384 for (Defined *d : isec->symbols) 385 if (d->unwindEntry) 386 hashable.push_back(d->unwindEntry); 387 } else { 388 isec->icfEqClass[0] = ++icfUniqueID; 389 } 390 } 391 parallelForEach(hashable, [](ConcatInputSection *isec) { 392 assert(isec->icfEqClass[0] == 0); // don't overwrite a unique ID! 393 // Turn-on the top bit to guarantee that valid hashes have no collisions 394 // with the small-integer unique IDs for ICF-ineligible sections 395 isec->icfEqClass[0] = xxHash64(isec->data) | (1ull << 31); 396 }); 397 // Now that every input section is either hashed or marked as unique, run the 398 // segregation algorithm to detect foldable subsections. 399 ICF(hashable).run(); 400 } 401