Coverage Report

Created: 2019-05-19 14:56

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/lib/ReaderWriter/MachO/CompactUnwindPass.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/ReaderWriter/MachO/CompactUnwindPass.cpp -------------*- C++ -*-===//
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
/// \file A pass to convert MachO's __compact_unwind sections into the final
10
/// __unwind_info format used during runtime. See
11
/// mach-o/compact_unwind_encoding.h for more details on the formats involved.
12
///
13
//===----------------------------------------------------------------------===//
14
15
#include "ArchHandler.h"
16
#include "File.h"
17
#include "MachONormalizedFileBinaryUtils.h"
18
#include "MachOPasses.h"
19
#include "lld/Common/LLVM.h"
20
#include "lld/Core/DefinedAtom.h"
21
#include "lld/Core/File.h"
22
#include "lld/Core/Reference.h"
23
#include "lld/Core/Simple.h"
24
#include "llvm/ADT/DenseMap.h"
25
#include "llvm/Support/Debug.h"
26
#include "llvm/Support/Format.h"
27
28
#define DEBUG_TYPE "macho-compact-unwind"
29
30
namespace lld {
31
namespace mach_o {
32
33
namespace {
34
struct CompactUnwindEntry {
35
  const Atom *rangeStart;
36
  const Atom *personalityFunction;
37
  const Atom *lsdaLocation;
38
  const Atom *ehFrame;
39
40
  uint32_t rangeLength;
41
42
  // There are 3 types of compact unwind entry, distinguished by the encoding
43
  // value: 0 indicates a function with no unwind info;
44
  // _archHandler.dwarfCompactUnwindType() indicates that the entry defers to
45
  // __eh_frame, and that the ehFrame entry will be valid; any other value is a
46
  // real compact unwind entry -- personalityFunction will be set and
47
  // lsdaLocation may be.
48
  uint32_t encoding;
49
50
  CompactUnwindEntry(const DefinedAtom *function)
51
      : rangeStart(function), personalityFunction(nullptr),
52
        lsdaLocation(nullptr), ehFrame(nullptr), rangeLength(function->size()),
53
0
        encoding(0) {}
54
55
  CompactUnwindEntry()
56
      : rangeStart(nullptr), personalityFunction(nullptr),
57
40
        lsdaLocation(nullptr), ehFrame(nullptr), rangeLength(0), encoding(0) {}
58
};
59
60
struct UnwindInfoPage {
61
  ArrayRef<CompactUnwindEntry> entries;
62
};
63
}
64
65
class UnwindInfoAtom : public SimpleDefinedAtom {
66
public:
67
  UnwindInfoAtom(ArchHandler &archHandler, const File &file, bool isBig,
68
                 std::vector<const Atom *> &personalities,
69
                 std::vector<uint32_t> &commonEncodings,
70
                 std::vector<UnwindInfoPage> &pages, uint32_t numLSDAs)
71
      : SimpleDefinedAtom(file), _archHandler(archHandler),
72
        _commonEncodingsOffset(7 * sizeof(uint32_t)),
73
        _personalityArrayOffset(_commonEncodingsOffset +
74
                                commonEncodings.size() * sizeof(uint32_t)),
75
        _topLevelIndexOffset(_personalityArrayOffset +
76
                             personalities.size() * sizeof(uint32_t)),
77
        _lsdaIndexOffset(_topLevelIndexOffset +
78
                         3 * (pages.size() + 1) * sizeof(uint32_t)),
79
        _firstPageOffset(_lsdaIndexOffset + 2 * numLSDAs * sizeof(uint32_t)),
80
10
        _isBig(isBig) {
81
10
82
10
    addHeader(commonEncodings.size(), personalities.size(), pages.size());
83
10
    addCommonEncodings(commonEncodings);
84
10
    addPersonalityFunctions(personalities);
85
10
    addTopLevelIndexes(pages);
86
10
    addLSDAIndexes(pages, numLSDAs);
87
10
    addSecondLevelPages(pages);
88
10
  }
89
90
10
  ~UnwindInfoAtom() override = default;
91
92
79
  ContentType contentType() const override {
93
79
    return DefinedAtom::typeProcessedUnwindInfo;
94
79
  }
95
96
10
  Alignment alignment() const override { return 4; }
97
98
30
  uint64_t size() const override { return _contents.size(); }
99
100
0
  ContentPermissions permissions() const override {
101
0
    return DefinedAtom::permR__;
102
0
  }
103
104
20
  ArrayRef<uint8_t> rawContent() const override { return _contents; }
105
106
  void addHeader(uint32_t numCommon, uint32_t numPersonalities,
107
10
                 uint32_t numPages) {
108
10
    using normalized::write32;
109
10
110
10
    uint32_t headerSize = 7 * sizeof(uint32_t);
111
10
    _contents.resize(headerSize);
112
10
113
10
    uint8_t *headerEntries = _contents.data();
114
10
    // version
115
10
    write32(headerEntries, 1, _isBig);
116
10
    // commonEncodingsArraySectionOffset
117
10
    write32(headerEntries + sizeof(uint32_t), _commonEncodingsOffset, _isBig);
118
10
    // commonEncodingsArrayCount
119
10
    write32(headerEntries + 2 * sizeof(uint32_t), numCommon, _isBig);
120
10
    // personalityArraySectionOffset
121
10
    write32(headerEntries + 3 * sizeof(uint32_t), _personalityArrayOffset,
122
10
            _isBig);
123
10
    // personalityArrayCount
124
10
    write32(headerEntries + 4 * sizeof(uint32_t), numPersonalities, _isBig);
125
10
    // indexSectionOffset
126
10
    write32(headerEntries + 5 * sizeof(uint32_t), _topLevelIndexOffset, _isBig);
127
10
    // indexCount
128
10
    write32(headerEntries + 6 * sizeof(uint32_t), numPages + 1, _isBig);
129
10
  }
130
131
  /// Add the list of common encodings to the section; this is simply an array
132
  /// of uint32_t compact values. Size has already been specified in the header.
133
10
  void addCommonEncodings(std::vector<uint32_t> &commonEncodings) {
134
10
    using normalized::write32;
135
10
136
10
    _contents.resize(_commonEncodingsOffset +
137
10
                     commonEncodings.size() * sizeof(uint32_t));
138
10
    uint8_t *commonEncodingsArea =
139
10
        reinterpret_cast<uint8_t *>(_contents.data() + _commonEncodingsOffset);
140
10
141
10
    for (uint32_t encoding : commonEncodings) {
142
0
      write32(commonEncodingsArea, encoding, _isBig);
143
0
      commonEncodingsArea += sizeof(uint32_t);
144
0
    }
145
10
  }
146
147
10
  void addPersonalityFunctions(std::vector<const Atom *> personalities) {
148
10
    _contents.resize(_personalityArrayOffset +
149
10
                     personalities.size() * sizeof(uint32_t));
150
10
151
12
    for (unsigned i = 0; i < personalities.size(); 
++i2
)
152
2
      addImageReferenceIndirect(_personalityArrayOffset + i * sizeof(uint32_t),
153
2
                                personalities[i]);
154
10
  }
155
156
10
  void addTopLevelIndexes(std::vector<UnwindInfoPage> &pages) {
157
10
    using normalized::write32;
158
10
159
10
    uint32_t numIndexes = pages.size() + 1;
160
10
    _contents.resize(_topLevelIndexOffset + numIndexes * 3 * sizeof(uint32_t));
161
10
162
10
    uint32_t pageLoc = _firstPageOffset;
163
10
164
10
    // The most difficult job here is calculating the LSDAs; everything else
165
10
    // follows fairly naturally, but we can't state where the first
166
10
    uint8_t *indexData = &_contents[_topLevelIndexOffset];
167
10
    uint32_t numLSDAs = 0;
168
20
    for (unsigned i = 0; i < pages.size(); 
++i10
) {
169
10
      // functionOffset
170
10
      addImageReference(_topLevelIndexOffset + 3 * i * sizeof(uint32_t),
171
10
                        pages[i].entries[0].rangeStart);
172
10
      // secondLevelPagesSectionOffset
173
10
      write32(indexData + (3 * i + 1) * sizeof(uint32_t), pageLoc, _isBig);
174
10
      write32(indexData + (3 * i + 2) * sizeof(uint32_t),
175
10
              _lsdaIndexOffset + numLSDAs * 2 * sizeof(uint32_t), _isBig);
176
10
177
10
      for (auto &entry : pages[i].entries)
178
25
        if (entry.lsdaLocation)
179
2
          ++numLSDAs;
180
10
    }
181
10
182
10
    // Finally, write out the final sentinel index
183
10
    auto &finalEntry = pages[pages.size() - 1].entries.back();
184
10
    addImageReference(_topLevelIndexOffset +
185
10
                          3 * pages.size() * sizeof(uint32_t),
186
10
                      finalEntry.rangeStart, finalEntry.rangeLength);
187
10
    // secondLevelPagesSectionOffset => 0
188
10
    write32(indexData + (3 * pages.size() + 2) * sizeof(uint32_t),
189
10
            _lsdaIndexOffset + numLSDAs * 2 * sizeof(uint32_t), _isBig);
190
10
  }
191
192
10
  void addLSDAIndexes(std::vector<UnwindInfoPage> &pages, uint32_t numLSDAs) {
193
10
    _contents.resize(_lsdaIndexOffset + numLSDAs * 2 * sizeof(uint32_t));
194
10
195
10
    uint32_t curOffset = _lsdaIndexOffset;
196
10
    for (auto &page : pages) {
197
25
      for (auto &entry : page.entries) {
198
25
        if (!entry.lsdaLocation)
199
23
          continue;
200
2
201
2
        addImageReference(curOffset, entry.rangeStart);
202
2
        addImageReference(curOffset + sizeof(uint32_t), entry.lsdaLocation);
203
2
        curOffset += 2 * sizeof(uint32_t);
204
2
      }
205
10
    }
206
10
  }
207
208
10
  void addSecondLevelPages(std::vector<UnwindInfoPage> &pages) {
209
10
    for (auto &page : pages) {
210
10
      addRegularSecondLevelPage(page);
211
10
    }
212
10
  }
213
214
10
  void addRegularSecondLevelPage(const UnwindInfoPage &page) {
215
10
    uint32_t curPageOffset = _contents.size();
216
10
    const int16_t headerSize = sizeof(uint32_t) + 2 * sizeof(uint16_t);
217
10
    uint32_t curPageSize =
218
10
        headerSize + 2 * page.entries.size() * sizeof(uint32_t);
219
10
    _contents.resize(curPageOffset + curPageSize);
220
10
221
10
    using normalized::write32;
222
10
    using normalized::write16;
223
10
    // 2 => regular page
224
10
    write32(&_contents[curPageOffset], 2, _isBig);
225
10
    // offset of 1st entry
226
10
    write16(&_contents[curPageOffset + 4], headerSize, _isBig);
227
10
    write16(&_contents[curPageOffset + 6], page.entries.size(), _isBig);
228
10
229
10
    uint32_t pagePos = curPageOffset + headerSize;
230
25
    for (auto &entry : page.entries) {
231
25
      addImageReference(pagePos, entry.rangeStart);
232
25
233
25
      write32(_contents.data() + pagePos + sizeof(uint32_t), entry.encoding,
234
25
              _isBig);
235
25
      if ((entry.encoding & 0x0f000000U) ==
236
25
          _archHandler.dwarfCompactUnwindType())
237
3
        addEhFrameReference(pagePos + sizeof(uint32_t), entry.ehFrame);
238
25
239
25
      pagePos += 2 * sizeof(uint32_t);
240
25
    }
241
10
  }
242
243
  void addEhFrameReference(uint32_t offset, const Atom *dest,
244
3
                           Reference::Addend addend = 0) {
245
3
    addReference(Reference::KindNamespace::mach_o, _archHandler.kindArch(),
246
3
                 _archHandler.unwindRefToEhFrameKind(), offset, dest, addend);
247
3
  }
248
249
  void addImageReference(uint32_t offset, const Atom *dest,
250
49
                         Reference::Addend addend = 0) {
251
49
    addReference(Reference::KindNamespace::mach_o, _archHandler.kindArch(),
252
49
                 _archHandler.imageOffsetKind(), offset, dest, addend);
253
49
  }
254
255
2
  void addImageReferenceIndirect(uint32_t offset, const Atom *dest) {
256
2
    addReference(Reference::KindNamespace::mach_o, _archHandler.kindArch(),
257
2
                 _archHandler.imageOffsetKindIndirect(), offset, dest, 0);
258
2
  }
259
260
private:
261
  mach_o::ArchHandler &_archHandler;
262
  std::vector<uint8_t> _contents;
263
  uint32_t _commonEncodingsOffset;
264
  uint32_t _personalityArrayOffset;
265
  uint32_t _topLevelIndexOffset;
266
  uint32_t _lsdaIndexOffset;
267
  uint32_t _firstPageOffset;
268
  bool _isBig;
269
};
270
271
/// Pass for instantiating and optimizing GOT slots.
272
///
273
class CompactUnwindPass : public Pass {
274
public:
275
  CompactUnwindPass(const MachOLinkingContext &context)
276
      : _ctx(context), _archHandler(_ctx.archHandler()),
277
        _file(*_ctx.make_file<MachOFile>("<mach-o Compact Unwind Pass>")),
278
87
        _isBig(MachOLinkingContext::isBigEndian(_ctx.arch())) {
279
87
    _file.setOrdinal(_ctx.getNextOrdinalAndIncrement());
280
87
  }
281
282
private:
283
87
  llvm::Error perform(SimpleFile &mergedFile) override {
284
87
    LLVM_DEBUG(llvm::dbgs() << "MachO Compact Unwind pass\n");
285
87
286
87
    std::map<const Atom *, CompactUnwindEntry> unwindLocs;
287
87
    std::map<const Atom *, const Atom *> dwarfFrames;
288
87
    std::vector<const Atom *> personalities;
289
87
    uint32_t numLSDAs = 0;
290
87
291
87
    // First collect all __compact_unwind and __eh_frame entries, addressable by
292
87
    // the function referred to.
293
87
    collectCompactUnwindEntries(mergedFile, unwindLocs, personalities,
294
87
                                numLSDAs);
295
87
296
87
    collectDwarfFrameEntries(mergedFile, dwarfFrames);
297
87
298
87
    // Skip rest of pass if no unwind info.
299
87
    if (unwindLocs.empty() && 
dwarfFrames.empty()77
)
300
77
      return llvm::Error::success();
301
10
302
10
    // FIXME: if there are more than 4 personality functions then we need to
303
10
    // defer to DWARF info for the ones we don't put in the list. They should
304
10
    // also probably be sorted by frequency.
305
10
    assert(personalities.size() <= 4);
306
10
307
10
    // TODO: Find commmon encodings for use by compressed pages.
308
10
    std::vector<uint32_t> commonEncodings;
309
10
310
10
    // Now sort the entries by final address and fixup the compact encoding to
311
10
    // its final form (i.e. set personality function bits & create DWARF
312
10
    // references where needed).
313
10
    std::vector<CompactUnwindEntry> unwindInfos = createUnwindInfoEntries(
314
10
        mergedFile, unwindLocs, personalities, dwarfFrames);
315
10
316
10
    // Remove any unused eh-frame atoms.
317
10
    pruneUnusedEHFrames(mergedFile, unwindInfos, unwindLocs, dwarfFrames);
318
10
319
10
    // Finally, we can start creating pages based on these entries.
320
10
321
10
    LLVM_DEBUG(llvm::dbgs() << "  Splitting entries into pages\n");
322
10
    // FIXME: we split the entries into pages naively: lots of 4k pages followed
323
10
    // by a small one. ld64 tried to minimize space and align them to real 4k
324
10
    // boundaries. That might be worth doing, or perhaps we could perform some
325
10
    // minor balancing for expected number of lookups.
326
10
    std::vector<UnwindInfoPage> pages;
327
10
    auto remainingInfos = llvm::makeArrayRef(unwindInfos);
328
10
    do {
329
10
      pages.push_back(UnwindInfoPage());
330
10
331
10
      // FIXME: we only create regular pages at the moment. These can hold up to
332
10
      // 1021 entries according to the documentation.
333
10
      unsigned entriesInPage = std::min(1021U, (unsigned)remainingInfos.size());
334
10
335
10
      pages.back().entries = remainingInfos.slice(0, entriesInPage);
336
10
      remainingInfos = remainingInfos.slice(entriesInPage);
337
10
338
10
      LLVM_DEBUG(llvm::dbgs()
339
10
                 << "    Page from "
340
10
                 << pages.back().entries[0].rangeStart->name() << " to "
341
10
                 << pages.back().entries.back().rangeStart->name() << " + "
342
10
                 << llvm::format("0x%x",
343
10
                                 pages.back().entries.back().rangeLength)
344
10
                 << " has " << entriesInPage << " entries\n");
345
10
    } while (!remainingInfos.empty());
346
10
347
10
    auto *unwind = new (_file.allocator())
348
10
        UnwindInfoAtom(_archHandler, _file, _isBig, personalities,
349
10
                       commonEncodings, pages, numLSDAs);
350
10
    mergedFile.addAtom(*unwind);
351
10
352
10
    // Finally, remove all __compact_unwind atoms now that we've processed them.
353
119
    mergedFile.removeDefinedAtomsIf([](const DefinedAtom *atom) {
354
119
      return atom->contentType() == DefinedAtom::typeCompactUnwindInfo;
355
119
    });
356
10
357
10
    return llvm::Error::success();
358
10
  }
359
360
  void collectCompactUnwindEntries(
361
      const SimpleFile &mergedFile,
362
      std::map<const Atom *, CompactUnwindEntry> &unwindLocs,
363
87
      std::vector<const Atom *> &personalities, uint32_t &numLSDAs) {
364
87
    LLVM_DEBUG(llvm::dbgs() << "  Collecting __compact_unwind entries\n");
365
87
366
485
    for (const DefinedAtom *atom : mergedFile.defined()) {
367
485
      if (atom->contentType() != DefinedAtom::typeCompactUnwindInfo)
368
470
        continue;
369
15
370
15
      auto unwindEntry = extractCompactUnwindEntry(atom);
371
15
      unwindLocs.insert(std::make_pair(unwindEntry.rangeStart, unwindEntry));
372
15
373
15
      LLVM_DEBUG(llvm::dbgs() << "    Entry for "
374
15
                              << unwindEntry.rangeStart->name() << ", encoding="
375
15
                              << llvm::format("0x%08x", unwindEntry.encoding));
376
15
      if (unwindEntry.personalityFunction)
377
15
        LLVM_DEBUG(llvm::dbgs()
378
15
                   << ", personality="
379
15
                   << unwindEntry.personalityFunction->name()
380
15
                   << ", lsdaLoc=" << unwindEntry.lsdaLocation->name());
381
15
      LLVM_DEBUG(llvm::dbgs() << '\n');
382
15
383
15
      // Count number of LSDAs we see, since we need to know how big the index
384
15
      // will be while laying out the section.
385
15
      if (unwindEntry.lsdaLocation)
386
2
        ++numLSDAs;
387
15
388
15
      // Gather the personality functions now, so that they're in deterministic
389
15
      // order (derived from the DefinedAtom order).
390
15
      if (unwindEntry.personalityFunction &&
391
15
          
!llvm::count(personalities, unwindEntry.personalityFunction)2
)
392
2
        personalities.push_back(unwindEntry.personalityFunction);
393
15
    }
394
87
  }
395
396
15
  CompactUnwindEntry extractCompactUnwindEntry(const DefinedAtom *atom) {
397
15
    CompactUnwindEntry entry;
398
15
399
18
    for (const Reference *ref : *atom) {
400
18
      switch (ref->offsetInAtom()) {
401
18
      case 0:
402
14
        // FIXME: there could legitimately be functions with multiple encoding
403
14
        // entries. However, nothing produces them at the moment.
404
14
        assert(ref->addend() == 0 && "unexpected offset into function");
405
14
        entry.rangeStart = ref->target();
406
14
        break;
407
18
      case 0x10:
408
2
        assert(ref->addend() == 0 && "unexpected offset into personality fn");
409
2
        entry.personalityFunction = ref->target();
410
2
        break;
411
18
      case 0x18:
412
2
        assert(ref->addend() == 0 && "unexpected offset into LSDA atom");
413
2
        entry.lsdaLocation = ref->target();
414
2
        break;
415
18
      }
416
18
    }
417
15
418
15
    if (atom->rawContent().size() < 4 * sizeof(uint32_t))
419
1
      return entry;
420
14
421
14
    using normalized::read32;
422
14
    entry.rangeLength =
423
14
        read32(atom->rawContent().data() + 2 * sizeof(uint32_t), _isBig);
424
14
    entry.encoding =
425
14
        read32(atom->rawContent().data() + 3 * sizeof(uint32_t), _isBig);
426
14
    return entry;
427
14
  }
428
429
  void
430
  collectDwarfFrameEntries(const SimpleFile &mergedFile,
431
87
                           std::map<const Atom *, const Atom *> &dwarfFrames) {
432
485
    for (const DefinedAtom *ehFrameAtom : mergedFile.defined()) {
433
485
      if (ehFrameAtom->contentType() != DefinedAtom::typeCFI)
434
463
        continue;
435
22
      if (ArchHandler::isDwarfCIE(_isBig, ehFrameAtom))
436
10
        continue;
437
12
438
12
      if (const Atom *function = _archHandler.fdeTargetFunction(ehFrameAtom))
439
12
        dwarfFrames[function] = ehFrameAtom;
440
12
    }
441
87
  }
442
443
  /// Every atom defined in __TEXT,__text needs an entry in the final
444
  /// __unwind_info section (in order). These comes from two sources:
445
  ///   + Input __compact_unwind sections where possible (after adding the
446
  ///      personality function offset which is only known now).
447
  ///   + A synthesised reference to __eh_frame if there's no __compact_unwind
448
  ///     or too many personality functions to be accommodated.
449
  std::vector<CompactUnwindEntry> createUnwindInfoEntries(
450
      const SimpleFile &mergedFile,
451
      const std::map<const Atom *, CompactUnwindEntry> &unwindLocs,
452
      const std::vector<const Atom *> &personalities,
453
10
      const std::map<const Atom *, const Atom *> &dwarfFrames) {
454
10
    std::vector<CompactUnwindEntry> unwindInfos;
455
10
456
10
    LLVM_DEBUG(llvm::dbgs() << "  Creating __unwind_info entries\n");
457
10
    // The final order in the __unwind_info section must be derived from the
458
10
    // order of typeCode atoms, since that's how they'll be put into the object
459
10
    // file eventually (yuck!).
460
126
    for (const DefinedAtom *atom : mergedFile.defined()) {
461
126
      if (atom->contentType() != DefinedAtom::typeCode)
462
101
        continue;
463
25
464
25
      unwindInfos.push_back(finalizeUnwindInfoEntryForAtom(
465
25
          atom, unwindLocs, personalities, dwarfFrames));
466
25
467
25
      LLVM_DEBUG(llvm::dbgs()
468
25
                 << "    Entry for " << atom->name() << ", final encoding="
469
25
                 << llvm::format("0x%08x", unwindInfos.back().encoding)
470
25
                 << '\n');
471
25
    }
472
10
473
10
    return unwindInfos;
474
10
  }
475
476
  /// Remove unused EH frames.
477
  ///
478
  /// An EH frame is considered unused if there is a corresponding compact
479
  /// unwind atom that doesn't require the EH frame.
480
  void pruneUnusedEHFrames(
481
                   SimpleFile &mergedFile,
482
                   const std::vector<CompactUnwindEntry> &unwindInfos,
483
                   const std::map<const Atom *, CompactUnwindEntry> &unwindLocs,
484
10
                   const std::map<const Atom *, const Atom *> &dwarfFrames) {
485
10
486
10
    // Worklist of all 'used' FDEs.
487
10
    std::vector<const DefinedAtom *> usedDwarfWorklist;
488
10
489
10
    // We have to check two conditions when building the worklist:
490
10
    // (1) EH frames used by compact unwind entries.
491
10
    for (auto &entry : unwindInfos)
492
25
      if (entry.ehFrame)
493
3
        usedDwarfWorklist.push_back(cast<DefinedAtom>(entry.ehFrame));
494
10
495
10
    // (2) EH frames that reference functions with no corresponding compact
496
10
    //     unwind info.
497
10
    for (auto &entry : dwarfFrames)
498
12
      if (!unwindLocs.count(entry.first))
499
2
        usedDwarfWorklist.push_back(cast<DefinedAtom>(entry.second));
500
10
501
10
    // Add all transitively referenced CFI atoms by processing the worklist.
502
10
    std::set<const Atom *> usedDwarfFrames;
503
20
    while (!usedDwarfWorklist.empty()) {
504
10
      const DefinedAtom *cfiAtom = usedDwarfWorklist.back();
505
10
      usedDwarfWorklist.pop_back();
506
10
      usedDwarfFrames.insert(cfiAtom);
507
10
      for (const auto *ref : *cfiAtom) {
508
10
        const DefinedAtom *cfiTarget = dyn_cast<DefinedAtom>(ref->target());
509
10
        if (cfiTarget->contentType() == DefinedAtom::typeCFI)
510
5
          usedDwarfWorklist.push_back(cfiTarget);
511
10
      }
512
10
    }
513
10
514
10
    // Finally, delete all unreferenced CFI atoms.
515
126
    mergedFile.removeDefinedAtomsIf([&](const DefinedAtom *atom) {
516
126
      if ((atom->contentType() == DefinedAtom::typeCFI) &&
517
126
          
!usedDwarfFrames.count(atom)22
)
518
17
        return true;
519
109
      return false;
520
109
    });
521
10
  }
522
523
  CompactUnwindEntry finalizeUnwindInfoEntryForAtom(
524
      const DefinedAtom *function,
525
      const std::map<const Atom *, CompactUnwindEntry> &unwindLocs,
526
      const std::vector<const Atom *> &personalities,
527
25
      const std::map<const Atom *, const Atom *> &dwarfFrames) {
528
25
    auto unwindLoc = unwindLocs.find(function);
529
25
530
25
    CompactUnwindEntry entry;
531
25
    if (unwindLoc == unwindLocs.end()) {
532
11
      // Default entry has correct encoding (0 => no unwind), but we need to
533
11
      // synthesise the function.
534
11
      entry.rangeStart = function;
535
11
      entry.rangeLength = function->size();
536
11
    } else
537
14
      entry = unwindLoc->second;
538
25
539
25
540
25
    // If there's no __compact_unwind entry, or it explicitly says to use
541
25
    // __eh_frame, we need to try and fill in the correct DWARF atom.
542
25
    if (entry.encoding == _archHandler.dwarfCompactUnwindType() ||
543
25
        
entry.encoding == 024
) {
544
12
      auto dwarfFrame = dwarfFrames.find(function);
545
12
      if (dwarfFrame != dwarfFrames.end()) {
546
3
        entry.encoding = _archHandler.dwarfCompactUnwindType();
547
3
        entry.ehFrame = dwarfFrame->second;
548
3
      }
549
12
    }
550
25
551
25
    auto personality = llvm::find(personalities, entry.personalityFunction);
552
25
    uint32_t personalityIdx = personality == personalities.end()
553
25
                                  ? 
023
554
25
                                  : 
personality - personalities.begin() + 12
;
555
25
556
25
    // FIXME: We should also use DWARF when there isn't enough room for the
557
25
    // personality function in the compact encoding.
558
25
    assert(personalityIdx < 4 && "too many personality functions");
559
25
560
25
    entry.encoding |= personalityIdx << 28;
561
25
562
25
    if (entry.lsdaLocation)
563
2
      entry.encoding |= 1U << 30;
564
25
565
25
    return entry;
566
25
  }
567
568
  const MachOLinkingContext &_ctx;
569
  mach_o::ArchHandler &_archHandler;
570
  MachOFile &_file;
571
  bool _isBig;
572
};
573
574
87
void addCompactUnwindPass(PassManager &pm, const MachOLinkingContext &ctx) {
575
87
  assert(ctx.needsCompactUnwindPass());
576
87
  pm.add(llvm::make_unique<CompactUnwindPass>(ctx));
577
87
}
578
579
} // end namesapce mach_o
580
} // end namesapce lld