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 // ICF is short for Identical Code Folding. That is a size optimization to 10 // identify and merge two or more read-only sections (typically functions) 11 // that happened to have the same contents. It usually reduces output size 12 // by a few percent. 13 // 14 // On Windows, ICF is enabled by default. 15 // 16 // See ELF/ICF.cpp for the details about the algortihm. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "ICF.h" 21 #include "Chunks.h" 22 #include "Symbols.h" 23 #include "lld/Common/ErrorHandler.h" 24 #include "lld/Common/Threads.h" 25 #include "lld/Common/Timer.h" 26 #include "llvm/ADT/Hashing.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/Parallel.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include "llvm/Support/xxhash.h" 31 #include <algorithm> 32 #include <atomic> 33 #include <vector> 34 35 using namespace llvm; 36 37 namespace lld { 38 namespace coff { 39 40 static Timer ICFTimer("ICF", Timer::root()); 41 42 class ICF { 43 public: 44 void run(ArrayRef<Chunk *> V); 45 46 private: 47 void segregate(size_t Begin, size_t End, bool Constant); 48 49 bool assocEquals(const SectionChunk *A, const SectionChunk *B); 50 51 bool equalsConstant(const SectionChunk *A, const SectionChunk *B); 52 bool equalsVariable(const SectionChunk *A, const SectionChunk *B); 53 54 bool isEligible(SectionChunk *C); 55 56 size_t findBoundary(size_t Begin, size_t End); 57 58 void forEachClassRange(size_t Begin, size_t End, 59 std::function<void(size_t, size_t)> Fn); 60 61 void forEachClass(std::function<void(size_t, size_t)> Fn); 62 63 std::vector<SectionChunk *> Chunks; 64 int Cnt = 0; 65 std::atomic<bool> Repeat = {false}; 66 }; 67 68 // Returns true if section S is subject of ICF. 69 // 70 // Microsoft's documentation 71 // (https://msdn.microsoft.com/en-us/library/bxwfs976.aspx; visited April 72 // 2017) says that /opt:icf folds both functions and read-only data. 73 // Despite that, the MSVC linker folds only functions. We found 74 // a few instances of programs that are not safe for data merging. 75 // Therefore, we merge only functions just like the MSVC tool. However, we also 76 // merge read-only sections in a couple of cases where the address of the 77 // section is insignificant to the user program and the behaviour matches that 78 // of the Visual C++ linker. 79 bool ICF::isEligible(SectionChunk *C) { 80 // Non-comdat chunks, dead chunks, and writable chunks are not elegible. 81 bool Writable = C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE; 82 if (!C->isCOMDAT() || !C->Live || Writable) 83 return false; 84 85 // Code sections are eligible. 86 if (C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE) 87 return true; 88 89 // .pdata and .xdata unwind info sections are eligible. 90 StringRef OutSecName = C->getSectionName().split('$').first; 91 if (OutSecName == ".pdata" || OutSecName == ".xdata") 92 return true; 93 94 // So are vtables. 95 if (C->Sym && C->Sym->getName().startswith("??_7")) 96 return true; 97 98 // Anything else not in an address-significance table is eligible. 99 return !C->KeepUnique; 100 } 101 102 // Split an equivalence class into smaller classes. 103 void ICF::segregate(size_t Begin, size_t End, bool Constant) { 104 while (Begin < End) { 105 // Divide [Begin, End) into two. Let Mid be the start index of the 106 // second group. 107 auto Bound = std::stable_partition( 108 Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) { 109 if (Constant) 110 return equalsConstant(Chunks[Begin], S); 111 return equalsVariable(Chunks[Begin], S); 112 }); 113 size_t Mid = Bound - Chunks.begin(); 114 115 // Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an 116 // equivalence class ID because every group ends with a unique index. 117 for (size_t I = Begin; I < Mid; ++I) 118 Chunks[I]->Class[(Cnt + 1) % 2] = Mid; 119 120 // If we created a group, we need to iterate the main loop again. 121 if (Mid != End) 122 Repeat = true; 123 124 Begin = Mid; 125 } 126 } 127 128 // Returns true if two sections' associative children are equal. 129 bool ICF::assocEquals(const SectionChunk *A, const SectionChunk *B) { 130 auto ChildClasses = [&](const SectionChunk *SC) { 131 std::vector<uint32_t> Classes; 132 for (const SectionChunk &C : SC->children()) 133 if (!C.getSectionName().startswith(".debug") && 134 C.getSectionName() != ".gfids$y" && C.getSectionName() != ".gljmp$y") 135 Classes.push_back(C.Class[Cnt % 2]); 136 return Classes; 137 }; 138 return ChildClasses(A) == ChildClasses(B); 139 } 140 141 // Compare "non-moving" part of two sections, namely everything 142 // except relocation targets. 143 bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) { 144 if (A->RelocsSize != B->RelocsSize) 145 return false; 146 147 // Compare relocations. 148 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) { 149 if (R1.Type != R2.Type || 150 R1.VirtualAddress != R2.VirtualAddress) { 151 return false; 152 } 153 Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex); 154 Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex); 155 if (B1 == B2) 156 return true; 157 if (auto *D1 = dyn_cast<DefinedRegular>(B1)) 158 if (auto *D2 = dyn_cast<DefinedRegular>(B2)) 159 return D1->getValue() == D2->getValue() && 160 D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2]; 161 return false; 162 }; 163 if (!std::equal(A->getRelocs().begin(), A->getRelocs().end(), 164 B->getRelocs().begin(), Eq)) 165 return false; 166 167 // Compare section attributes and contents. 168 return A->getOutputCharacteristics() == B->getOutputCharacteristics() && 169 A->getSectionName() == B->getSectionName() && 170 A->Header->SizeOfRawData == B->Header->SizeOfRawData && 171 A->Checksum == B->Checksum && A->getContents() == B->getContents() && 172 assocEquals(A, B); 173 } 174 175 // Compare "moving" part of two sections, namely relocation targets. 176 bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) { 177 // Compare relocations. 178 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) { 179 Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex); 180 Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex); 181 if (B1 == B2) 182 return true; 183 if (auto *D1 = dyn_cast<DefinedRegular>(B1)) 184 if (auto *D2 = dyn_cast<DefinedRegular>(B2)) 185 return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2]; 186 return false; 187 }; 188 return std::equal(A->getRelocs().begin(), A->getRelocs().end(), 189 B->getRelocs().begin(), Eq) && 190 assocEquals(A, B); 191 } 192 193 // Find the first Chunk after Begin that has a different class from Begin. 194 size_t ICF::findBoundary(size_t Begin, size_t End) { 195 for (size_t I = Begin + 1; I < End; ++I) 196 if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2]) 197 return I; 198 return End; 199 } 200 201 void ICF::forEachClassRange(size_t Begin, size_t End, 202 std::function<void(size_t, size_t)> Fn) { 203 while (Begin < End) { 204 size_t Mid = findBoundary(Begin, End); 205 Fn(Begin, Mid); 206 Begin = Mid; 207 } 208 } 209 210 // Call Fn on each class group. 211 void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) { 212 // If the number of sections are too small to use threading, 213 // call Fn sequentially. 214 if (Chunks.size() < 1024) { 215 forEachClassRange(0, Chunks.size(), Fn); 216 ++Cnt; 217 return; 218 } 219 220 // Shard into non-overlapping intervals, and call Fn in parallel. 221 // The sharding must be completed before any calls to Fn are made 222 // so that Fn can modify the Chunks in its shard without causing data 223 // races. 224 const size_t NumShards = 256; 225 size_t Step = Chunks.size() / NumShards; 226 size_t Boundaries[NumShards + 1]; 227 Boundaries[0] = 0; 228 Boundaries[NumShards] = Chunks.size(); 229 parallelForEachN(1, NumShards, [&](size_t I) { 230 Boundaries[I] = findBoundary((I - 1) * Step, Chunks.size()); 231 }); 232 parallelForEachN(1, NumShards + 1, [&](size_t I) { 233 if (Boundaries[I - 1] < Boundaries[I]) { 234 forEachClassRange(Boundaries[I - 1], Boundaries[I], Fn); 235 } 236 }); 237 ++Cnt; 238 } 239 240 // Merge identical COMDAT sections. 241 // Two sections are considered the same if their section headers, 242 // contents and relocations are all the same. 243 void ICF::run(ArrayRef<Chunk *> Vec) { 244 ScopedTimer T(ICFTimer); 245 246 // Collect only mergeable sections and group by hash value. 247 uint32_t NextId = 1; 248 for (Chunk *C : Vec) { 249 if (auto *SC = dyn_cast<SectionChunk>(C)) { 250 if (isEligible(SC)) 251 Chunks.push_back(SC); 252 else 253 SC->Class[0] = NextId++; 254 } 255 } 256 257 // Make sure that ICF doesn't merge sections that are being handled by string 258 // tail merging. 259 for (MergeChunk *MC : MergeChunk::Instances) 260 if (MC) 261 for (SectionChunk *SC : MC->Sections) 262 SC->Class[0] = NextId++; 263 264 // Initially, we use hash values to partition sections. 265 parallelForEach(Chunks, [&](SectionChunk *SC) { 266 SC->Class[0] = xxHash64(SC->getContents()); 267 }); 268 269 // Combine the hashes of the sections referenced by each section into its 270 // hash. 271 for (unsigned Cnt = 0; Cnt != 2; ++Cnt) { 272 parallelForEach(Chunks, [&](SectionChunk *SC) { 273 uint32_t Hash = SC->Class[Cnt % 2]; 274 for (Symbol *B : SC->symbols()) 275 if (auto *Sym = dyn_cast_or_null<DefinedRegular>(B)) 276 Hash += Sym->getChunk()->Class[Cnt % 2]; 277 // Set MSB to 1 to avoid collisions with non-hash classs. 278 SC->Class[(Cnt + 1) % 2] = Hash | (1U << 31); 279 }); 280 } 281 282 // From now on, sections in Chunks are ordered so that sections in 283 // the same group are consecutive in the vector. 284 llvm::stable_sort(Chunks, [](const SectionChunk *A, const SectionChunk *B) { 285 return A->Class[0] < B->Class[0]; 286 }); 287 288 // Compare static contents and assign unique IDs for each static content. 289 forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); }); 290 291 // Split groups by comparing relocations until convergence is obtained. 292 do { 293 Repeat = false; 294 forEachClass( 295 [&](size_t Begin, size_t End) { segregate(Begin, End, false); }); 296 } while (Repeat); 297 298 log("ICF needed " + Twine(Cnt) + " iterations"); 299 300 // Merge sections in the same classs. 301 forEachClass([&](size_t Begin, size_t End) { 302 if (End - Begin == 1) 303 return; 304 305 log("Selected " + Chunks[Begin]->getDebugName()); 306 for (size_t I = Begin + 1; I < End; ++I) { 307 log(" Removed " + Chunks[I]->getDebugName()); 308 Chunks[Begin]->replace(Chunks[I]); 309 } 310 }); 311 } 312 313 // Entry point to ICF. 314 void doICF(ArrayRef<Chunk *> Chunks) { ICF().run(Chunks); } 315 316 } // namespace coff 317 } // namespace lld 318