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