1 //===- bolt/Core/DebugData.cpp - Debugging information handling -----------===//
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 // This file implements functions and classes for handling debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Core/DebugData.h"
14 #include "bolt/Core/BinaryBasicBlock.h"
15 #include "bolt/Core/BinaryFunction.h"
16 #include "bolt/Utils/Utils.h"
17 #include "llvm/MC/MCObjectStreamer.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/EndianStream.h"
21 #include "llvm/Support/LEB128.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <cstdint>
25 #include <limits>
26 
27 #define DEBUG_TYPE "bolt-debug-info"
28 
29 namespace opts {
30 extern llvm::cl::opt<unsigned> Verbosity;
31 }
32 
33 namespace llvm {
34 namespace bolt {
35 
36 const DebugLineTableRowRef DebugLineTableRowRef::NULL_ROW{0, 0};
37 
38 namespace {
39 
40 // Writes address ranges to Writer as pairs of 64-bit (address, size).
41 // If RelativeRange is true, assumes the address range to be written must be of
42 // the form (begin address, range size), otherwise (begin address, end address).
43 // Terminates the list by writing a pair of two zeroes.
44 // Returns the number of written bytes.
45 uint64_t writeAddressRanges(raw_svector_ostream &Stream,
46                             const DebugAddressRangesVector &AddressRanges,
47                             const bool WriteRelativeRanges = false) {
48   for (const DebugAddressRange &Range : AddressRanges) {
49     support::endian::write(Stream, Range.LowPC, support::little);
50     support::endian::write(
51         Stream, WriteRelativeRanges ? Range.HighPC - Range.LowPC : Range.HighPC,
52         support::little);
53   }
54   // Finish with 0 entries.
55   support::endian::write(Stream, 0ULL, support::little);
56   support::endian::write(Stream, 0ULL, support::little);
57   return AddressRanges.size() * 16 + 16;
58 }
59 
60 } // namespace
61 
62 DebugRangesSectionWriter::DebugRangesSectionWriter() {
63   RangesBuffer = std::make_unique<DebugBufferVector>();
64   RangesStream = std::make_unique<raw_svector_ostream>(*RangesBuffer);
65 
66   // Add an empty range as the first entry;
67   SectionOffset +=
68       writeAddressRanges(*RangesStream.get(), DebugAddressRangesVector{});
69 }
70 
71 uint64_t DebugRangesSectionWriter::addRanges(
72     DebugAddressRangesVector &&Ranges,
73     std::map<DebugAddressRangesVector, uint64_t> &CachedRanges) {
74   if (Ranges.empty())
75     return getEmptyRangesOffset();
76 
77   const auto RI = CachedRanges.find(Ranges);
78   if (RI != CachedRanges.end())
79     return RI->second;
80 
81   const uint64_t EntryOffset = addRanges(Ranges);
82   CachedRanges.emplace(std::move(Ranges), EntryOffset);
83 
84   return EntryOffset;
85 }
86 
87 uint64_t
88 DebugRangesSectionWriter::addRanges(const DebugAddressRangesVector &Ranges) {
89   if (Ranges.empty())
90     return getEmptyRangesOffset();
91 
92   // Reading the SectionOffset and updating it should be atomic to guarantee
93   // unique and correct offsets in patches.
94   std::lock_guard<std::mutex> Lock(WriterMutex);
95   const uint32_t EntryOffset = SectionOffset;
96   SectionOffset += writeAddressRanges(*RangesStream.get(), Ranges);
97 
98   return EntryOffset;
99 }
100 
101 uint64_t DebugRangesSectionWriter::getSectionOffset() {
102   std::lock_guard<std::mutex> Lock(WriterMutex);
103   return SectionOffset;
104 }
105 
106 void DebugARangesSectionWriter::addCURanges(uint64_t CUOffset,
107                                             DebugAddressRangesVector &&Ranges) {
108   std::lock_guard<std::mutex> Lock(CUAddressRangesMutex);
109   CUAddressRanges.emplace(CUOffset, std::move(Ranges));
110 }
111 
112 void DebugARangesSectionWriter::writeARangesSection(
113     raw_svector_ostream &RangesStream) const {
114   // For reference on the format of the .debug_aranges section, see the DWARF4
115   // specification, section 6.1.4 Lookup by Address
116   // http://www.dwarfstd.org/doc/DWARF4.pdf
117   for (const auto &CUOffsetAddressRangesPair : CUAddressRanges) {
118     const uint64_t Offset = CUOffsetAddressRangesPair.first;
119     const DebugAddressRangesVector &AddressRanges =
120         CUOffsetAddressRangesPair.second;
121 
122     // Emit header.
123 
124     // Size of this set: 8 (size of the header) + 4 (padding after header)
125     // + 2*sizeof(uint64_t) bytes for each of the ranges, plus an extra
126     // pair of uint64_t's for the terminating, zero-length range.
127     // Does not include size field itself.
128     uint32_t Size = 8 + 4 + 2 * sizeof(uint64_t) * (AddressRanges.size() + 1);
129 
130     // Header field #1: set size.
131     support::endian::write(RangesStream, Size, support::little);
132 
133     // Header field #2: version number, 2 as per the specification.
134     support::endian::write(RangesStream, static_cast<uint16_t>(2),
135                            support::little);
136 
137     // Header field #3: debug info offset of the correspondent compile unit.
138     support::endian::write(RangesStream, static_cast<uint32_t>(Offset),
139                            support::little);
140 
141     // Header field #4: address size.
142     // 8 since we only write ELF64 binaries for now.
143     RangesStream << char(8);
144 
145     // Header field #5: segment size of target architecture.
146     RangesStream << char(0);
147 
148     // Padding before address table - 4 bytes in the 64-bit-pointer case.
149     support::endian::write(RangesStream, static_cast<uint32_t>(0),
150                            support::little);
151 
152     writeAddressRanges(RangesStream, AddressRanges, true);
153   }
154 }
155 
156 DebugAddrWriter::DebugAddrWriter(BinaryContext *Bc) { BC = Bc; }
157 
158 void DebugAddrWriter::AddressForDWOCU::dump() {
159   std::vector<IndexAddressPair> SortedMap(indexToAddressBegin(),
160                                           indexToAdddessEnd());
161   // Sorting address in increasing order of indices.
162   std::sort(SortedMap.begin(), SortedMap.end(),
163             [](const IndexAddressPair &A, const IndexAddressPair &B) {
164               return A.first < B.first;
165             });
166   for (auto &Pair : SortedMap)
167     dbgs() << Twine::utohexstr(Pair.second) << "\t" << Pair.first << "\n";
168 }
169 uint32_t DebugAddrWriter::getIndexFromAddress(uint64_t Address,
170                                               uint64_t DWOId) {
171   if (!AddressMaps.count(DWOId))
172     AddressMaps[DWOId] = AddressForDWOCU();
173 
174   AddressForDWOCU &Map = AddressMaps[DWOId];
175   auto Entry = Map.find(Address);
176   if (Entry == Map.end()) {
177     auto Index = Map.getNextIndex();
178     Entry = Map.insert(Address, Index).first;
179   }
180   return Entry->second;
181 }
182 
183 // Case1) Address is not in map insert in to AddresToIndex and IndexToAddres
184 // Case2) Address is in the map but Index is higher or equal. Need to update
185 // IndexToAddrss. Case3) Address is in the map but Index is lower. Need to
186 // update AddressToIndex and IndexToAddress
187 void DebugAddrWriter::addIndexAddress(uint64_t Address, uint32_t Index,
188                                       uint64_t DWOId) {
189   AddressForDWOCU &Map = AddressMaps[DWOId];
190   auto Entry = Map.find(Address);
191   if (Entry != Map.end()) {
192     if (Entry->second > Index)
193       Map.updateAddressToIndex(Address, Index);
194     Map.updateIndexToAddrss(Address, Index);
195   } else
196     Map.insert(Address, Index);
197 }
198 
199 AddressSectionBuffer DebugAddrWriter::finalize() {
200   // Need to layout all sections within .debug_addr
201   // Within each section sort Address by index.
202   AddressSectionBuffer Buffer;
203   raw_svector_ostream AddressStream(Buffer);
204   for (std::unique_ptr<DWARFUnit> &CU : BC->DwCtx->compile_units()) {
205     Optional<uint64_t> DWOId = CU->getDWOId();
206     // Handling the case wehre debug information is a mix of Debug fission and
207     // monolitic.
208     if (!DWOId)
209       continue;
210     auto AM = AddressMaps.find(*DWOId);
211     // Adding to map even if it did not contribute to .debug_addr.
212     // The Skeleton CU will still have DW_AT_GNU_addr_base.
213     DWOIdToOffsetMap[*DWOId] = Buffer.size();
214     // If does not exist this CUs DWO section didn't contribute to .debug_addr.
215     if (AM == AddressMaps.end())
216       continue;
217     std::vector<IndexAddressPair> SortedMap(AM->second.indexToAddressBegin(),
218                                             AM->second.indexToAdddessEnd());
219     // Sorting address in increasing order of indices.
220     std::sort(SortedMap.begin(), SortedMap.end(),
221               [](const IndexAddressPair &A, const IndexAddressPair &B) {
222                 return A.first < B.first;
223               });
224 
225     uint8_t AddrSize = CU->getAddressByteSize();
226     uint32_t Counter = 0;
227     auto WriteAddress = [&](uint64_t Address) -> void {
228       ++Counter;
229       switch (AddrSize) {
230       default:
231         assert(false && "Address Size is invalid.");
232         break;
233       case 4:
234         support::endian::write(AddressStream, static_cast<uint32_t>(Address),
235                                support::little);
236         break;
237       case 8:
238         support::endian::write(AddressStream, Address, support::little);
239         break;
240       }
241     };
242 
243     for (const IndexAddressPair &Val : SortedMap) {
244       while (Val.first > Counter)
245         WriteAddress(0);
246       WriteAddress(Val.second);
247     }
248   }
249 
250   return Buffer;
251 }
252 
253 uint64_t DebugAddrWriter::getOffset(uint64_t DWOId) {
254   auto Iter = DWOIdToOffsetMap.find(DWOId);
255   assert(Iter != DWOIdToOffsetMap.end() &&
256          "Offset in to.debug_addr was not found for DWO ID.");
257   return Iter->second;
258 }
259 
260 DebugLocWriter::DebugLocWriter(BinaryContext *BC) {
261   LocBuffer = std::make_unique<DebugBufferVector>();
262   LocStream = std::make_unique<raw_svector_ostream>(*LocBuffer);
263 }
264 
265 void DebugLocWriter::addList(uint64_t AttrOffset,
266                              DebugLocationsVector &&LocList) {
267   if (LocList.empty()) {
268     EmptyAttrLists.push_back(AttrOffset);
269     return;
270   }
271   // Since there is a separate DebugLocWriter for each thread,
272   // we don't need a lock to read the SectionOffset and update it.
273   const uint32_t EntryOffset = SectionOffset;
274 
275   for (const DebugLocationEntry &Entry : LocList) {
276     support::endian::write(*LocStream, static_cast<uint64_t>(Entry.LowPC),
277                            support::little);
278     support::endian::write(*LocStream, static_cast<uint64_t>(Entry.HighPC),
279                            support::little);
280     support::endian::write(*LocStream, static_cast<uint16_t>(Entry.Expr.size()),
281                            support::little);
282     *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()),
283                             Entry.Expr.size());
284     SectionOffset += 2 * 8 + 2 + Entry.Expr.size();
285   }
286   LocStream->write_zeros(16);
287   SectionOffset += 16;
288   LocListDebugInfoPatches.push_back({AttrOffset, EntryOffset});
289 }
290 
291 void DebugLoclistWriter::addList(uint64_t AttrOffset,
292                                  DebugLocationsVector &&LocList) {
293   Patches.push_back({AttrOffset, std::move(LocList)});
294 }
295 
296 std::unique_ptr<DebugBufferVector> DebugLocWriter::getBuffer() {
297   return std::move(LocBuffer);
298 }
299 
300 // DWARF 4: 2.6.2
301 void DebugLocWriter::finalize(uint64_t SectionOffset,
302                               SimpleBinaryPatcher &DebugInfoPatcher) {
303   for (const auto LocListDebugInfoPatchType : LocListDebugInfoPatches) {
304     uint64_t Offset = SectionOffset + LocListDebugInfoPatchType.LocListOffset;
305     DebugInfoPatcher.addLE32Patch(LocListDebugInfoPatchType.DebugInfoAttrOffset,
306                                   Offset);
307   }
308 
309   for (uint64_t DebugInfoAttrOffset : EmptyAttrLists)
310     DebugInfoPatcher.addLE32Patch(DebugInfoAttrOffset,
311                                   DebugLocWriter::EmptyListOffset);
312 }
313 
314 void DebugLoclistWriter::finalize(uint64_t SectionOffset,
315                                   SimpleBinaryPatcher &DebugInfoPatcher) {
316   for (LocPatch &Patch : Patches) {
317     if (Patch.LocList.empty()) {
318       DebugInfoPatcher.addLE32Patch(Patch.AttrOffset,
319                                     DebugLocWriter::EmptyListOffset);
320       continue;
321     }
322     const uint32_t EntryOffset = LocBuffer->size();
323     for (const DebugLocationEntry &Entry : Patch.LocList) {
324       support::endian::write(*LocStream,
325                              static_cast<uint8_t>(dwarf::DW_LLE_startx_length),
326                              support::little);
327       uint32_t Index = AddrWriter->getIndexFromAddress(Entry.LowPC, DWOId);
328       encodeULEB128(Index, *LocStream);
329 
330       // TODO: Support DWARF5
331       support::endian::write(*LocStream,
332                              static_cast<uint32_t>(Entry.HighPC - Entry.LowPC),
333                              support::little);
334       support::endian::write(*LocStream,
335                              static_cast<uint16_t>(Entry.Expr.size()),
336                              support::little);
337       *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()),
338                               Entry.Expr.size());
339     }
340     support::endian::write(*LocStream,
341                            static_cast<uint8_t>(dwarf::DW_LLE_end_of_list),
342                            support::little);
343     DebugInfoPatcher.addLE32Patch(Patch.AttrOffset, EntryOffset);
344     clearList(Patch.LocList);
345   }
346   clearList(Patches);
347 }
348 
349 DebugAddrWriter *DebugLoclistWriter::AddrWriter = nullptr;
350 
351 void SimpleBinaryPatcher::addBinaryPatch(uint32_t Offset,
352                                          const std::string &NewValue) {
353   Patches.emplace_back(Offset, NewValue);
354 }
355 
356 void SimpleBinaryPatcher::addBytePatch(uint32_t Offset, uint8_t Value) {
357   Patches.emplace_back(Offset, std::string(1, Value));
358 }
359 
360 void SimpleBinaryPatcher::addLEPatch(uint32_t Offset, uint64_t NewValue,
361                                      size_t ByteSize) {
362   std::string LE64(ByteSize, 0);
363   for (size_t I = 0; I < ByteSize; ++I) {
364     LE64[I] = NewValue & 0xff;
365     NewValue >>= 8;
366   }
367   Patches.emplace_back(Offset, LE64);
368 }
369 
370 void SimpleBinaryPatcher::addUDataPatch(uint32_t Offset, uint64_t Value,
371                                         uint64_t Size) {
372   std::string Buff;
373   raw_string_ostream OS(Buff);
374   encodeULEB128(Value, OS, Size);
375 
376   Patches.emplace_back(Offset, OS.str());
377 }
378 
379 void SimpleBinaryPatcher::addLE64Patch(uint32_t Offset, uint64_t NewValue) {
380   addLEPatch(Offset, NewValue, 8);
381 }
382 
383 void SimpleBinaryPatcher::addLE32Patch(uint32_t Offset, uint32_t NewValue) {
384   addLEPatch(Offset, NewValue, 4);
385 }
386 
387 void SimpleBinaryPatcher::patchBinary(std::string &BinaryContents,
388                                       uint32_t DWPOffset = 0) {
389   for (const auto &Patch : Patches) {
390     uint32_t Offset = Patch.first - DWPOffset;
391     const std::string &ByteSequence = Patch.second;
392     assert(Offset + ByteSequence.size() <= BinaryContents.size() &&
393            "Applied patch runs over binary size.");
394     for (uint64_t I = 0, Size = ByteSequence.size(); I < Size; ++I) {
395       BinaryContents[Offset + I] = ByteSequence[I];
396     }
397   }
398 }
399 
400 void DebugStrWriter::create() {
401   StrBuffer = std::make_unique<DebugStrBufferVector>();
402   StrStream = std::make_unique<raw_svector_ostream>(*StrBuffer);
403 }
404 
405 void DebugStrWriter::initialize() {
406   auto StrSection = BC->DwCtx->getDWARFObj().getStrSection();
407   (*StrStream) << StrSection;
408 }
409 
410 uint32_t DebugStrWriter::addString(StringRef Str) {
411   if (StrBuffer->empty())
412     initialize();
413   auto Offset = StrBuffer->size();
414   (*StrStream) << Str;
415   StrStream->write_zeros(1);
416   return Offset;
417 }
418 
419 void DebugAbbrevWriter::addUnitAbbreviations(DWARFUnit &Unit) {
420   const DWARFAbbreviationDeclarationSet *Abbrevs = Unit.getAbbreviations();
421   if (!Abbrevs)
422     return;
423 
424   // Multiple units may share the same abbreviations. Only add abbreviations
425   // for the first unit and reuse them.
426   const uint64_t AbbrevOffset = Unit.getAbbreviationsOffset();
427   if (UnitsAbbrevData.find(AbbrevOffset) != UnitsAbbrevData.end())
428     return;
429 
430   AbbrevData &UnitData = UnitsAbbrevData[AbbrevOffset];
431   UnitData.Buffer = std::make_unique<DebugBufferVector>();
432   UnitData.Stream = std::make_unique<raw_svector_ostream>(*UnitData.Buffer);
433 
434   const PatchesTy &UnitPatches = Patches[&Unit];
435 
436   raw_svector_ostream &OS = *UnitData.Stream.get();
437 
438   // Take a fast path if there are no patches to apply. Simply copy the original
439   // contents.
440   if (UnitPatches.empty()) {
441     StringRef AbbrevSectionContents =
442         Unit.isDWOUnit() ? Unit.getContext().getDWARFObj().getAbbrevDWOSection()
443                          : Unit.getContext().getDWARFObj().getAbbrevSection();
444     StringRef AbbrevContents;
445 
446     const DWARFUnitIndex &CUIndex = Unit.getContext().getCUIndex();
447     if (!CUIndex.getRows().empty()) {
448       // Handle DWP section contribution.
449       const DWARFUnitIndex::Entry *DWOEntry =
450           CUIndex.getFromHash(*Unit.getDWOId());
451       if (!DWOEntry)
452         return;
453 
454       const DWARFUnitIndex::Entry::SectionContribution *DWOContrubution =
455           DWOEntry->getContribution(DWARFSectionKind::DW_SECT_ABBREV);
456       AbbrevContents = AbbrevSectionContents.substr(DWOContrubution->Offset,
457                                                     DWOContrubution->Length);
458     } else if (!Unit.isDWOUnit()) {
459       const uint64_t StartOffset = Unit.getAbbreviationsOffset();
460 
461       // We know where the unit's abbreviation set starts, but not where it ends
462       // as such data is not readily available. Hence, we have to build a sorted
463       // list of start addresses and find the next starting address to determine
464       // the set boundaries.
465       //
466       // FIXME: if we had a full access to DWARFDebugAbbrev::AbbrDeclSets
467       // we wouldn't have to build our own sorted list for the quick lookup.
468       if (AbbrevSetOffsets.empty()) {
469         llvm::for_each(
470             *Unit.getContext().getDebugAbbrev(),
471             [&](const std::pair<uint64_t, DWARFAbbreviationDeclarationSet> &P) {
472               AbbrevSetOffsets.push_back(P.first);
473             });
474         llvm::sort(AbbrevSetOffsets);
475       }
476       auto It = llvm::upper_bound(AbbrevSetOffsets, StartOffset);
477       const uint64_t EndOffset =
478           It == AbbrevSetOffsets.end() ? AbbrevSectionContents.size() : *It;
479       AbbrevContents = AbbrevSectionContents.slice(StartOffset, EndOffset);
480     } else {
481       // For DWO unit outside of DWP, we expect the entire section to hold
482       // abbreviations for this unit only.
483       AbbrevContents = AbbrevSectionContents;
484     }
485 
486     OS.reserveExtraSpace(AbbrevContents.size());
487     OS << AbbrevContents;
488 
489     return;
490   }
491 
492   for (auto I = Abbrevs->begin(), E = Abbrevs->end(); I != E; ++I) {
493     const DWARFAbbreviationDeclaration &Abbrev = *I;
494     auto Patch = UnitPatches.find(&Abbrev);
495 
496     encodeULEB128(Abbrev.getCode(), OS);
497     encodeULEB128(Abbrev.getTag(), OS);
498     encodeULEB128(Abbrev.hasChildren(), OS);
499     for (const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec :
500          Abbrev.attributes()) {
501       if (Patch != UnitPatches.end()) {
502         bool Patched = false;
503         // Patches added later take a precedence over earlier ones.
504         for (auto I = Patch->second.rbegin(), E = Patch->second.rend(); I != E;
505              ++I) {
506           if (I->OldAttr != AttrSpec.Attr)
507             continue;
508 
509           encodeULEB128(I->NewAttr, OS);
510           encodeULEB128(I->NewAttrForm, OS);
511           Patched = true;
512           break;
513         }
514         if (Patched)
515           continue;
516       }
517 
518       encodeULEB128(AttrSpec.Attr, OS);
519       encodeULEB128(AttrSpec.Form, OS);
520       if (AttrSpec.isImplicitConst())
521         encodeSLEB128(AttrSpec.getImplicitConstValue(), OS);
522     }
523 
524     encodeULEB128(0, OS);
525     encodeULEB128(0, OS);
526   }
527   encodeULEB128(0, OS);
528 }
529 
530 std::unique_ptr<DebugBufferVector> DebugAbbrevWriter::finalize() {
531   if (DWOId) {
532     // We expect abbrev_offset to always be zero for DWO units as there
533     // should be one CU per DWO, and TUs should share the same abbreviation
534     // set with the CU.
535     // For DWP AbbreviationsOffset is an Abbrev contribution in the DWP file, so
536     // can be none zero. Thus we are skipping the check for DWP.
537     bool IsDWP = !Context.getCUIndex().getRows().empty();
538     if (!IsDWP) {
539       for (const std::unique_ptr<DWARFUnit> &Unit : Context.dwo_units()) {
540         if (Unit->getAbbreviationsOffset() != 0) {
541           errs() << "BOLT-ERROR: detected DWO unit with non-zero abbr_offset. "
542                     "Unable to update debug info.\n";
543           exit(1);
544         }
545       }
546     }
547 
548     // Issue abbreviations for the DWO CU only.
549     addUnitAbbreviations(*Context.getDWOCompileUnitForHash(*DWOId));
550   } else {
551     // Add abbreviations from compile and type non-DWO units.
552     for (const std::unique_ptr<DWARFUnit> &Unit : Context.normal_units())
553       addUnitAbbreviations(*Unit);
554   }
555 
556   DebugBufferVector ReturnBuffer;
557 
558   // Pre-calculate the total size of abbrev section.
559   uint64_t Size = 0;
560   for (const auto &KV : UnitsAbbrevData) {
561     const AbbrevData &UnitData = KV.second;
562     Size += UnitData.Buffer->size();
563   }
564   ReturnBuffer.reserve(Size);
565 
566   uint64_t Pos = 0;
567   for (auto &KV : UnitsAbbrevData) {
568     AbbrevData &UnitData = KV.second;
569     ReturnBuffer.append(*UnitData.Buffer);
570     UnitData.Offset = Pos;
571     Pos += UnitData.Buffer->size();
572 
573     UnitData.Buffer.reset();
574     UnitData.Stream.reset();
575   }
576 
577   return std::make_unique<DebugBufferVector>(ReturnBuffer);
578 }
579 
580 static void emitDwarfSetLineAddrAbs(MCStreamer &OS,
581                                     MCDwarfLineTableParams Params,
582                                     int64_t LineDelta, uint64_t Address,
583                                     int PointerSize) {
584   // emit the sequence to set the address
585   OS.emitIntValue(dwarf::DW_LNS_extended_op, 1);
586   OS.emitULEB128IntValue(PointerSize + 1);
587   OS.emitIntValue(dwarf::DW_LNE_set_address, 1);
588   OS.emitIntValue(Address, PointerSize);
589 
590   // emit the sequence for the LineDelta (from 1) and a zero address delta.
591   MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
592 }
593 
594 static inline void emitBinaryDwarfLineTable(
595     MCStreamer *MCOS, MCDwarfLineTableParams Params,
596     const DWARFDebugLine::LineTable *Table,
597     const std::vector<DwarfLineTable::RowSequence> &InputSequences) {
598   if (InputSequences.empty())
599     return;
600 
601   constexpr uint64_t InvalidAddress = UINT64_MAX;
602   unsigned FileNum = 1;
603   unsigned LastLine = 1;
604   unsigned Column = 0;
605   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
606   unsigned Isa = 0;
607   unsigned Discriminator = 0;
608   uint64_t LastAddress = InvalidAddress;
609   uint64_t PrevEndOfSequence = InvalidAddress;
610   const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo();
611 
612   auto emitEndOfSequence = [&](uint64_t Address) {
613     MCDwarfLineAddr::Emit(MCOS, Params, INT64_MAX, Address - LastAddress);
614     FileNum = 1;
615     LastLine = 1;
616     Column = 0;
617     Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
618     Isa = 0;
619     Discriminator = 0;
620     LastAddress = InvalidAddress;
621   };
622 
623   for (const DwarfLineTable::RowSequence &Sequence : InputSequences) {
624     const uint64_t SequenceStart =
625         Table->Rows[Sequence.FirstIndex].Address.Address;
626 
627     // Check if we need to mark the end of the sequence.
628     if (PrevEndOfSequence != InvalidAddress && LastAddress != InvalidAddress &&
629         PrevEndOfSequence != SequenceStart) {
630       emitEndOfSequence(PrevEndOfSequence);
631     }
632 
633     for (uint32_t RowIndex = Sequence.FirstIndex;
634          RowIndex <= Sequence.LastIndex; ++RowIndex) {
635       const DWARFDebugLine::Row &Row = Table->Rows[RowIndex];
636       int64_t LineDelta = static_cast<int64_t>(Row.Line) - LastLine;
637       const uint64_t Address = Row.Address.Address;
638 
639       if (FileNum != Row.File) {
640         FileNum = Row.File;
641         MCOS->emitInt8(dwarf::DW_LNS_set_file);
642         MCOS->emitULEB128IntValue(FileNum);
643       }
644       if (Column != Row.Column) {
645         Column = Row.Column;
646         MCOS->emitInt8(dwarf::DW_LNS_set_column);
647         MCOS->emitULEB128IntValue(Column);
648       }
649       if (Discriminator != Row.Discriminator &&
650           MCOS->getContext().getDwarfVersion() >= 4) {
651         Discriminator = Row.Discriminator;
652         unsigned Size = getULEB128Size(Discriminator);
653         MCOS->emitInt8(dwarf::DW_LNS_extended_op);
654         MCOS->emitULEB128IntValue(Size + 1);
655         MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
656         MCOS->emitULEB128IntValue(Discriminator);
657       }
658       if (Isa != Row.Isa) {
659         Isa = Row.Isa;
660         MCOS->emitInt8(dwarf::DW_LNS_set_isa);
661         MCOS->emitULEB128IntValue(Isa);
662       }
663       if (Row.IsStmt != Flags) {
664         Flags = Row.IsStmt;
665         MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
666       }
667       if (Row.BasicBlock)
668         MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
669       if (Row.PrologueEnd)
670         MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
671       if (Row.EpilogueBegin)
672         MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
673 
674       // The end of the sequence is not normal in the middle of the input
675       // sequence, but could happen, e.g. for assembly code.
676       if (Row.EndSequence) {
677         emitEndOfSequence(Address);
678       } else {
679         if (LastAddress == InvalidAddress)
680           emitDwarfSetLineAddrAbs(*MCOS, Params, LineDelta, Address,
681                                   AsmInfo->getCodePointerSize());
682         else
683           MCDwarfLineAddr::Emit(MCOS, Params, LineDelta, Address - LastAddress);
684 
685         LastAddress = Address;
686         LastLine = Row.Line;
687       }
688 
689       Discriminator = 0;
690     }
691     PrevEndOfSequence = Sequence.EndAddress;
692   }
693 
694   // Finish with the end of the sequence.
695   if (LastAddress != InvalidAddress)
696     emitEndOfSequence(PrevEndOfSequence);
697 }
698 
699 // This function is similar to the one from MCDwarfLineTable, except it handles
700 // end-of-sequence entries differently by utilizing line entries with
701 // DWARF2_FLAG_END_SEQUENCE flag.
702 static inline void emitDwarfLineTable(
703     MCStreamer *MCOS, MCSection *Section,
704     const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
705   unsigned FileNum = 1;
706   unsigned LastLine = 1;
707   unsigned Column = 0;
708   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
709   unsigned Isa = 0;
710   unsigned Discriminator = 0;
711   MCSymbol *LastLabel = nullptr;
712   const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo();
713 
714   // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
715   for (const MCDwarfLineEntry &LineEntry : LineEntries) {
716     if (LineEntry.getFlags() & DWARF2_FLAG_END_SEQUENCE) {
717       MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, LineEntry.getLabel(),
718                                      AsmInfo->getCodePointerSize());
719       FileNum = 1;
720       LastLine = 1;
721       Column = 0;
722       Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
723       Isa = 0;
724       Discriminator = 0;
725       LastLabel = nullptr;
726       continue;
727     }
728 
729     int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
730 
731     if (FileNum != LineEntry.getFileNum()) {
732       FileNum = LineEntry.getFileNum();
733       MCOS->emitInt8(dwarf::DW_LNS_set_file);
734       MCOS->emitULEB128IntValue(FileNum);
735     }
736     if (Column != LineEntry.getColumn()) {
737       Column = LineEntry.getColumn();
738       MCOS->emitInt8(dwarf::DW_LNS_set_column);
739       MCOS->emitULEB128IntValue(Column);
740     }
741     if (Discriminator != LineEntry.getDiscriminator() &&
742         MCOS->getContext().getDwarfVersion() >= 4) {
743       Discriminator = LineEntry.getDiscriminator();
744       unsigned Size = getULEB128Size(Discriminator);
745       MCOS->emitInt8(dwarf::DW_LNS_extended_op);
746       MCOS->emitULEB128IntValue(Size + 1);
747       MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
748       MCOS->emitULEB128IntValue(Discriminator);
749     }
750     if (Isa != LineEntry.getIsa()) {
751       Isa = LineEntry.getIsa();
752       MCOS->emitInt8(dwarf::DW_LNS_set_isa);
753       MCOS->emitULEB128IntValue(Isa);
754     }
755     if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
756       Flags = LineEntry.getFlags();
757       MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
758     }
759     if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
760       MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
761     if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
762       MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
763     if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
764       MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
765 
766     MCSymbol *Label = LineEntry.getLabel();
767 
768     // At this point we want to emit/create the sequence to encode the delta
769     // in line numbers and the increment of the address from the previous
770     // Label and the current Label.
771     MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
772                                    AsmInfo->getCodePointerSize());
773     Discriminator = 0;
774     LastLine = LineEntry.getLine();
775     LastLabel = Label;
776   }
777 
778   assert(LastLabel == nullptr && "end of sequence expected");
779 }
780 
781 void DwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
782                             Optional<MCDwarfLineStr> &LineStr,
783                             BinaryContext &BC) const {
784   if (!RawData.empty()) {
785     assert(MCLineSections.getMCLineEntries().empty() &&
786            InputSequences.empty() &&
787            "cannot combine raw data with new line entries");
788     MCOS->emitLabel(getLabel());
789     MCOS->emitBytes(RawData);
790 
791     // Emit fake relocation for RuntimeDyld to always allocate the section.
792     //
793     // FIXME: remove this once RuntimeDyld stops skipping allocatable sections
794     //        without relocations.
795     MCOS->emitRelocDirective(
796         *MCConstantExpr::create(0, *BC.Ctx), "BFD_RELOC_NONE",
797         MCSymbolRefExpr::create(getLabel(), *BC.Ctx), SMLoc(), *BC.STI);
798 
799     return;
800   }
801 
802   MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
803 
804   // Put out the line tables.
805   for (const auto &LineSec : MCLineSections.getMCLineEntries())
806     emitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
807 
808   // Emit line tables for the original code.
809   emitBinaryDwarfLineTable(MCOS, Params, InputTable, InputSequences);
810 
811   // This is the end of the section, so set the value of the symbol at the end
812   // of this section (that was used in a previous expression).
813   MCOS->emitLabel(LineEndSym);
814 }
815 
816 void DwarfLineTable::emit(BinaryContext &BC, MCStreamer &Streamer) {
817   MCAssembler &Assembler =
818       static_cast<MCObjectStreamer *>(&Streamer)->getAssembler();
819 
820   MCDwarfLineTableParams Params = Assembler.getDWARFLinetableParams();
821 
822   auto &LineTables = BC.getDwarfLineTables();
823 
824   // Bail out early so we don't switch to the debug_line section needlessly and
825   // in doing so create an unnecessary (if empty) section.
826   if (LineTables.empty())
827     return;
828 
829   // In a v5 non-split line table, put the strings in a separate section.
830   Optional<MCDwarfLineStr> LineStr(None);
831   if (BC.Ctx->getDwarfVersion() >= 5)
832     LineStr = MCDwarfLineStr(*BC.Ctx);
833 
834   // Switch to the section where the table will be emitted into.
835   Streamer.SwitchSection(BC.MOFI->getDwarfLineSection());
836 
837   // Handle the rest of the Compile Units.
838   for (auto &CUIDTablePair : LineTables) {
839     CUIDTablePair.second.emitCU(&Streamer, Params, LineStr, BC);
840   }
841 }
842 
843 } // namespace bolt
844 } // namespace llvm
845