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/Core/Parallel.h"
25 #include "llvm/ADT/Hashing.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
39 void run(const std::vector<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<uint32_t> NextId = {1};
60 std::atomic<bool> Repeat = {false};
63 // Returns a hash value for S.
64 uint32_t ICF::getHash(SectionChunk *C) {
65 return hash_combine(C->getPermissions(),
66 hash_value(C->SectionName),
69 uint32_t(C->Header->SizeOfRawData),
73 // Returns true if section S is subject of ICF.
75 // Microsoft's documentation
76 // (https://msdn.microsoft.com/en-us/library/bxwfs976.aspx; visited April
77 // 2017) says that /opt:icf folds both functions and read-only data.
78 // Despite that, the MSVC linker folds only functions. We found
79 // a few instances of programs that are not safe for data merging.
80 // Therefore, we merge only functions just like the MSVC tool.
81 bool ICF::isEligible(SectionChunk *C) {
82 bool Global = C->Sym && C->Sym->isExternal();
83 bool Executable = C->getPermissions() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE;
84 bool Writable = C->getPermissions() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
85 return C->isCOMDAT() && C->isLive() && Global && Executable && !Writable;
88 // Split an equivalence class into smaller classes.
89 void ICF::segregate(size_t Begin, size_t End, bool Constant) {
91 // Divide [Begin, End) into two. Let Mid be the start index of the
93 auto Bound = std::stable_partition(
94 Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
96 return equalsConstant(Chunks[Begin], S);
97 return equalsVariable(Chunks[Begin], S);
99 size_t Mid = Bound - Chunks.begin();
101 // Split [Begin, End) into [Begin, Mid) and [Mid, End).
102 uint32_t Id = NextId++;
103 for (size_t I = Begin; I < Mid; ++I)
104 Chunks[I]->Class[(Cnt + 1) % 2] = Id;
106 // If we created a group, we need to iterate the main loop again.
114 // Compare "non-moving" part of two sections, namely everything
115 // except relocation targets.
116 bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) {
117 if (A->NumRelocs != B->NumRelocs)
120 // Compare relocations.
121 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
122 if (R1.Type != R2.Type ||
123 R1.VirtualAddress != R2.VirtualAddress) {
126 SymbolBody *B1 = A->File->getSymbolBody(R1.SymbolTableIndex);
127 SymbolBody *B2 = B->File->getSymbolBody(R2.SymbolTableIndex);
130 if (auto *D1 = dyn_cast<DefinedRegular>(B1))
131 if (auto *D2 = dyn_cast<DefinedRegular>(B2))
132 return D1->getValue() == D2->getValue() &&
133 D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
136 if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
139 // Compare section attributes and contents.
140 return A->getPermissions() == B->getPermissions() &&
141 A->SectionName == B->SectionName &&
142 A->getAlign() == B->getAlign() &&
143 A->Header->SizeOfRawData == B->Header->SizeOfRawData &&
144 A->Checksum == B->Checksum &&
145 A->getContents() == B->getContents();
148 // Compare "moving" part of two sections, namely relocation targets.
149 bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) {
150 // Compare relocations.
151 auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
152 SymbolBody *B1 = A->File->getSymbolBody(R1.SymbolTableIndex);
153 SymbolBody *B2 = B->File->getSymbolBody(R2.SymbolTableIndex);
156 if (auto *D1 = dyn_cast<DefinedRegular>(B1))
157 if (auto *D2 = dyn_cast<DefinedRegular>(B2))
158 return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
161 return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq);
164 size_t ICF::findBoundary(size_t Begin, size_t End) {
165 for (size_t I = Begin + 1; I < End; ++I)
166 if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2])
171 void ICF::forEachClassRange(size_t Begin, size_t End,
172 std::function<void(size_t, size_t)> Fn) {
174 Begin = findBoundary(Begin - 1, End);
176 while (Begin < End) {
177 size_t Mid = findBoundary(Begin, Chunks.size());
183 // Call Fn on each class group.
184 void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) {
185 // If the number of sections are too small to use threading,
186 // call Fn sequentially.
187 if (Chunks.size() < 1024) {
188 forEachClassRange(0, Chunks.size(), Fn);
192 // Split sections into 256 shards and call Fn in parallel.
193 size_t NumShards = 256;
194 size_t Step = Chunks.size() / NumShards;
195 parallel_for(size_t(0), NumShards, [&](size_t I) {
196 forEachClassRange(I * Step, (I + 1) * Step, Fn);
198 forEachClassRange(Step * NumShards, Chunks.size(), Fn);
201 // Merge identical COMDAT sections.
202 // Two sections are considered the same if their section headers,
203 // contents and relocations are all the same.
204 void ICF::run(const std::vector<Chunk *> &Vec) {
205 // Collect only mergeable sections and group by hash value.
206 for (Chunk *C : Vec) {
207 auto *SC = dyn_cast<SectionChunk>(C);
211 if (isEligible(SC)) {
212 // Set MSB to 1 to avoid collisions with non-hash classs.
213 SC->Class[0] = getHash(SC) | (1 << 31);
214 Chunks.push_back(SC);
216 SC->Class[0] = NextId++;
223 // From now on, sections in Chunks are ordered so that sections in
224 // the same group are consecutive in the vector.
225 std::stable_sort(Chunks.begin(), Chunks.end(),
226 [](SectionChunk *A, SectionChunk *B) {
227 return A->Class[0] < B->Class[0];
230 // Compare static contents and assign unique IDs for each static content.
231 forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
234 // Split groups by comparing relocations until convergence is obtained.
238 [&](size_t Begin, size_t End) { segregate(Begin, End, false); });
242 log("ICF needed " + Twine(Cnt) + " iterations");
244 // Merge sections in the same classs.
245 forEachClass([&](size_t Begin, size_t End) {
246 if (End - Begin == 1)
249 log("Selected " + Chunks[Begin]->getDebugName());
250 for (size_t I = Begin + 1; I < End; ++I) {
251 log(" Removed " + Chunks[I]->getDebugName());
252 Chunks[Begin]->replace(Chunks[I]);
257 // Entry point to ICF.
258 void doICF(const std::vector<Chunk *> &Chunks) { ICF().run(Chunks); }