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 //===----------------------------------------------------------------------===//
23 #include "lld/Common/ErrorHandler.h"
24 #include "llvm/ADT/Hashing.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Parallel.h"
27 #include "llvm/Support/raw_ostream.h"
39 void run(ArrayRef<Chunk *> V);
42 void segregate(size_t Begin, size_t End, bool Constant);
44 bool equalsConstant(const SectionChunk *A, const SectionChunk *B);
45 bool equalsVariable(const SectionChunk *A, const SectionChunk *B);
47 uint32_t getHash(SectionChunk *C);
48 bool isEligible(SectionChunk *C);
50 size_t findBoundary(size_t Begin, size_t End);
52 void forEachClassRange(size_t Begin, size_t End,
53 std::function<void(size_t, size_t)> Fn);
55 void forEachClass(std::function<void(size_t, size_t)> Fn);
57 std::vector<SectionChunk *> Chunks;
59 std::atomic<bool> Repeat = {false};
62 // Returns a hash value for S.
63 uint32_t ICF::getHash(SectionChunk *C) {
64 return hash_combine(C->getPermissions(), C->SectionName, C->NumRelocs,
65 C->Alignment, uint32_t(C->Header->SizeOfRawData),
66 C->Checksum, C->getContents());
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 merge
77 // identical .xdata sections, because the address of unwind information is
78 // insignificant to the user program and the Visual C++ linker does this.
79 bool ICF::isEligible(SectionChunk *C) {
80 // Non-comdat chunks, dead chunks, and writable chunks are not elegible.
81 bool Writable = C->getPermissions() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
82 if (!C->isCOMDAT() || !C->isLive() || Writable)
85 // Code sections are eligible.
86 if (C->getPermissions() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
89 // .xdata unwind info sections are eligble.
90 return C->getSectionName().split('$').first == ".xdata";
93 // Split an equivalence class into smaller classes.
94 void ICF::segregate(size_t Begin, size_t End, bool Constant) {
96 // Divide [Begin, End) into two. Let Mid be the start index of the
98 auto Bound = std::stable_partition(
99 Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
101 return equalsConstant(Chunks[Begin], S);
102 return equalsVariable(Chunks[Begin], S);
104 size_t Mid = Bound - Chunks.begin();
106 // Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
107 // equivalence class ID because every group ends with a unique index.
108 for (size_t I = Begin; I < Mid; ++I)
109 Chunks[I]->Class[(Cnt + 1) % 2] = Mid;
111 // If we created a group, we need to iterate the main loop again.
119 // Compare "non-moving" part of two sections, namely everything
120 // except relocation targets.
121 bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) {
122 if (A->NumRelocs != B->NumRelocs)
125 // Compare relocations.
126 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
127 if (R1.Type != R2.Type ||
128 R1.VirtualAddress != R2.VirtualAddress) {
131 Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
132 Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
135 if (auto *D1 = dyn_cast<DefinedRegular>(B1))
136 if (auto *D2 = dyn_cast<DefinedRegular>(B2))
137 return D1->getValue() == D2->getValue() &&
138 D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
141 if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
144 // Compare section attributes and contents.
145 return A->getPermissions() == B->getPermissions() &&
146 A->SectionName == B->SectionName && A->Alignment == B->Alignment &&
147 A->Header->SizeOfRawData == B->Header->SizeOfRawData &&
148 A->Checksum == B->Checksum && A->getContents() == B->getContents();
151 // Compare "moving" part of two sections, namely relocation targets.
152 bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) {
153 // Compare relocations.
154 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
155 Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
156 Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
159 if (auto *D1 = dyn_cast<DefinedRegular>(B1))
160 if (auto *D2 = dyn_cast<DefinedRegular>(B2))
161 return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
164 return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq);
167 size_t ICF::findBoundary(size_t Begin, size_t End) {
168 for (size_t I = Begin + 1; I < End; ++I)
169 if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2])
174 void ICF::forEachClassRange(size_t Begin, size_t End,
175 std::function<void(size_t, size_t)> Fn) {
177 Begin = findBoundary(Begin - 1, End);
179 while (Begin < End) {
180 size_t Mid = findBoundary(Begin, Chunks.size());
186 // Call Fn on each class group.
187 void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) {
188 // If the number of sections are too small to use threading,
189 // call Fn sequentially.
190 if (Chunks.size() < 1024) {
191 forEachClassRange(0, Chunks.size(), Fn);
196 // Split sections into 256 shards and call Fn in parallel.
197 size_t NumShards = 256;
198 size_t Step = Chunks.size() / NumShards;
199 for_each_n(parallel::par, size_t(0), NumShards, [&](size_t I) {
200 size_t End = (I == NumShards - 1) ? Chunks.size() : (I + 1) * Step;
201 forEachClassRange(I * Step, End, Fn);
206 // Merge identical COMDAT sections.
207 // Two sections are considered the same if their section headers,
208 // contents and relocations are all the same.
209 void ICF::run(ArrayRef<Chunk *> Vec) {
210 // Collect only mergeable sections and group by hash value.
212 for (Chunk *C : Vec) {
213 if (auto *SC = dyn_cast<SectionChunk>(C)) {
215 Chunks.push_back(SC);
217 SC->Class[0] = NextId++;
221 // Initially, we use hash values to partition sections.
222 for_each(parallel::par, Chunks.begin(), Chunks.end(), [&](SectionChunk *SC) {
223 // Set MSB to 1 to avoid collisions with non-hash classs.
224 SC->Class[0] = getHash(SC) | (1 << 31);
227 // From now on, sections in Chunks are ordered so that sections in
228 // the same group are consecutive in the vector.
229 std::stable_sort(Chunks.begin(), Chunks.end(),
230 [](SectionChunk *A, SectionChunk *B) {
231 return A->Class[0] < B->Class[0];
234 // Compare static contents and assign unique IDs for each static content.
235 forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
237 // Split groups by comparing relocations until convergence is obtained.
241 [&](size_t Begin, size_t End) { segregate(Begin, End, false); });
244 log("ICF needed " + Twine(Cnt) + " iterations");
246 // Merge sections in the same classs.
247 forEachClass([&](size_t Begin, size_t End) {
248 if (End - Begin == 1)
251 log("Selected " + Chunks[Begin]->getDebugName());
252 for (size_t I = Begin + 1; I < End; ++I) {
253 log(" Removed " + Chunks[I]->getDebugName());
254 Chunks[Begin]->replace(Chunks[I]);
259 // Entry point to ICF.
260 void doICF(ArrayRef<Chunk *> Chunks) { ICF().run(Chunks); }