]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - COFF/ICF.cpp
Vendor import of lld trunk r302418:
[FreeBSD/FreeBSD.git] / COFF / ICF.cpp
1 //===- ICF.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
13 // by a few percent.
14 //
15 // On Windows, ICF is enabled by default.
16 //
17 // See ELF/ICF.cpp for the details about the algortihm.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "Chunks.h"
22 #include "Error.h"
23 #include "Symbols.h"
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"
28 #include <algorithm>
29 #include <atomic>
30 #include <vector>
31
32 using namespace llvm;
33
34 namespace lld {
35 namespace coff {
36
37 class ICF {
38 public:
39   void run(const std::vector<Chunk *> &V);
40
41 private:
42   void segregate(size_t Begin, size_t End, bool Constant);
43
44   bool equalsConstant(const SectionChunk *A, const SectionChunk *B);
45   bool equalsVariable(const SectionChunk *A, const SectionChunk *B);
46
47   uint32_t getHash(SectionChunk *C);
48   bool isEligible(SectionChunk *C);
49
50   size_t findBoundary(size_t Begin, size_t End);
51
52   void forEachClassRange(size_t Begin, size_t End,
53                          std::function<void(size_t, size_t)> Fn);
54
55   void forEachClass(std::function<void(size_t, size_t)> Fn);
56
57   std::vector<SectionChunk *> Chunks;
58   int Cnt = 0;
59   std::atomic<uint32_t> NextId = {1};
60   std::atomic<bool> Repeat = {false};
61 };
62
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),
67                       C->NumRelocs,
68                       C->getAlign(),
69                       uint32_t(C->Header->SizeOfRawData),
70                       C->Checksum);
71 }
72
73 // Returns true if section S is subject of ICF.
74 //
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;
86 }
87
88 // Split an equivalence class into smaller classes.
89 void ICF::segregate(size_t Begin, size_t End, bool Constant) {
90   while (Begin < End) {
91     // Divide [Begin, End) into two. Let Mid be the start index of the
92     // second group.
93     auto Bound = std::stable_partition(
94         Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
95           if (Constant)
96             return equalsConstant(Chunks[Begin], S);
97           return equalsVariable(Chunks[Begin], S);
98         });
99     size_t Mid = Bound - Chunks.begin();
100
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;
105
106     // If we created a group, we need to iterate the main loop again.
107     if (Mid != End)
108       Repeat = true;
109
110     Begin = Mid;
111   }
112 }
113
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)
118     return false;
119
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) {
124       return false;
125     }
126     SymbolBody *B1 = A->File->getSymbolBody(R1.SymbolTableIndex);
127     SymbolBody *B2 = B->File->getSymbolBody(R2.SymbolTableIndex);
128     if (B1 == B2)
129       return true;
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];
134     return false;
135   };
136   if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
137     return false;
138
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();
146 }
147
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);
154     if (B1 == B2)
155       return true;
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];
159     return false;
160   };
161   return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq);
162 }
163
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])
167       return I;
168   return End;
169 }
170
171 void ICF::forEachClassRange(size_t Begin, size_t End,
172                             std::function<void(size_t, size_t)> Fn) {
173   if (Begin > 0)
174     Begin = findBoundary(Begin - 1, End);
175
176   while (Begin < End) {
177     size_t Mid = findBoundary(Begin, Chunks.size());
178     Fn(Begin, Mid);
179     Begin = Mid;
180   }
181 }
182
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);
189     return;
190   }
191
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);
197   });
198   forEachClassRange(Step * NumShards, Chunks.size(), Fn);
199 }
200
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);
208     if (!SC)
209       continue;
210
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);
215     } else {
216       SC->Class[0] = NextId++;
217     }
218   }
219
220   if (Chunks.empty())
221     return;
222
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];
228                    });
229
230   // Compare static contents and assign unique IDs for each static content.
231   forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
232   ++Cnt;
233
234   // Split groups by comparing relocations until convergence is obtained.
235   do {
236     Repeat = false;
237     forEachClass(
238         [&](size_t Begin, size_t End) { segregate(Begin, End, false); });
239     ++Cnt;
240   } while (Repeat);
241
242   log("ICF needed " + Twine(Cnt) + " iterations");
243
244   // Merge sections in the same classs.
245   forEachClass([&](size_t Begin, size_t End) {
246     if (End - Begin == 1)
247       return;
248
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]);
253     }
254   });
255 }
256
257 // Entry point to ICF.
258 void doICF(const std::vector<Chunk *> &Chunks) { ICF().run(Chunks); }
259
260 } // namespace coff
261 } // namespace lld