1 //===- ICF.cpp ------------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ICF is short for Identical Code Folding. That is a size optimization to
11 // identify and merge two or more read-only sections (typically functions)
12 // that happened to have the same contents. It usually reduces output size
15 // On Windows, ICF is enabled by default.
17 // See ELF/ICF.cpp for the details about the algortihm.
19 //===----------------------------------------------------------------------===//
24 #include "lld/Common/ErrorHandler.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"
40 static Timer ICFTimer("ICF", Timer::root());
44 void run(ArrayRef<Chunk *> V);
47 void segregate(size_t Begin, size_t End, bool Constant);
49 bool assocEquals(const SectionChunk *A, const SectionChunk *B);
51 bool equalsConstant(const SectionChunk *A, const SectionChunk *B);
52 bool equalsVariable(const SectionChunk *A, const SectionChunk *B);
54 uint32_t getHash(SectionChunk *C);
55 bool isEligible(SectionChunk *C);
57 size_t findBoundary(size_t Begin, size_t End);
59 void forEachClassRange(size_t Begin, size_t End,
60 std::function<void(size_t, size_t)> Fn);
62 void forEachClass(std::function<void(size_t, size_t)> Fn);
64 std::vector<SectionChunk *> Chunks;
66 std::atomic<bool> Repeat = {false};
69 // Returns true if section S is subject of ICF.
71 // Microsoft's documentation
72 // (https://msdn.microsoft.com/en-us/library/bxwfs976.aspx; visited April
73 // 2017) says that /opt:icf folds both functions and read-only data.
74 // Despite that, the MSVC linker folds only functions. We found
75 // a few instances of programs that are not safe for data merging.
76 // Therefore, we merge only functions just like the MSVC tool. However, we also
77 // merge read-only sections in a couple of cases where the address of the
78 // section is insignificant to the user program and the behaviour matches that
79 // of the Visual C++ linker.
80 bool ICF::isEligible(SectionChunk *C) {
81 // Non-comdat chunks, dead chunks, and writable chunks are not elegible.
82 bool Writable = C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
83 if (!C->isCOMDAT() || !C->isLive() || Writable)
86 // Code sections are eligible.
87 if (C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
90 // .pdata and .xdata unwind info sections are eligible.
91 StringRef OutSecName = C->getSectionName().split('$').first;
92 if (OutSecName == ".pdata" || OutSecName == ".xdata")
96 return C->Sym && C->Sym->getName().startswith("??_7");
99 // Split an equivalence class into smaller classes.
100 void ICF::segregate(size_t Begin, size_t End, bool Constant) {
101 while (Begin < End) {
102 // Divide [Begin, End) into two. Let Mid be the start index of the
104 auto Bound = std::stable_partition(
105 Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
107 return equalsConstant(Chunks[Begin], S);
108 return equalsVariable(Chunks[Begin], S);
110 size_t Mid = Bound - Chunks.begin();
112 // Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
113 // equivalence class ID because every group ends with a unique index.
114 for (size_t I = Begin; I < Mid; ++I)
115 Chunks[I]->Class[(Cnt + 1) % 2] = Mid;
117 // If we created a group, we need to iterate the main loop again.
125 // Returns true if two sections' associative children are equal.
126 bool ICF::assocEquals(const SectionChunk *A, const SectionChunk *B) {
127 auto ChildClasses = [&](const SectionChunk *SC) {
128 std::vector<uint32_t> Classes;
129 for (const SectionChunk *C : SC->children())
130 if (!C->SectionName.startswith(".debug") &&
131 C->SectionName != ".gfids$y" && C->SectionName != ".gljmp$y")
132 Classes.push_back(C->Class[Cnt % 2]);
135 return ChildClasses(A) == ChildClasses(B);
138 // Compare "non-moving" part of two sections, namely everything
139 // except relocation targets.
140 bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) {
141 if (A->Relocs.size() != B->Relocs.size())
144 // Compare relocations.
145 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
146 if (R1.Type != R2.Type ||
147 R1.VirtualAddress != R2.VirtualAddress) {
150 Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
151 Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
154 if (auto *D1 = dyn_cast<DefinedRegular>(B1))
155 if (auto *D2 = dyn_cast<DefinedRegular>(B2))
156 return D1->getValue() == D2->getValue() &&
157 D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
160 if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
163 // Compare section attributes and contents.
164 return A->getOutputCharacteristics() == B->getOutputCharacteristics() &&
165 A->SectionName == B->SectionName &&
166 A->Header->SizeOfRawData == B->Header->SizeOfRawData &&
167 A->Checksum == B->Checksum && A->getContents() == B->getContents() &&
171 // Compare "moving" part of two sections, namely relocation targets.
172 bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) {
173 // Compare relocations.
174 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
175 Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
176 Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
179 if (auto *D1 = dyn_cast<DefinedRegular>(B1))
180 if (auto *D2 = dyn_cast<DefinedRegular>(B2))
181 return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
184 return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(),
189 // Find the first Chunk after Begin that has a different class from Begin.
190 size_t ICF::findBoundary(size_t Begin, size_t End) {
191 for (size_t I = Begin + 1; I < End; ++I)
192 if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2])
197 void ICF::forEachClassRange(size_t Begin, size_t End,
198 std::function<void(size_t, size_t)> Fn) {
199 while (Begin < End) {
200 size_t Mid = findBoundary(Begin, End);
206 // Call Fn on each class group.
207 void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) {
208 // If the number of sections are too small to use threading,
209 // call Fn sequentially.
210 if (Chunks.size() < 1024) {
211 forEachClassRange(0, Chunks.size(), Fn);
216 // Shard into non-overlapping intervals, and call Fn in parallel.
217 // The sharding must be completed before any calls to Fn are made
218 // so that Fn can modify the Chunks in its shard without causing data
220 const size_t NumShards = 256;
221 size_t Step = Chunks.size() / NumShards;
222 size_t Boundaries[NumShards + 1];
224 Boundaries[NumShards] = Chunks.size();
225 for_each_n(parallel::par, size_t(1), NumShards, [&](size_t I) {
226 Boundaries[I] = findBoundary((I - 1) * Step, Chunks.size());
228 for_each_n(parallel::par, size_t(1), NumShards + 1, [&](size_t I) {
229 if (Boundaries[I - 1] < Boundaries[I]) {
230 forEachClassRange(Boundaries[I - 1], Boundaries[I], Fn);
236 // Merge identical COMDAT sections.
237 // Two sections are considered the same if their section headers,
238 // contents and relocations are all the same.
239 void ICF::run(ArrayRef<Chunk *> Vec) {
240 ScopedTimer T(ICFTimer);
242 // Collect only mergeable sections and group by hash value.
244 for (Chunk *C : Vec) {
245 if (auto *SC = dyn_cast<SectionChunk>(C)) {
247 Chunks.push_back(SC);
249 SC->Class[0] = NextId++;
253 // Make sure that ICF doesn't merge sections that are being handled by string
255 for (auto &P : MergeChunk::Instances)
256 for (SectionChunk *SC : P.second->Sections)
257 SC->Class[0] = NextId++;
259 // Initially, we use hash values to partition sections.
260 for_each(parallel::par, Chunks.begin(), Chunks.end(), [&](SectionChunk *SC) {
261 // Set MSB to 1 to avoid collisions with non-hash classs.
262 SC->Class[0] = xxHash64(SC->getContents()) | (1 << 31);
265 // From now on, sections in Chunks are ordered so that sections in
266 // the same group are consecutive in the vector.
267 std::stable_sort(Chunks.begin(), Chunks.end(),
268 [](SectionChunk *A, SectionChunk *B) {
269 return A->Class[0] < B->Class[0];
272 // Compare static contents and assign unique IDs for each static content.
273 forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
275 // Split groups by comparing relocations until convergence is obtained.
279 [&](size_t Begin, size_t End) { segregate(Begin, End, false); });
282 log("ICF needed " + Twine(Cnt) + " iterations");
284 // Merge sections in the same classs.
285 forEachClass([&](size_t Begin, size_t End) {
286 if (End - Begin == 1)
289 log("Selected " + Chunks[Begin]->getDebugName());
290 for (size_t I = Begin + 1; I < End; ++I) {
291 log(" Removed " + Chunks[I]->getDebugName());
292 Chunks[Begin]->replace(Chunks[I]);
297 // Entry point to ICF.
298 void doICF(ArrayRef<Chunk *> Chunks) { ICF().run(Chunks); }