xref: /llvm-project-15.0.7/lld/MachO/ICF.cpp (revision fb978f09)
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 #include "ICF.h"
10 #include "ConcatOutputSection.h"
11 #include "InputSection.h"
12 #include "Symbols.h"
13 #include "UnwindInfoSection.h"
14 
15 #include "llvm/Support/Parallel.h"
16 #include "llvm/Support/TimeProfiler.h"
17 
18 #include <atomic>
19 
20 using namespace llvm;
21 using namespace lld;
22 using namespace lld::macho;
23 
24 class ICF {
25 public:
26   ICF(std::vector<ConcatInputSection *> &inputs);
27 
28   void run();
29   void segregate(size_t begin, size_t end,
30                  std::function<bool(const ConcatInputSection *,
31                                     const ConcatInputSection *)>
32                      equals);
33   size_t findBoundary(size_t begin, size_t end);
34   void forEachClassRange(size_t begin, size_t end,
35                          std::function<void(size_t, size_t)> func);
36   void forEachClass(std::function<void(size_t, size_t)> func);
37 
38   // ICF needs a copy of the inputs vector because its equivalence-class
39   // segregation algorithm destroys the proper sequence.
40   std::vector<ConcatInputSection *> icfInputs;
41 };
42 
43 ICF::ICF(std::vector<ConcatInputSection *> &inputs) {
44   icfInputs.assign(inputs.begin(), inputs.end());
45 }
46 
47 // ICF = Identical Code Folding
48 //
49 // We only fold __TEXT,__text, so this is really "code" folding, and not
50 // "COMDAT" folding. String and scalar constant literals are deduplicated
51 // elsewhere.
52 //
53 // Summary of segments & sections:
54 //
55 // The __TEXT segment is readonly at the MMU. Some sections are already
56 // deduplicated elsewhere (__TEXT,__cstring & __TEXT,__literal*) and some are
57 // synthetic and inherently free of duplicates (__TEXT,__stubs &
58 // __TEXT,__unwind_info). Note that we don't yet run ICF on __TEXT,__const,
59 // because doing so induces many test failures.
60 //
61 // The __LINKEDIT segment is readonly at the MMU, yet entirely synthetic, and
62 // thus ineligible for ICF.
63 //
64 // The __DATA_CONST segment is read/write at the MMU, but is logically const to
65 // the application after dyld applies fixups to pointer data. We currently
66 // fold only the __DATA_CONST,__cfstring section.
67 //
68 // The __DATA segment is read/write at the MMU, and as application-writeable
69 // data, none of its sections are eligible for ICF.
70 //
71 // Please see the large block comment in lld/ELF/ICF.cpp for an explanation
72 // of the segregation algorithm.
73 //
74 // FIXME(gkm): implement keep-unique attributes
75 // FIXME(gkm): implement address-significance tables for MachO object files
76 
77 static unsigned icfPass = 0;
78 static std::atomic<bool> icfRepeat{false};
79 
80 // Compare everything except the relocation referents
81 static bool equalsConstant(const ConcatInputSection *ia,
82                            const ConcatInputSection *ib) {
83   // We can only fold within the same OutputSection.
84   if (ia->parent != ib->parent)
85     return false;
86   if (ia->data.size() != ib->data.size())
87     return false;
88   if (ia->data != ib->data)
89     return false;
90   if (ia->relocs.size() != ib->relocs.size())
91     return false;
92   auto f = [&](const Reloc &ra, const Reloc &rb) {
93     if (ra.type != rb.type)
94       return false;
95     if (ra.pcrel != rb.pcrel)
96       return false;
97     if (ra.length != rb.length)
98       return false;
99     if (ra.offset != rb.offset)
100       return false;
101     if (ra.addend != rb.addend)
102       return false;
103     if (ra.referent.is<Symbol *>() != rb.referent.is<Symbol *>())
104       return false; // a nice place to breakpoint
105     return true;
106   };
107   return std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(),
108                     f);
109 }
110 
111 // Compare only the relocation referents
112 static bool equalsVariable(const ConcatInputSection *ia,
113                            const ConcatInputSection *ib) {
114   assert(ia->relocs.size() == ib->relocs.size());
115   auto f = [&](const Reloc &ra, const Reloc &rb) {
116     if (ra.referent == rb.referent)
117       return true;
118     if (ra.referent.is<Symbol *>()) {
119       const auto *sa = ra.referent.get<Symbol *>();
120       const auto *sb = rb.referent.get<Symbol *>();
121       if (sa->kind() != sb->kind())
122         return false;
123       if (isa<Defined>(sa)) {
124         const auto *da = dyn_cast<Defined>(sa);
125         const auto *db = dyn_cast<Defined>(sb);
126         if (da->isec && db->isec) {
127           if (da->isec->kind() != db->isec->kind())
128             return false;
129           if (const auto *isecA = dyn_cast<ConcatInputSection>(da->isec)) {
130             const auto *isecB = cast<ConcatInputSection>(db->isec);
131             return da->value == db->value && isecA->icfEqClass[icfPass % 2] ==
132                                                  isecB->icfEqClass[icfPass % 2];
133           }
134           // Else we have two literal sections. References to them are
135           // constant-equal if their offsets in the output section are equal.
136           return da->isec->parent == db->isec->parent &&
137                  da->isec->getOffset(da->value) ==
138                      db->isec->getOffset(db->value);
139         }
140         assert(da->isAbsolute() && db->isAbsolute());
141         return da->value == db->value;
142       } else if (isa<DylibSymbol>(sa)) {
143         // There is one DylibSymbol per gotIndex and we already checked for
144         // symbol equality, thus we know that these must be different.
145         return false;
146       } else {
147         llvm_unreachable("equalsVariable symbol kind");
148       }
149     } else {
150       const auto *sa = ra.referent.get<InputSection *>();
151       const auto *sb = rb.referent.get<InputSection *>();
152       if (sa->kind() != sb->kind())
153         return false;
154       if (const auto *isecA = dyn_cast<ConcatInputSection>(sa)) {
155         const auto *isecB = cast<ConcatInputSection>(sb);
156         return isecA->icfEqClass[icfPass % 2] == isecB->icfEqClass[icfPass % 2];
157       } else {
158         assert(isa<CStringInputSection>(sa) ||
159                isa<WordLiteralInputSection>(sa));
160         return sa->getOffset(ra.addend) == sb->getOffset(rb.addend);
161       }
162     }
163   };
164   return std::equal(ia->relocs.begin(), ia->relocs.end(), ib->relocs.begin(),
165                     f);
166 }
167 
168 // Find the first InputSection after BEGIN whose equivalence class differs
169 size_t ICF::findBoundary(size_t begin, size_t end) {
170   uint64_t beginHash = icfInputs[begin]->icfEqClass[icfPass % 2];
171   for (size_t i = begin + 1; i < end; ++i)
172     if (beginHash != icfInputs[i]->icfEqClass[icfPass % 2])
173       return i;
174   return end;
175 }
176 
177 // Invoke FUNC on subranges with matching equivalence class
178 void ICF::forEachClassRange(size_t begin, size_t end,
179                             std::function<void(size_t, size_t)> func) {
180   while (begin < end) {
181     size_t mid = findBoundary(begin, end);
182     func(begin, mid);
183     begin = mid;
184   }
185 }
186 
187 // Split icfInputs into shards, then parallelize invocation of FUNC on subranges
188 // with matching equivalence class
189 void ICF::forEachClass(std::function<void(size_t, size_t)> func) {
190   // Only use threads when the benefits outweigh the overhead.
191   const size_t threadingThreshold = 1024;
192   if (icfInputs.size() < threadingThreshold) {
193     forEachClassRange(0, icfInputs.size(), func);
194     ++icfPass;
195     return;
196   }
197 
198   // Shard into non-overlapping intervals, and call FUNC in parallel.  The
199   // sharding must be completed before any calls to FUNC are made so that FUNC
200   // can modify the InputSection in its shard without causing data races.
201   const size_t shards = 256;
202   size_t step = icfInputs.size() / shards;
203   size_t boundaries[shards + 1];
204   boundaries[0] = 0;
205   boundaries[shards] = icfInputs.size();
206   parallelForEachN(1, shards, [&](size_t i) {
207     boundaries[i] = findBoundary((i - 1) * step, icfInputs.size());
208   });
209   parallelForEachN(1, shards + 1, [&](size_t i) {
210     if (boundaries[i - 1] < boundaries[i]) {
211       forEachClassRange(boundaries[i - 1], boundaries[i], func);
212     }
213   });
214   ++icfPass;
215 }
216 
217 void ICF::run() {
218   // Into each origin-section hash, combine all reloc referent section hashes.
219   for (icfPass = 0; icfPass < 2; ++icfPass) {
220     parallelForEach(icfInputs, [&](ConcatInputSection *isec) {
221       uint64_t hash = isec->icfEqClass[icfPass % 2];
222       for (const Reloc &r : isec->relocs) {
223         if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
224           if (auto *dylibSym = dyn_cast<DylibSymbol>(sym))
225             hash += dylibSym->stubsHelperIndex;
226           else if (auto *defined = dyn_cast<Defined>(sym)) {
227             if (defined->isec) {
228               if (auto isec = dyn_cast<ConcatInputSection>(defined->isec))
229                 hash += defined->value + isec->icfEqClass[icfPass % 2];
230               else
231                 hash += defined->isec->kind() +
232                         defined->isec->getOffset(defined->value);
233             } else {
234               hash += defined->value;
235             }
236           } else
237             llvm_unreachable("foldIdenticalSections symbol kind");
238         }
239       }
240       // Set MSB to 1 to avoid collisions with non-hashed classes.
241       isec->icfEqClass[(icfPass + 1) % 2] = hash | (1ull << 63);
242     });
243   }
244 
245   llvm::stable_sort(
246       icfInputs, [](const ConcatInputSection *a, const ConcatInputSection *b) {
247         return a->icfEqClass[0] < b->icfEqClass[0];
248       });
249   forEachClass(
250       [&](size_t begin, size_t end) { segregate(begin, end, equalsConstant); });
251 
252   // Split equivalence groups by comparing relocations until convergence
253   do {
254     icfRepeat = false;
255     forEachClass([&](size_t begin, size_t end) {
256       segregate(begin, end, equalsVariable);
257     });
258   } while (icfRepeat);
259   log("ICF needed " + Twine(icfPass) + " iterations");
260 
261   // Fold sections within equivalence classes
262   forEachClass([&](size_t begin, size_t end) {
263     if (end - begin < 2)
264       return;
265     ConcatInputSection *beginIsec = icfInputs[begin];
266     for (size_t i = begin + 1; i < end; ++i)
267       beginIsec->foldIdentical(icfInputs[i]);
268   });
269 }
270 
271 // Split an equivalence class into smaller classes.
272 void ICF::segregate(
273     size_t begin, size_t end,
274     std::function<bool(const ConcatInputSection *, const ConcatInputSection *)>
275         equals) {
276   while (begin < end) {
277     // Divide [begin, end) into two. Let mid be the start index of the
278     // second group.
279     auto bound = std::stable_partition(icfInputs.begin() + begin + 1,
280                                        icfInputs.begin() + end,
281                                        [&](ConcatInputSection *isec) {
282                                          return equals(icfInputs[begin], isec);
283                                        });
284     size_t mid = bound - icfInputs.begin();
285 
286     // Split [begin, end) into [begin, mid) and [mid, end). We use mid as an
287     // equivalence class ID because every group ends with a unique index.
288     for (size_t i = begin; i < mid; ++i)
289       icfInputs[i]->icfEqClass[(icfPass + 1) % 2] = mid;
290 
291     // If we created a group, we need to iterate the main loop again.
292     if (mid != end)
293       icfRepeat = true;
294 
295     begin = mid;
296   }
297 }
298 
299 template <class Ptr>
300 DenseSet<const InputSection *> findFunctionsWithUnwindInfo() {
301   DenseSet<const InputSection *> result;
302   for (ConcatInputSection *isec : in.unwindInfo->getInputs()) {
303     for (size_t i = 0; i < isec->relocs.size(); ++i) {
304       Reloc &r = isec->relocs[i];
305       assert(target->hasAttr(r.type, RelocAttrBits::UNSIGNED));
306       if (r.offset % sizeof(CompactUnwindEntry<Ptr>) !=
307           offsetof(CompactUnwindEntry<Ptr>, functionAddress))
308         continue;
309       result.insert(r.referent.get<InputSection *>());
310     }
311   }
312   return result;
313 }
314 
315 void macho::foldIdenticalSections() {
316   TimeTraceScope timeScope("Fold Identical Code Sections");
317   // The ICF equivalence-class segregation algorithm relies on pre-computed
318   // hashes of InputSection::data for the ConcatOutputSection::inputs and all
319   // sections referenced by their relocs. We could recursively traverse the
320   // relocs to find every referenced InputSection, but that precludes easy
321   // parallelization. Therefore, we hash every InputSection here where we have
322   // them all accessible as simple vectors.
323 
324   // ICF can't fold functions with unwind info
325   DenseSet<const InputSection *> functionsWithUnwindInfo =
326       target->wordSize == 8 ? findFunctionsWithUnwindInfo<uint64_t>()
327                             : findFunctionsWithUnwindInfo<uint32_t>();
328 
329   // If an InputSection is ineligible for ICF, we give it a unique ID to force
330   // it into an unfoldable singleton equivalence class.  Begin the unique-ID
331   // space at inputSections.size(), so that it will never intersect with
332   // equivalence-class IDs which begin at 0. Since hashes & unique IDs never
333   // coexist with equivalence-class IDs, this is not necessary, but might help
334   // someone keep the numbers straight in case we ever need to debug the
335   // ICF::segregate()
336   std::vector<ConcatInputSection *> hashable;
337   uint64_t icfUniqueID = inputSections.size();
338   for (ConcatInputSection *isec : inputSections) {
339     // FIXME: consider non-code __text sections as hashable?
340     bool isHashable = (isCodeSection(isec) || isCfStringSection(isec)) &&
341                       !isec->shouldOmitFromOutput() &&
342                       !functionsWithUnwindInfo.contains(isec) &&
343                       isec->isHashableForICF();
344     if (isHashable)
345       hashable.push_back(isec);
346     else
347       isec->icfEqClass[0] = ++icfUniqueID;
348   }
349   parallelForEach(hashable,
350                   [](ConcatInputSection *isec) { isec->hashForICF(); });
351   // Now that every input section is either hashed or marked as unique, run the
352   // segregation algorithm to detect foldable subsections.
353   ICF(hashable).run();
354 }
355