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 algorithm.
17//
18//===----------------------------------------------------------------------===//
19
20#include "ICF.h"
21#include "COFFLinkerContext.h"
22#include "Chunks.h"
23#include "Symbols.h"
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"
31#include <algorithm>
32#include <atomic>
33#include <vector>
34
35using namespace llvm;
36
37namespace lld::coff {
38
39class ICF {
40public:
41  ICF(COFFLinkerContext &c) : ctx(c){};
42  void run();
43
44private:
45  void segregate(size_t begin, size_t end, bool constant);
46
47  bool assocEquals(const SectionChunk *a, const SectionChunk *b);
48
49  bool equalsConstant(const SectionChunk *a, const SectionChunk *b);
50  bool equalsVariable(const SectionChunk *a, const SectionChunk *b);
51
52  bool isEligible(SectionChunk *c);
53
54  size_t findBoundary(size_t begin, size_t end);
55
56  void forEachClassRange(size_t begin, size_t end,
57                         std::function<void(size_t, size_t)> fn);
58
59  void forEachClass(std::function<void(size_t, size_t)> fn);
60
61  std::vector<SectionChunk *> chunks;
62  int cnt = 0;
63  std::atomic<bool> repeat = {false};
64
65  COFFLinkerContext &ctx;
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.
79bool ICF::isEligible(SectionChunk *c) {
80  // Non-comdat chunks, dead chunks, and writable chunks are not eligible.
81  bool writable = c->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
82  if (!c->isCOMDAT() || !c->live || writable)
83    return false;
84
85  // Under regular (not safe) ICF, all code sections are eligible.
86  if ((ctx.config.doICF == ICFLevel::All) &&
87      c->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
88    return true;
89
90  // .pdata and .xdata unwind info sections are eligible.
91  StringRef outSecName = c->getSectionName().split('$').first;
92  if (outSecName == ".pdata" || outSecName == ".xdata")
93    return true;
94
95  // So are vtables.
96  if (c->sym && c->sym->getName().startswith("??_7"))
97    return true;
98
99  // Anything else not in an address-significance table is eligible.
100  return !c->keepUnique;
101}
102
103// Split an equivalence class into smaller classes.
104void ICF::segregate(size_t begin, size_t end, bool constant) {
105  while (begin < end) {
106    // Divide [Begin, End) into two. Let Mid be the start index of the
107    // second group.
108    auto bound = std::stable_partition(
109        chunks.begin() + begin + 1, chunks.begin() + end, [&](SectionChunk *s) {
110          if (constant)
111            return equalsConstant(chunks[begin], s);
112          return equalsVariable(chunks[begin], s);
113        });
114    size_t mid = bound - chunks.begin();
115
116    // Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
117    // equivalence class ID because every group ends with a unique index.
118    for (size_t i = begin; i < mid; ++i)
119      chunks[i]->eqClass[(cnt + 1) % 2] = mid;
120
121    // If we created a group, we need to iterate the main loop again.
122    if (mid != end)
123      repeat = true;
124
125    begin = mid;
126  }
127}
128
129// Returns true if two sections' associative children are equal.
130bool ICF::assocEquals(const SectionChunk *a, const SectionChunk *b) {
131  // Ignore associated metadata sections that don't participate in ICF, such as
132  // debug info and CFGuard metadata.
133  auto considerForICF = [](const SectionChunk &assoc) {
134    StringRef Name = assoc.getSectionName();
135    return !(Name.startswith(".debug") || Name == ".gfids$y" ||
136             Name == ".giats$y" || Name == ".gljmp$y");
137  };
138  auto ra = make_filter_range(a->children(), considerForICF);
139  auto rb = make_filter_range(b->children(), considerForICF);
140  return std::equal(ra.begin(), ra.end(), rb.begin(), rb.end(),
141                    [&](const SectionChunk &ia, const SectionChunk &ib) {
142                      return ia.eqClass[cnt % 2] == ib.eqClass[cnt % 2];
143                    });
144}
145
146// Compare "non-moving" part of two sections, namely everything
147// except relocation targets.
148bool ICF::equalsConstant(const SectionChunk *a, const SectionChunk *b) {
149  if (a->relocsSize != b->relocsSize)
150    return false;
151
152  // Compare relocations.
153  auto eq = [&](const coff_relocation &r1, const coff_relocation &r2) {
154    if (r1.Type != r2.Type ||
155        r1.VirtualAddress != r2.VirtualAddress) {
156      return false;
157    }
158    Symbol *b1 = a->file->getSymbol(r1.SymbolTableIndex);
159    Symbol *b2 = b->file->getSymbol(r2.SymbolTableIndex);
160    if (b1 == b2)
161      return true;
162    if (auto *d1 = dyn_cast<DefinedRegular>(b1))
163      if (auto *d2 = dyn_cast<DefinedRegular>(b2))
164        return d1->getValue() == d2->getValue() &&
165               d1->getChunk()->eqClass[cnt % 2] == d2->getChunk()->eqClass[cnt % 2];
166    return false;
167  };
168  if (!std::equal(a->getRelocs().begin(), a->getRelocs().end(),
169                  b->getRelocs().begin(), eq))
170    return false;
171
172  // Compare section attributes and contents.
173  return a->getOutputCharacteristics() == b->getOutputCharacteristics() &&
174         a->getSectionName() == b->getSectionName() &&
175         a->header->SizeOfRawData == b->header->SizeOfRawData &&
176         a->checksum == b->checksum && a->getContents() == b->getContents() &&
177         assocEquals(a, b);
178}
179
180// Compare "moving" part of two sections, namely relocation targets.
181bool ICF::equalsVariable(const SectionChunk *a, const SectionChunk *b) {
182  // Compare relocations.
183  auto eq = [&](const coff_relocation &r1, const coff_relocation &r2) {
184    Symbol *b1 = a->file->getSymbol(r1.SymbolTableIndex);
185    Symbol *b2 = b->file->getSymbol(r2.SymbolTableIndex);
186    if (b1 == b2)
187      return true;
188    if (auto *d1 = dyn_cast<DefinedRegular>(b1))
189      if (auto *d2 = dyn_cast<DefinedRegular>(b2))
190        return d1->getChunk()->eqClass[cnt % 2] == d2->getChunk()->eqClass[cnt % 2];
191    return false;
192  };
193  return std::equal(a->getRelocs().begin(), a->getRelocs().end(),
194                    b->getRelocs().begin(), eq) &&
195         assocEquals(a, b);
196}
197
198// Find the first Chunk after Begin that has a different class from Begin.
199size_t ICF::findBoundary(size_t begin, size_t end) {
200  for (size_t i = begin + 1; i < end; ++i)
201    if (chunks[begin]->eqClass[cnt % 2] != chunks[i]->eqClass[cnt % 2])
202      return i;
203  return end;
204}
205
206void ICF::forEachClassRange(size_t begin, size_t end,
207                            std::function<void(size_t, size_t)> fn) {
208  while (begin < end) {
209    size_t mid = findBoundary(begin, end);
210    fn(begin, mid);
211    begin = mid;
212  }
213}
214
215// Call Fn on each class group.
216void ICF::forEachClass(std::function<void(size_t, size_t)> fn) {
217  // If the number of sections are too small to use threading,
218  // call Fn sequentially.
219  if (chunks.size() < 1024) {
220    forEachClassRange(0, chunks.size(), fn);
221    ++cnt;
222    return;
223  }
224
225  // Shard into non-overlapping intervals, and call Fn in parallel.
226  // The sharding must be completed before any calls to Fn are made
227  // so that Fn can modify the Chunks in its shard without causing data
228  // races.
229  const size_t numShards = 256;
230  size_t step = chunks.size() / numShards;
231  size_t boundaries[numShards + 1];
232  boundaries[0] = 0;
233  boundaries[numShards] = chunks.size();
234  parallelFor(1, numShards, [&](size_t i) {
235    boundaries[i] = findBoundary((i - 1) * step, chunks.size());
236  });
237  parallelFor(1, numShards + 1, [&](size_t i) {
238    if (boundaries[i - 1] < boundaries[i]) {
239      forEachClassRange(boundaries[i - 1], boundaries[i], fn);
240    }
241  });
242  ++cnt;
243}
244
245// Merge identical COMDAT sections.
246// Two sections are considered the same if their section headers,
247// contents and relocations are all the same.
248void ICF::run() {
249  ScopedTimer t(ctx.icfTimer);
250
251  // Collect only mergeable sections and group by hash value.
252  uint32_t nextId = 1;
253  for (Chunk *c : ctx.symtab.getChunks()) {
254    if (auto *sc = dyn_cast<SectionChunk>(c)) {
255      if (isEligible(sc))
256        chunks.push_back(sc);
257      else
258        sc->eqClass[0] = nextId++;
259    }
260  }
261
262  // Make sure that ICF doesn't merge sections that are being handled by string
263  // tail merging.
264  for (MergeChunk *mc : ctx.mergeChunkInstances)
265    if (mc)
266      for (SectionChunk *sc : mc->sections)
267        sc->eqClass[0] = nextId++;
268
269  // Initially, we use hash values to partition sections.
270  parallelForEach(chunks, [&](SectionChunk *sc) {
271    sc->eqClass[0] = xxHash64(sc->getContents());
272  });
273
274  // Combine the hashes of the sections referenced by each section into its
275  // hash.
276  for (unsigned cnt = 0; cnt != 2; ++cnt) {
277    parallelForEach(chunks, [&](SectionChunk *sc) {
278      uint32_t hash = sc->eqClass[cnt % 2];
279      for (Symbol *b : sc->symbols())
280        if (auto *sym = dyn_cast_or_null<DefinedRegular>(b))
281          hash += sym->getChunk()->eqClass[cnt % 2];
282      // Set MSB to 1 to avoid collisions with non-hash classes.
283      sc->eqClass[(cnt + 1) % 2] = hash | (1U << 31);
284    });
285  }
286
287  // From now on, sections in Chunks are ordered so that sections in
288  // the same group are consecutive in the vector.
289  llvm::stable_sort(chunks, [](const SectionChunk *a, const SectionChunk *b) {
290    return a->eqClass[0] < b->eqClass[0];
291  });
292
293  // Compare static contents and assign unique IDs for each static content.
294  forEachClass([&](size_t begin, size_t end) { segregate(begin, end, true); });
295
296  // Split groups by comparing relocations until convergence is obtained.
297  do {
298    repeat = false;
299    forEachClass(
300        [&](size_t begin, size_t end) { segregate(begin, end, false); });
301  } while (repeat);
302
303  log("ICF needed " + Twine(cnt) + " iterations");
304
305  // Merge sections in the same classes.
306  forEachClass([&](size_t begin, size_t end) {
307    if (end - begin == 1)
308      return;
309
310    log("Selected " + chunks[begin]->getDebugName());
311    for (size_t i = begin + 1; i < end; ++i) {
312      log("  Removed " + chunks[i]->getDebugName());
313      chunks[begin]->replace(chunks[i]);
314    }
315  });
316}
317
318// Entry point to ICF.
319void doICF(COFFLinkerContext &ctx) { ICF(ctx).run(); }
320
321} // namespace lld::coff
322