[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / DWARFLinker / DWARFStreamer.cpp
blob3a9f79e470128bc56eabd9facbebd7c15db4f0ad
1 //===- DwarfStreamer.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 //===----------------------------------------------------------------------===//
9 #include "llvm/DWARFLinker/DWARFStreamer.h"
10 #include "llvm/ADT/Triple.h"
11 #include "llvm/CodeGen/NonRelocatableStringpool.h"
12 #include "llvm/DWARFLinker/DWARFLinkerCompileUnit.h"
13 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCCodeEmitter.h"
16 #include "llvm/MC/MCDwarf.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/MC/MCTargetOptions.h"
23 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Target/TargetOptions.h"
28 namespace llvm {
30 bool DwarfStreamer::init(Triple TheTriple) {
31 std::string ErrorStr;
32 std::string TripleName;
33 StringRef Context = "dwarf streamer init";
35 // Get the target.
36 const Target *TheTarget =
37 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
38 if (!TheTarget)
39 return error(ErrorStr, Context), false;
40 TripleName = TheTriple.getTriple();
42 // Create all the MC Objects.
43 MRI.reset(TheTarget->createMCRegInfo(TripleName));
44 if (!MRI)
45 return error(Twine("no register info for target ") + TripleName, Context),
46 false;
48 MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
49 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
50 if (!MAI)
51 return error("no asm info for target " + TripleName, Context), false;
53 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
54 if (!MSTI)
55 return error("no subtarget info for target " + TripleName, Context), false;
57 MC.reset(new MCContext(TheTriple, MAI.get(), MRI.get(), MSTI.get()));
58 MOFI.reset(TheTarget->createMCObjectFileInfo(*MC, /*PIC=*/false));
59 MC->setObjectFileInfo(MOFI.get());
61 MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
62 if (!MAB)
63 return error("no asm backend for target " + TripleName, Context), false;
65 MII.reset(TheTarget->createMCInstrInfo());
66 if (!MII)
67 return error("no instr info info for target " + TripleName, Context), false;
69 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
70 if (!MCE)
71 return error("no code emitter for target " + TripleName, Context), false;
73 switch (OutFileType) {
74 case OutputFileType::Assembly: {
75 MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(),
76 *MAI, *MII, *MRI);
77 MS = TheTarget->createAsmStreamer(
78 *MC, std::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP,
79 std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB),
80 true);
81 break;
83 case OutputFileType::Object: {
84 MS = TheTarget->createMCObjectStreamer(
85 TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB),
86 MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE),
87 *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
88 /*DWARFMustBeAtTheEnd*/ false);
89 break;
93 if (!MS)
94 return error("no object streamer for target " + TripleName, Context), false;
96 // Finally create the AsmPrinter we'll use to emit the DIEs.
97 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
98 None));
99 if (!TM)
100 return error("no target machine for target " + TripleName, Context), false;
102 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
103 if (!Asm)
104 return error("no asm printer for target " + TripleName, Context), false;
106 RangesSectionSize = 0;
107 LocSectionSize = 0;
108 LineSectionSize = 0;
109 FrameSectionSize = 0;
110 DebugInfoSectionSize = 0;
112 return true;
115 void DwarfStreamer::finish() { MS->Finish(); }
117 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
118 MS->SwitchSection(MOFI->getDwarfInfoSection());
119 MC->setDwarfVersion(DwarfVersion);
122 /// Emit the compilation unit header for \p Unit in the debug_info section.
124 /// A Dwarf 4 section header is encoded as:
125 /// uint32_t Unit length (omitting this field)
126 /// uint16_t Version
127 /// uint32_t Abbreviation table offset
128 /// uint8_t Address size
129 /// Leading to a total of 11 bytes.
131 /// A Dwarf 5 section header is encoded as:
132 /// uint32_t Unit length (omitting this field)
133 /// uint16_t Version
134 /// uint8_t Unit type
135 /// uint8_t Address size
136 /// uint32_t Abbreviation table offset
137 /// Leading to a total of 12 bytes.
138 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit,
139 unsigned DwarfVersion) {
140 switchToDebugInfoSection(DwarfVersion);
142 /// The start of the unit within its section.
143 Unit.setLabelBegin(Asm->createTempSymbol("cu_begin"));
144 Asm->OutStreamer->emitLabel(Unit.getLabelBegin());
146 // Emit size of content not including length itself. The size has already
147 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
148 // account for the length field.
149 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
150 Asm->emitInt16(DwarfVersion);
152 if (DwarfVersion >= 5) {
153 Asm->emitInt8(dwarf::DW_UT_compile);
154 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
155 // We share one abbreviations table across all units so it's always at the
156 // start of the section.
157 Asm->emitInt32(0);
158 DebugInfoSectionSize += 12;
159 } else {
160 // We share one abbreviations table across all units so it's always at the
161 // start of the section.
162 Asm->emitInt32(0);
163 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
164 DebugInfoSectionSize += 11;
167 // Remember this CU.
168 EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()});
171 /// Emit the \p Abbrevs array as the shared abbreviation table
172 /// for the linked Dwarf file.
173 void DwarfStreamer::emitAbbrevs(
174 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
175 unsigned DwarfVersion) {
176 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
177 MC->setDwarfVersion(DwarfVersion);
178 Asm->emitDwarfAbbrevs(Abbrevs);
181 /// Recursively emit the DIE tree rooted at \p Die.
182 void DwarfStreamer::emitDIE(DIE &Die) {
183 MS->SwitchSection(MOFI->getDwarfInfoSection());
184 Asm->emitDwarfDIE(Die);
185 DebugInfoSectionSize += Die.getSize();
188 /// Emit contents of section SecName From Obj.
189 void DwarfStreamer::emitSectionContents(StringRef SecData, StringRef SecName) {
190 MCSection *Section =
191 StringSwitch<MCSection *>(SecName)
192 .Case("debug_line", MC->getObjectFileInfo()->getDwarfLineSection())
193 .Case("debug_loc", MC->getObjectFileInfo()->getDwarfLocSection())
194 .Case("debug_ranges",
195 MC->getObjectFileInfo()->getDwarfRangesSection())
196 .Case("debug_frame", MC->getObjectFileInfo()->getDwarfFrameSection())
197 .Case("debug_aranges",
198 MC->getObjectFileInfo()->getDwarfARangesSection())
199 .Default(nullptr);
201 if (Section) {
202 MS->SwitchSection(Section);
204 MS->emitBytes(SecData);
208 /// Emit DIE containing warnings.
209 void DwarfStreamer::emitPaperTrailWarningsDie(DIE &Die) {
210 switchToDebugInfoSection(/* Version */ 2);
211 auto &Asm = getAsmPrinter();
212 Asm.emitInt32(11 + Die.getSize() - 4);
213 Asm.emitInt16(2);
214 Asm.emitInt32(0);
215 Asm.emitInt8(MC->getTargetTriple().isArch64Bit() ? 8 : 4);
216 DebugInfoSectionSize += 11;
217 emitDIE(Die);
220 /// Emit the debug_str section stored in \p Pool.
221 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
222 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
223 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
224 for (auto Entry : Entries) {
225 // Emit the string itself.
226 Asm->OutStreamer->emitBytes(Entry.getString());
227 // Emit a null terminator.
228 Asm->emitInt8(0);
231 #if 0
232 if (DwarfVersion >= 5) {
233 // Emit an empty string offset section.
234 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrOffSection());
235 Asm->emitDwarfUnitLength(4, "Length of String Offsets Set");
236 Asm->emitInt16(DwarfVersion);
237 Asm->emitInt16(0);
239 #endif
242 void DwarfStreamer::emitDebugNames(
243 AccelTable<DWARF5AccelTableStaticData> &Table) {
244 if (EmittedUnits.empty())
245 return;
247 // Build up data structures needed to emit this section.
248 std::vector<MCSymbol *> CompUnits;
249 DenseMap<unsigned, size_t> UniqueIdToCuMap;
250 unsigned Id = 0;
251 for (auto &CU : EmittedUnits) {
252 CompUnits.push_back(CU.LabelBegin);
253 // We might be omitting CUs, so we need to remap them.
254 UniqueIdToCuMap[CU.ID] = Id++;
257 Asm->OutStreamer->SwitchSection(MOFI->getDwarfDebugNamesSection());
258 emitDWARF5AccelTable(
259 Asm.get(), Table, CompUnits,
260 [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) {
261 return UniqueIdToCuMap[Entry.getCUIndex()];
265 void DwarfStreamer::emitAppleNamespaces(
266 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
267 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamespaceSection());
268 auto *SectionBegin = Asm->createTempSymbol("namespac_begin");
269 Asm->OutStreamer->emitLabel(SectionBegin);
270 emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin);
273 void DwarfStreamer::emitAppleNames(
274 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
275 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamesSection());
276 auto *SectionBegin = Asm->createTempSymbol("names_begin");
277 Asm->OutStreamer->emitLabel(SectionBegin);
278 emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin);
281 void DwarfStreamer::emitAppleObjc(
282 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
283 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelObjCSection());
284 auto *SectionBegin = Asm->createTempSymbol("objc_begin");
285 Asm->OutStreamer->emitLabel(SectionBegin);
286 emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin);
289 void DwarfStreamer::emitAppleTypes(
290 AccelTable<AppleAccelTableStaticTypeData> &Table) {
291 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelTypesSection());
292 auto *SectionBegin = Asm->createTempSymbol("types_begin");
293 Asm->OutStreamer->emitLabel(SectionBegin);
294 emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin);
297 /// Emit the swift_ast section stored in \p Buffers.
298 void DwarfStreamer::emitSwiftAST(StringRef Buffer) {
299 MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
300 SwiftASTSection->setAlignment(Align(32));
301 MS->SwitchSection(SwiftASTSection);
302 MS->emitBytes(Buffer);
305 /// Emit the debug_range section contents for \p FuncRange by
306 /// translating the original \p Entries. The debug_range section
307 /// format is totally trivial, consisting just of pairs of address
308 /// sized addresses describing the ranges.
309 void DwarfStreamer::emitRangesEntries(
310 int64_t UnitPcOffset, uint64_t OrigLowPc,
311 const FunctionIntervals::const_iterator &FuncRange,
312 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
313 unsigned AddressSize) {
314 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
316 // Offset each range by the right amount.
317 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
318 for (const auto &Range : Entries) {
319 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
320 warn("unsupported base address selection operation",
321 "emitting debug_ranges");
322 break;
324 // Do not emit empty ranges.
325 if (Range.StartAddress == Range.EndAddress)
326 continue;
328 // All range entries should lie in the function range.
329 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
330 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
331 warn("inconsistent range data.", "emitting debug_ranges");
332 MS->emitIntValue(Range.StartAddress + PcOffset, AddressSize);
333 MS->emitIntValue(Range.EndAddress + PcOffset, AddressSize);
334 RangesSectionSize += 2 * AddressSize;
337 // Add the terminator entry.
338 MS->emitIntValue(0, AddressSize);
339 MS->emitIntValue(0, AddressSize);
340 RangesSectionSize += 2 * AddressSize;
343 /// Emit the debug_aranges contribution of a unit and
344 /// if \p DoDebugRanges is true the debug_range contents for a
345 /// compile_unit level DW_AT_ranges attribute (Which are basically the
346 /// same thing with a different base address).
347 /// Just aggregate all the ranges gathered inside that unit.
348 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
349 bool DoDebugRanges) {
350 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
351 // Gather the ranges in a vector, so that we can simplify them. The
352 // IntervalMap will have coalesced the non-linked ranges, but here
353 // we want to coalesce the linked addresses.
354 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
355 const auto &FunctionRanges = Unit.getFunctionRanges();
356 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
357 Range != End; ++Range)
358 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
359 Range.stop() + Range.value()));
361 // The object addresses where sorted, but again, the linked
362 // addresses might end up in a different order.
363 llvm::sort(Ranges);
365 if (!Ranges.empty()) {
366 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
368 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
369 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
371 unsigned HeaderSize =
372 sizeof(int32_t) + // Size of contents (w/o this field
373 sizeof(int16_t) + // DWARF ARange version number
374 sizeof(int32_t) + // Offset of CU in the .debug_info section
375 sizeof(int8_t) + // Pointer Size (in bytes)
376 sizeof(int8_t); // Segment Size (in bytes)
378 unsigned TupleSize = AddressSize * 2;
379 unsigned Padding = offsetToAlignment(HeaderSize, Align(TupleSize));
381 Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
382 Asm->OutStreamer->emitLabel(BeginLabel);
383 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
384 Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset
385 Asm->emitInt8(AddressSize); // Address size
386 Asm->emitInt8(0); // Segment size
388 Asm->OutStreamer->emitFill(Padding, 0x0);
390 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
391 ++Range) {
392 uint64_t RangeStart = Range->first;
393 MS->emitIntValue(RangeStart, AddressSize);
394 while ((Range + 1) != End && Range->second == (Range + 1)->first)
395 ++Range;
396 MS->emitIntValue(Range->second - RangeStart, AddressSize);
399 // Emit terminator
400 Asm->OutStreamer->emitIntValue(0, AddressSize);
401 Asm->OutStreamer->emitIntValue(0, AddressSize);
402 Asm->OutStreamer->emitLabel(EndLabel);
405 if (!DoDebugRanges)
406 return;
408 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
409 // Offset each range by the right amount.
410 int64_t PcOffset = -Unit.getLowPc();
411 // Emit coalesced ranges.
412 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
413 MS->emitIntValue(Range->first + PcOffset, AddressSize);
414 while (Range + 1 != End && Range->second == (Range + 1)->first)
415 ++Range;
416 MS->emitIntValue(Range->second + PcOffset, AddressSize);
417 RangesSectionSize += 2 * AddressSize;
420 // Add the terminator entry.
421 MS->emitIntValue(0, AddressSize);
422 MS->emitIntValue(0, AddressSize);
423 RangesSectionSize += 2 * AddressSize;
426 /// Emit location lists for \p Unit and update attributes to point to the new
427 /// entries.
428 void DwarfStreamer::emitLocationsForUnit(
429 const CompileUnit &Unit, DWARFContext &Dwarf,
430 std::function<void(StringRef, SmallVectorImpl<uint8_t> &)> ProcessExpr) {
431 const auto &Attributes = Unit.getLocationAttributes();
433 if (Attributes.empty())
434 return;
436 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
438 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
439 uint64_t BaseAddressMarker = (AddressSize == 8)
440 ? std::numeric_limits<uint64_t>::max()
441 : std::numeric_limits<uint32_t>::max();
442 const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
443 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
444 DWARFUnit &OrigUnit = Unit.getOrigUnit();
445 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
446 int64_t UnitPcOffset = 0;
447 if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
448 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
450 SmallVector<uint8_t, 32> Buffer;
451 for (const auto &Attr : Attributes) {
452 uint64_t Offset = Attr.first.get();
453 Attr.first.set(LocSectionSize);
454 // This is the quantity to add to the old location address to get
455 // the correct address for the new one.
456 int64_t LocPcOffset = Attr.second + UnitPcOffset;
457 while (Data.isValidOffset(Offset)) {
458 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
459 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
460 LocSectionSize += 2 * AddressSize;
461 // End of list entry.
462 if (Low == 0 && High == 0) {
463 Asm->OutStreamer->emitIntValue(0, AddressSize);
464 Asm->OutStreamer->emitIntValue(0, AddressSize);
465 break;
467 // Base address selection entry.
468 if (Low == BaseAddressMarker) {
469 Asm->OutStreamer->emitIntValue(BaseAddressMarker, AddressSize);
470 Asm->OutStreamer->emitIntValue(High + Attr.second, AddressSize);
471 LocPcOffset = 0;
472 continue;
474 // Location list entry.
475 Asm->OutStreamer->emitIntValue(Low + LocPcOffset, AddressSize);
476 Asm->OutStreamer->emitIntValue(High + LocPcOffset, AddressSize);
477 uint64_t Length = Data.getU16(&Offset);
478 Asm->OutStreamer->emitIntValue(Length, 2);
479 // Copy the bytes into to the buffer, process them, emit them.
480 Buffer.reserve(Length);
481 Buffer.resize(0);
482 StringRef Input = InputSec.Data.substr(Offset, Length);
483 ProcessExpr(Input, Buffer);
484 Asm->OutStreamer->emitBytes(
485 StringRef((const char *)Buffer.data(), Length));
486 Offset += Length;
487 LocSectionSize += Length + 2;
492 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
493 StringRef PrologueBytes,
494 unsigned MinInstLength,
495 std::vector<DWARFDebugLine::Row> &Rows,
496 unsigned PointerSize) {
497 // Switch to the section where the table will be emitted into.
498 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
499 MCSymbol *LineStartSym = MC->createTempSymbol();
500 MCSymbol *LineEndSym = MC->createTempSymbol();
502 // The first 4 bytes is the total length of the information for this
503 // compilation unit (not including these 4 bytes for the length).
504 Asm->emitLabelDifference(LineEndSym, LineStartSym, 4);
505 Asm->OutStreamer->emitLabel(LineStartSym);
506 // Copy Prologue.
507 MS->emitBytes(PrologueBytes);
508 LineSectionSize += PrologueBytes.size() + 4;
510 SmallString<128> EncodingBuffer;
511 raw_svector_ostream EncodingOS(EncodingBuffer);
513 if (Rows.empty()) {
514 // We only have the dummy entry, dsymutil emits an entry with a 0
515 // address in that case.
516 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
517 EncodingOS);
518 MS->emitBytes(EncodingOS.str());
519 LineSectionSize += EncodingBuffer.size();
520 MS->emitLabel(LineEndSym);
521 return;
524 // Line table state machine fields
525 unsigned FileNum = 1;
526 unsigned LastLine = 1;
527 unsigned Column = 0;
528 unsigned IsStatement = 1;
529 unsigned Isa = 0;
530 uint64_t Address = -1ULL;
532 unsigned RowsSinceLastSequence = 0;
534 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
535 auto &Row = Rows[Idx];
537 int64_t AddressDelta;
538 if (Address == -1ULL) {
539 MS->emitIntValue(dwarf::DW_LNS_extended_op, 1);
540 MS->emitULEB128IntValue(PointerSize + 1);
541 MS->emitIntValue(dwarf::DW_LNE_set_address, 1);
542 MS->emitIntValue(Row.Address.Address, PointerSize);
543 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
544 AddressDelta = 0;
545 } else {
546 AddressDelta = (Row.Address.Address - Address) / MinInstLength;
549 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
550 // We should find a way to share this code, but the current compatibility
551 // requirement with classic dsymutil makes it hard. Revisit that once this
552 // requirement is dropped.
554 if (FileNum != Row.File) {
555 FileNum = Row.File;
556 MS->emitIntValue(dwarf::DW_LNS_set_file, 1);
557 MS->emitULEB128IntValue(FileNum);
558 LineSectionSize += 1 + getULEB128Size(FileNum);
560 if (Column != Row.Column) {
561 Column = Row.Column;
562 MS->emitIntValue(dwarf::DW_LNS_set_column, 1);
563 MS->emitULEB128IntValue(Column);
564 LineSectionSize += 1 + getULEB128Size(Column);
567 // FIXME: We should handle the discriminator here, but dsymutil doesn't
568 // consider it, thus ignore it for now.
570 if (Isa != Row.Isa) {
571 Isa = Row.Isa;
572 MS->emitIntValue(dwarf::DW_LNS_set_isa, 1);
573 MS->emitULEB128IntValue(Isa);
574 LineSectionSize += 1 + getULEB128Size(Isa);
576 if (IsStatement != Row.IsStmt) {
577 IsStatement = Row.IsStmt;
578 MS->emitIntValue(dwarf::DW_LNS_negate_stmt, 1);
579 LineSectionSize += 1;
581 if (Row.BasicBlock) {
582 MS->emitIntValue(dwarf::DW_LNS_set_basic_block, 1);
583 LineSectionSize += 1;
586 if (Row.PrologueEnd) {
587 MS->emitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
588 LineSectionSize += 1;
591 if (Row.EpilogueBegin) {
592 MS->emitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
593 LineSectionSize += 1;
596 int64_t LineDelta = int64_t(Row.Line) - LastLine;
597 if (!Row.EndSequence) {
598 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
599 MS->emitBytes(EncodingOS.str());
600 LineSectionSize += EncodingBuffer.size();
601 EncodingBuffer.resize(0);
602 Address = Row.Address.Address;
603 LastLine = Row.Line;
604 RowsSinceLastSequence++;
605 } else {
606 if (LineDelta) {
607 MS->emitIntValue(dwarf::DW_LNS_advance_line, 1);
608 MS->emitSLEB128IntValue(LineDelta);
609 LineSectionSize += 1 + getSLEB128Size(LineDelta);
611 if (AddressDelta) {
612 MS->emitIntValue(dwarf::DW_LNS_advance_pc, 1);
613 MS->emitULEB128IntValue(AddressDelta);
614 LineSectionSize += 1 + getULEB128Size(AddressDelta);
616 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
617 0, EncodingOS);
618 MS->emitBytes(EncodingOS.str());
619 LineSectionSize += EncodingBuffer.size();
620 EncodingBuffer.resize(0);
621 Address = -1ULL;
622 LastLine = FileNum = IsStatement = 1;
623 RowsSinceLastSequence = Column = Isa = 0;
627 if (RowsSinceLastSequence) {
628 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
629 EncodingOS);
630 MS->emitBytes(EncodingOS.str());
631 LineSectionSize += EncodingBuffer.size();
632 EncodingBuffer.resize(0);
635 MS->emitLabel(LineEndSym);
638 /// Copy the debug_line over to the updated binary while unobfuscating the file
639 /// names and directories.
640 void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) {
641 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
642 StringRef Contents = Data.getData();
644 // We have to deconstruct the line table header, because it contains to
645 // length fields that will need to be updated when we change the length of
646 // the files and directories in there.
647 unsigned UnitLength = Data.getU32(&Offset);
648 uint64_t UnitEnd = Offset + UnitLength;
649 MCSymbol *BeginLabel = MC->createTempSymbol();
650 MCSymbol *EndLabel = MC->createTempSymbol();
651 unsigned Version = Data.getU16(&Offset);
653 if (Version > 5) {
654 warn("Unsupported line table version: dropping contents and not "
655 "unobfsucating line table.");
656 return;
659 Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
660 Asm->OutStreamer->emitLabel(BeginLabel);
661 Asm->emitInt16(Version);
662 LineSectionSize += 6;
664 MCSymbol *HeaderBeginLabel = MC->createTempSymbol();
665 MCSymbol *HeaderEndLabel = MC->createTempSymbol();
666 Asm->emitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
667 Asm->OutStreamer->emitLabel(HeaderBeginLabel);
668 Offset += 4;
669 LineSectionSize += 4;
671 uint64_t AfterHeaderLengthOffset = Offset;
672 // Skip to the directories.
673 Offset += (Version >= 4) ? 5 : 4;
674 unsigned OpcodeBase = Data.getU8(&Offset);
675 Offset += OpcodeBase - 1;
676 Asm->OutStreamer->emitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
677 LineSectionSize += Offset - AfterHeaderLengthOffset;
679 // Offset points to the first directory.
680 while (const char *Dir = Data.getCStr(&Offset)) {
681 if (Dir[0] == 0)
682 break;
684 StringRef Translated = Translator(Dir);
685 Asm->OutStreamer->emitBytes(Translated);
686 Asm->emitInt8(0);
687 LineSectionSize += Translated.size() + 1;
689 Asm->emitInt8(0);
690 LineSectionSize += 1;
692 while (const char *File = Data.getCStr(&Offset)) {
693 if (File[0] == 0)
694 break;
696 StringRef Translated = Translator(File);
697 Asm->OutStreamer->emitBytes(Translated);
698 Asm->emitInt8(0);
699 LineSectionSize += Translated.size() + 1;
701 uint64_t OffsetBeforeLEBs = Offset;
702 Asm->emitULEB128(Data.getULEB128(&Offset));
703 Asm->emitULEB128(Data.getULEB128(&Offset));
704 Asm->emitULEB128(Data.getULEB128(&Offset));
705 LineSectionSize += Offset - OffsetBeforeLEBs;
707 Asm->emitInt8(0);
708 LineSectionSize += 1;
710 Asm->OutStreamer->emitLabel(HeaderEndLabel);
712 // Copy the actual line table program over.
713 Asm->OutStreamer->emitBytes(Contents.slice(Offset, UnitEnd));
714 LineSectionSize += UnitEnd - Offset;
716 Asm->OutStreamer->emitLabel(EndLabel);
717 Offset = UnitEnd;
720 /// Emit the pubnames or pubtypes section contribution for \p
721 /// Unit into \p Sec. The data is provided in \p Names.
722 void DwarfStreamer::emitPubSectionForUnit(
723 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
724 const std::vector<CompileUnit::AccelInfo> &Names) {
725 if (Names.empty())
726 return;
728 // Start the dwarf pubnames section.
729 Asm->OutStreamer->SwitchSection(Sec);
730 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
731 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
733 bool HeaderEmitted = false;
734 // Emit the pubnames for this compilation unit.
735 for (const auto &Name : Names) {
736 if (Name.SkipPubSection)
737 continue;
739 if (!HeaderEmitted) {
740 // Emit the header.
741 Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Length
742 Asm->OutStreamer->emitLabel(BeginLabel);
743 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
744 Asm->emitInt32(Unit.getStartOffset()); // Unit offset
745 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
746 HeaderEmitted = true;
748 Asm->emitInt32(Name.Die->getOffset());
750 // Emit the string itself.
751 Asm->OutStreamer->emitBytes(Name.Name.getString());
752 // Emit a null terminator.
753 Asm->emitInt8(0);
756 if (!HeaderEmitted)
757 return;
758 Asm->emitInt32(0); // End marker.
759 Asm->OutStreamer->emitLabel(EndLabel);
762 /// Emit .debug_pubnames for \p Unit.
763 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
764 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
765 "names", Unit, Unit.getPubnames());
768 /// Emit .debug_pubtypes for \p Unit.
769 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
770 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
771 "types", Unit, Unit.getPubtypes());
774 /// Emit a CIE into the debug_frame section.
775 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
776 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
778 MS->emitBytes(CIEBytes);
779 FrameSectionSize += CIEBytes.size();
782 /// Emit a FDE into the debug_frame section. \p FDEBytes
783 /// contains the FDE data without the length, CIE offset and address
784 /// which will be replaced with the parameter values.
785 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
786 uint32_t Address, StringRef FDEBytes) {
787 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
789 MS->emitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
790 MS->emitIntValue(CIEOffset, 4);
791 MS->emitIntValue(Address, AddrSize);
792 MS->emitBytes(FDEBytes);
793 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
796 } // namespace llvm