LLVM 18.0.0git
DWARFStreamer.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
8
16#include "llvm/MC/MCDwarf.h"
18#include "llvm/MC/MCSection.h"
19#include "llvm/MC/MCStreamer.h"
25#include "llvm/Support/LEB128.h"
28
29namespace llvm {
30
32 StringRef Swift5ReflectionSegmentName) {
33 std::string ErrorStr;
34 std::string TripleName;
35
36 // Get the target.
37 const Target *TheTarget =
38 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
39 if (!TheTarget)
40 return createStringError(std::errc::invalid_argument, ErrorStr.c_str());
41
42 TripleName = TheTriple.getTriple();
43
44 // Create all the MC Objects.
45 MRI.reset(TheTarget->createMCRegInfo(TripleName));
46 if (!MRI)
47 return createStringError(std::errc::invalid_argument,
48 "no register info for target %s",
49 TripleName.c_str());
50
52 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
53 if (!MAI)
54 return createStringError(std::errc::invalid_argument,
55 "no asm info for target %s", TripleName.c_str());
56
57 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
58 if (!MSTI)
59 return createStringError(std::errc::invalid_argument,
60 "no subtarget info for target %s",
61 TripleName.c_str());
62
63 MC.reset(new MCContext(TheTriple, MAI.get(), MRI.get(), MSTI.get(), nullptr,
64 nullptr, true, Swift5ReflectionSegmentName));
65 MOFI.reset(TheTarget->createMCObjectFileInfo(*MC, /*PIC=*/false, false));
66 MC->setObjectFileInfo(MOFI.get());
67
68 MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
69 if (!MAB)
70 return createStringError(std::errc::invalid_argument,
71 "no asm backend for target %s",
72 TripleName.c_str());
73
74 MII.reset(TheTarget->createMCInstrInfo());
75 if (!MII)
76 return createStringError(std::errc::invalid_argument,
77 "no instr info info for target %s",
78 TripleName.c_str());
79
80 MCE = TheTarget->createMCCodeEmitter(*MII, *MC);
81 if (!MCE)
82 return createStringError(std::errc::invalid_argument,
83 "no code emitter for target %s",
84 TripleName.c_str());
85
86 switch (OutFileType) {
88 MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(),
89 *MAI, *MII, *MRI);
90 MS = TheTarget->createAsmStreamer(
91 *MC, std::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP,
92 std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB),
93 true);
94 break;
95 }
97 MS = TheTarget->createMCObjectStreamer(
98 TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB),
99 MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE),
100 *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
101 /*DWARFMustBeAtTheEnd*/ false);
102 break;
103 }
104 }
105
106 if (!MS)
107 return createStringError(std::errc::invalid_argument,
108 "no object streamer for target %s",
109 TripleName.c_str());
110
111 // Finally create the AsmPrinter we'll use to emit the DIEs.
112 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
113 std::nullopt));
114 if (!TM)
115 return createStringError(std::errc::invalid_argument,
116 "no target machine for target %s",
117 TripleName.c_str());
118
119 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
120 if (!Asm)
121 return createStringError(std::errc::invalid_argument,
122 "no asm printer for target %s",
123 TripleName.c_str());
124 Asm->setDwarfUsesRelocationsAcrossSections(false);
125
126 RangesSectionSize = 0;
127 RngListsSectionSize = 0;
128 LocSectionSize = 0;
129 LocListsSectionSize = 0;
130 LineSectionSize = 0;
131 FrameSectionSize = 0;
132 DebugInfoSectionSize = 0;
133 MacInfoSectionSize = 0;
134 MacroSectionSize = 0;
135
136 return Error::success();
137}
138
140
141void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
142 MS->switchSection(MOFI->getDwarfInfoSection());
143 MC->setDwarfVersion(DwarfVersion);
144}
145
146/// Emit the compilation unit header for \p Unit in the debug_info section.
147///
148/// A Dwarf 4 section header is encoded as:
149/// uint32_t Unit length (omitting this field)
150/// uint16_t Version
151/// uint32_t Abbreviation table offset
152/// uint8_t Address size
153/// Leading to a total of 11 bytes.
154///
155/// A Dwarf 5 section header is encoded as:
156/// uint32_t Unit length (omitting this field)
157/// uint16_t Version
158/// uint8_t Unit type
159/// uint8_t Address size
160/// uint32_t Abbreviation table offset
161/// Leading to a total of 12 bytes.
163 unsigned DwarfVersion) {
164 switchToDebugInfoSection(DwarfVersion);
165
166 /// The start of the unit within its section.
167 Unit.setLabelBegin(Asm->createTempSymbol("cu_begin"));
168 Asm->OutStreamer->emitLabel(Unit.getLabelBegin());
169
170 // Emit size of content not including length itself. The size has already
171 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
172 // account for the length field.
173 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
174 Asm->emitInt16(DwarfVersion);
175
176 if (DwarfVersion >= 5) {
177 Asm->emitInt8(dwarf::DW_UT_compile);
178 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
179 // We share one abbreviations table across all units so it's always at the
180 // start of the section.
181 Asm->emitInt32(0);
182 DebugInfoSectionSize += 12;
183 } else {
184 // We share one abbreviations table across all units so it's always at the
185 // start of the section.
186 Asm->emitInt32(0);
187 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
188 DebugInfoSectionSize += 11;
189 }
190
191 // Remember this CU.
192 EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()});
193}
194
195/// Emit the \p Abbrevs array as the shared abbreviation table
196/// for the linked Dwarf file.
198 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
199 unsigned DwarfVersion) {
200 MS->switchSection(MOFI->getDwarfAbbrevSection());
201 MC->setDwarfVersion(DwarfVersion);
202 Asm->emitDwarfAbbrevs(Abbrevs);
203}
204
205/// Recursively emit the DIE tree rooted at \p Die.
207 MS->switchSection(MOFI->getDwarfInfoSection());
208 Asm->emitDwarfDIE(Die);
209 DebugInfoSectionSize += Die.getSize();
210}
211
212/// Emit contents of section SecName From Obj.
214 MCSection *Section =
216 .Case("debug_line", MC->getObjectFileInfo()->getDwarfLineSection())
217 .Case("debug_loc", MC->getObjectFileInfo()->getDwarfLocSection())
218 .Case("debug_ranges",
219 MC->getObjectFileInfo()->getDwarfRangesSection())
220 .Case("debug_frame", MC->getObjectFileInfo()->getDwarfFrameSection())
221 .Case("debug_aranges",
222 MC->getObjectFileInfo()->getDwarfARangesSection())
223 .Case("debug_addr", MC->getObjectFileInfo()->getDwarfAddrSection())
224 .Case("debug_rnglists",
225 MC->getObjectFileInfo()->getDwarfRnglistsSection())
226 .Case("debug_loclists",
227 MC->getObjectFileInfo()->getDwarfLoclistsSection())
228 .Default(nullptr);
229
230 if (Section) {
231 MS->switchSection(Section);
232
233 MS->emitBytes(SecData);
234 }
235}
236
237/// Emit the debug_str section stored in \p Pool.
239 Asm->OutStreamer->switchSection(MOFI->getDwarfStrSection());
240 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
241 for (auto Entry : Entries) {
242 // Emit the string itself.
243 Asm->OutStreamer->emitBytes(Entry.getString());
244 // Emit a null terminator.
245 Asm->emitInt8(0);
246 }
247}
248
249/// Emit the debug string offset table described by \p StringOffsets into the
250/// .debug_str_offsets table.
252 const SmallVector<uint64_t> &StringOffsets, uint16_t TargetDWARFVersion) {
253
254 if (TargetDWARFVersion < 5 || StringOffsets.empty())
255 return;
256
257 Asm->OutStreamer->switchSection(MOFI->getDwarfStrOffSection());
258
259 MCSymbol *BeginLabel = Asm->createTempSymbol("Bdebugstroff");
260 MCSymbol *EndLabel = Asm->createTempSymbol("Edebugstroff");
261
262 // Length.
263 Asm->emitLabelDifference(EndLabel, BeginLabel, sizeof(uint32_t));
264 Asm->OutStreamer->emitLabel(BeginLabel);
265 StrOffsetSectionSize += sizeof(uint32_t);
266
267 // Version.
268 MS->emitInt16(5);
269 StrOffsetSectionSize += sizeof(uint16_t);
270
271 // Padding.
272 MS->emitInt16(0);
273 StrOffsetSectionSize += sizeof(uint16_t);
274
275 for (auto Off : StringOffsets) {
276 Asm->OutStreamer->emitInt32(Off);
277 StrOffsetSectionSize += sizeof(uint32_t);
278 }
279 Asm->OutStreamer->emitLabel(EndLabel);
280}
281
282/// Emit the debug_line_str section stored in \p Pool.
284 Asm->OutStreamer->switchSection(MOFI->getDwarfLineStrSection());
285 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
286 for (auto Entry : Entries) {
287 // Emit the string itself.
288 Asm->OutStreamer->emitBytes(Entry.getString());
289 // Emit a null terminator.
290 Asm->emitInt8(0);
291 }
292}
293
296 if (EmittedUnits.empty())
297 return;
298
299 // Build up data structures needed to emit this section.
300 std::vector<std::variant<MCSymbol *, uint64_t>> CompUnits;
301 DenseMap<unsigned, size_t> UniqueIdToCuMap;
302 unsigned Id = 0;
303 for (auto &CU : EmittedUnits) {
304 CompUnits.push_back(CU.LabelBegin);
305 // We might be omitting CUs, so we need to remap them.
306 UniqueIdToCuMap[CU.ID] = Id++;
307 }
308
309 Asm->OutStreamer->switchSection(MOFI->getDwarfDebugNamesSection());
311 Asm.get(), Table, CompUnits,
312 [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) {
313 return UniqueIdToCuMap[Entry.getCUIndex()];
314 });
315}
316
319 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelNamespaceSection());
320 auto *SectionBegin = Asm->createTempSymbol("namespac_begin");
321 Asm->OutStreamer->emitLabel(SectionBegin);
322 emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin);
323}
324
327 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelNamesSection());
328 auto *SectionBegin = Asm->createTempSymbol("names_begin");
329 Asm->OutStreamer->emitLabel(SectionBegin);
330 emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin);
331}
332
335 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelObjCSection());
336 auto *SectionBegin = Asm->createTempSymbol("objc_begin");
337 Asm->OutStreamer->emitLabel(SectionBegin);
338 emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin);
339}
340
343 Asm->OutStreamer->switchSection(MOFI->getDwarfAccelTypesSection());
344 auto *SectionBegin = Asm->createTempSymbol("types_begin");
345 Asm->OutStreamer->emitLabel(SectionBegin);
346 emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin);
347}
348
349/// Emit the swift_ast section stored in \p Buffers.
351 MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
352 SwiftASTSection->setAlignment(Align(32));
353 MS->switchSection(SwiftASTSection);
354 MS->emitBytes(Buffer);
355}
356
359 StringRef Buffer, uint32_t Alignment, uint32_t Size) {
360 MCSection *ReflectionSection =
361 MOFI->getSwift5ReflectionSection(ReflSectionKind);
362 if (ReflectionSection == nullptr)
363 return;
364 ReflectionSection->setAlignment(Align(Alignment));
365 MS->switchSection(ReflectionSection);
366 MS->emitBytes(Buffer);
367}
368
370 const CompileUnit &Unit, const AddressRanges &LinkedRanges) {
371 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
372
373 // Make .debug_aranges to be current section.
374 MS->switchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
375
376 // Emit Header.
377 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
378 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
379
380 unsigned HeaderSize =
381 sizeof(int32_t) + // Size of contents (w/o this field
382 sizeof(int16_t) + // DWARF ARange version number
383 sizeof(int32_t) + // Offset of CU in the .debug_info section
384 sizeof(int8_t) + // Pointer Size (in bytes)
385 sizeof(int8_t); // Segment Size (in bytes)
386
387 unsigned TupleSize = AddressSize * 2;
388 unsigned Padding = offsetToAlignment(HeaderSize, Align(TupleSize));
389
390 Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
391 Asm->OutStreamer->emitLabel(BeginLabel);
392 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
393 Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset
394 Asm->emitInt8(AddressSize); // Address size
395 Asm->emitInt8(0); // Segment size
396
397 Asm->OutStreamer->emitFill(Padding, 0x0);
398
399 // Emit linked ranges.
400 for (const AddressRange &Range : LinkedRanges) {
401 MS->emitIntValue(Range.start(), AddressSize);
402 MS->emitIntValue(Range.end() - Range.start(), AddressSize);
403 }
404
405 // Emit terminator.
406 Asm->OutStreamer->emitIntValue(0, AddressSize);
407 Asm->OutStreamer->emitIntValue(0, AddressSize);
408 Asm->OutStreamer->emitLabel(EndLabel);
409}
410
411void DwarfStreamer::emitDwarfDebugRangesTableFragment(
412 const CompileUnit &Unit, const AddressRanges &LinkedRanges,
413 PatchLocation Patch) {
414 Patch.set(RangesSectionSize);
415
416 // Make .debug_ranges to be current section.
417 MS->switchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
418 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
419
420 // Emit ranges.
421 uint64_t BaseAddress = 0;
422 if (std::optional<uint64_t> LowPC = Unit.getLowPc())
423 BaseAddress = *LowPC;
424
425 for (const AddressRange &Range : LinkedRanges) {
426 MS->emitIntValue(Range.start() - BaseAddress, AddressSize);
427 MS->emitIntValue(Range.end() - BaseAddress, AddressSize);
428
429 RangesSectionSize += AddressSize;
430 RangesSectionSize += AddressSize;
431 }
432
433 // Add the terminator entry.
434 MS->emitIntValue(0, AddressSize);
435 MS->emitIntValue(0, AddressSize);
436
437 RangesSectionSize += AddressSize;
438 RangesSectionSize += AddressSize;
439}
440
441MCSymbol *
443 if (Unit.getOrigUnit().getVersion() < 5)
444 return nullptr;
445
446 // Make .debug_rnglists to be current section.
447 MS->switchSection(MC->getObjectFileInfo()->getDwarfRnglistsSection());
448
449 MCSymbol *BeginLabel = Asm->createTempSymbol("Brnglists");
450 MCSymbol *EndLabel = Asm->createTempSymbol("Ernglists");
451 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
452
453 // Length
454 Asm->emitLabelDifference(EndLabel, BeginLabel, sizeof(uint32_t));
455 Asm->OutStreamer->emitLabel(BeginLabel);
456 RngListsSectionSize += sizeof(uint32_t);
457
458 // Version.
459 MS->emitInt16(5);
460 RngListsSectionSize += sizeof(uint16_t);
461
462 // Address size.
463 MS->emitInt8(AddressSize);
464 RngListsSectionSize++;
465
466 // Seg_size
467 MS->emitInt8(0);
468 RngListsSectionSize++;
469
470 // Offset entry count
471 MS->emitInt32(0);
472 RngListsSectionSize += sizeof(uint32_t);
473
474 return EndLabel;
475}
476
478 const CompileUnit &Unit, const AddressRanges &LinkedRanges,
479 PatchLocation Patch, DebugDieValuePool &AddrPool) {
480 if (Unit.getOrigUnit().getVersion() < 5) {
481 emitDwarfDebugRangesTableFragment(Unit, LinkedRanges, Patch);
482 return;
483 }
484
485 emitDwarfDebugRngListsTableFragment(Unit, LinkedRanges, Patch, AddrPool);
486}
487
489 MCSymbol *EndLabel) {
490 if (Unit.getOrigUnit().getVersion() < 5)
491 return;
492
493 // Make .debug_rnglists to be current section.
494 MS->switchSection(MC->getObjectFileInfo()->getDwarfRnglistsSection());
495
496 if (EndLabel != nullptr)
497 Asm->OutStreamer->emitLabel(EndLabel);
498}
499
500void DwarfStreamer::emitDwarfDebugRngListsTableFragment(
501 const CompileUnit &Unit, const AddressRanges &LinkedRanges,
502 PatchLocation Patch, DebugDieValuePool &AddrPool) {
503 Patch.set(RngListsSectionSize);
504
505 // Make .debug_rnglists to be current section.
506 MS->switchSection(MC->getObjectFileInfo()->getDwarfRnglistsSection());
507 std::optional<uint64_t> BaseAddress;
508
509 for (const AddressRange &Range : LinkedRanges) {
510
511 if (!BaseAddress) {
512 BaseAddress = Range.start();
513
514 // Emit base address.
515 MS->emitInt8(dwarf::DW_RLE_base_addressx);
516 RngListsSectionSize += 1;
517 RngListsSectionSize +=
518 MS->emitULEB128IntValue(AddrPool.getValueIndex(*BaseAddress));
519 }
520
521 // Emit type of entry.
522 MS->emitInt8(dwarf::DW_RLE_offset_pair);
523 RngListsSectionSize += 1;
524
525 // Emit start offset relative to base address.
526 RngListsSectionSize +=
527 MS->emitULEB128IntValue(Range.start() - *BaseAddress);
528
529 // Emit end offset relative to base address.
530 RngListsSectionSize += MS->emitULEB128IntValue(Range.end() - *BaseAddress);
531 }
532
533 // Emit the terminator entry.
534 MS->emitInt8(dwarf::DW_RLE_end_of_list);
535 RngListsSectionSize += 1;
536}
537
538/// Emit debug locations(.debug_loc, .debug_loclists) header.
540 if (Unit.getOrigUnit().getVersion() < 5)
541 return nullptr;
542
543 // Make .debug_loclists the current section.
544 MS->switchSection(MC->getObjectFileInfo()->getDwarfLoclistsSection());
545
546 MCSymbol *BeginLabel = Asm->createTempSymbol("Bloclists");
547 MCSymbol *EndLabel = Asm->createTempSymbol("Eloclists");
548 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
549
550 // Length
551 Asm->emitLabelDifference(EndLabel, BeginLabel, sizeof(uint32_t));
552 Asm->OutStreamer->emitLabel(BeginLabel);
553 LocListsSectionSize += sizeof(uint32_t);
554
555 // Version.
556 MS->emitInt16(5);
557 LocListsSectionSize += sizeof(uint16_t);
558
559 // Address size.
560 MS->emitInt8(AddressSize);
561 LocListsSectionSize++;
562
563 // Seg_size
564 MS->emitInt8(0);
565 LocListsSectionSize++;
566
567 // Offset entry count
568 MS->emitInt32(0);
569 LocListsSectionSize += sizeof(uint32_t);
570
571 return EndLabel;
572}
573
574/// Emit debug locations(.debug_loc, .debug_loclists) fragment.
576 const CompileUnit &Unit,
577 const DWARFLocationExpressionsVector &LinkedLocationExpression,
578 PatchLocation Patch, DebugDieValuePool &AddrPool) {
579 if (Unit.getOrigUnit().getVersion() < 5) {
580 emitDwarfDebugLocTableFragment(Unit, LinkedLocationExpression, Patch);
581 return;
582 }
583
584 emitDwarfDebugLocListsTableFragment(Unit, LinkedLocationExpression, Patch,
585 AddrPool);
586}
587
588/// Emit debug locations(.debug_loc, .debug_loclists) footer.
590 MCSymbol *EndLabel) {
591 if (Unit.getOrigUnit().getVersion() < 5)
592 return;
593
594 // Make .debug_loclists the current section.
595 MS->switchSection(MC->getObjectFileInfo()->getDwarfLoclistsSection());
596
597 if (EndLabel != nullptr)
598 Asm->OutStreamer->emitLabel(EndLabel);
599}
600
601/// Emit piece of .debug_loc for \p LinkedLocationExpression.
602void DwarfStreamer::emitDwarfDebugLocTableFragment(
603 const CompileUnit &Unit,
604 const DWARFLocationExpressionsVector &LinkedLocationExpression,
605 PatchLocation Patch) {
606 Patch.set(LocSectionSize);
607
608 // Make .debug_loc to be current section.
609 MS->switchSection(MC->getObjectFileInfo()->getDwarfLocSection());
610 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
611
612 // Emit ranges.
613 uint64_t BaseAddress = 0;
614 if (std::optional<uint64_t> LowPC = Unit.getLowPc())
615 BaseAddress = *LowPC;
616
617 for (const DWARFLocationExpression &LocExpression :
618 LinkedLocationExpression) {
619 if (LocExpression.Range) {
620 MS->emitIntValue(LocExpression.Range->LowPC - BaseAddress, AddressSize);
621 MS->emitIntValue(LocExpression.Range->HighPC - BaseAddress, AddressSize);
622
623 LocSectionSize += AddressSize;
624 LocSectionSize += AddressSize;
625 }
626
627 Asm->OutStreamer->emitIntValue(LocExpression.Expr.size(), 2);
628 Asm->OutStreamer->emitBytes(StringRef(
629 (const char *)LocExpression.Expr.data(), LocExpression.Expr.size()));
630 LocSectionSize += LocExpression.Expr.size() + 2;
631 }
632
633 // Add the terminator entry.
634 MS->emitIntValue(0, AddressSize);
635 MS->emitIntValue(0, AddressSize);
636
637 LocSectionSize += AddressSize;
638 LocSectionSize += AddressSize;
639}
640
641/// Emit .debug_addr header.
643
644 // Make .debug_addr the current section.
645 MS->switchSection(MC->getObjectFileInfo()->getDwarfAddrSection());
646
647 MCSymbol *BeginLabel = Asm->createTempSymbol("Bdebugaddr");
648 MCSymbol *EndLabel = Asm->createTempSymbol("Edebugaddr");
649 unsigned AddrSize = Unit.getOrigUnit().getAddressByteSize();
650
651 // Emit length.
652 Asm->emitLabelDifference(EndLabel, BeginLabel, sizeof(uint32_t));
653 Asm->OutStreamer->emitLabel(BeginLabel);
654 AddrSectionSize += sizeof(uint32_t);
655
656 // Emit version.
657 Asm->emitInt16(5);
658 AddrSectionSize += 2;
659
660 // Emit address size.
661 Asm->emitInt8(AddrSize);
662 AddrSectionSize += 1;
663
664 // Emit segment size.
665 Asm->emitInt8(0);
666 AddrSectionSize += 1;
667
668 return EndLabel;
669}
670
671/// Emit the .debug_addr addresses stored in \p Addrs.
673 uint8_t AddrSize) {
674 Asm->OutStreamer->switchSection(MOFI->getDwarfAddrSection());
675 for (auto Addr : Addrs) {
676 Asm->OutStreamer->emitIntValue(Addr, AddrSize);
677 AddrSectionSize += AddrSize;
678 }
679}
680
681/// Emit .debug_addr footer.
683 MCSymbol *EndLabel) {
684
685 // Make .debug_addr the current section.
686 MS->switchSection(MC->getObjectFileInfo()->getDwarfAddrSection());
687
688 if (EndLabel != nullptr)
689 Asm->OutStreamer->emitLabel(EndLabel);
690}
691
692/// Emit piece of .debug_loclists for \p LinkedLocationExpression.
693void DwarfStreamer::emitDwarfDebugLocListsTableFragment(
694 const CompileUnit &Unit,
695 const DWARFLocationExpressionsVector &LinkedLocationExpression,
696 PatchLocation Patch, DebugDieValuePool &AddrPool) {
697 Patch.set(LocListsSectionSize);
698
699 // Make .debug_loclists the current section.
700 MS->switchSection(MC->getObjectFileInfo()->getDwarfLoclistsSection());
701 std::optional<uint64_t> BaseAddress;
702
703 for (const DWARFLocationExpression &LocExpression :
704 LinkedLocationExpression) {
705 if (LocExpression.Range) {
706
707 if (!BaseAddress) {
708
709 BaseAddress = LocExpression.Range->LowPC;
710
711 // Emit base address.
712 MS->emitInt8(dwarf::DW_LLE_base_addressx);
713 LocListsSectionSize += 1;
714 LocListsSectionSize +=
715 MS->emitULEB128IntValue(AddrPool.getValueIndex(*BaseAddress));
716 }
717
718 // Emit type of entry.
719 MS->emitInt8(dwarf::DW_LLE_offset_pair);
720 LocListsSectionSize += 1;
721
722 // Emit start offset relative to base address.
723 LocListsSectionSize +=
724 MS->emitULEB128IntValue(LocExpression.Range->LowPC - *BaseAddress);
725
726 // Emit end offset relative to base address.
727 LocListsSectionSize +=
728 MS->emitULEB128IntValue(LocExpression.Range->HighPC - *BaseAddress);
729 } else {
730 // Emit type of entry.
731 MS->emitInt8(dwarf::DW_LLE_default_location);
732 LocListsSectionSize += 1;
733 }
734
735 LocListsSectionSize += MS->emitULEB128IntValue(LocExpression.Expr.size());
736 Asm->OutStreamer->emitBytes(StringRef(
737 (const char *)LocExpression.Expr.data(), LocExpression.Expr.size()));
738 LocListsSectionSize += LocExpression.Expr.size();
739 }
740
741 // Emit the terminator entry.
742 MS->emitInt8(dwarf::DW_LLE_end_of_list);
743 LocListsSectionSize += 1;
744}
745
747 const DWARFDebugLine::LineTable &LineTable, const CompileUnit &Unit,
748 OffsetsStringPool &DebugStrPool, OffsetsStringPool &DebugLineStrPool) {
749 // Switch to the section where the table will be emitted into.
750 MS->switchSection(MC->getObjectFileInfo()->getDwarfLineSection());
751
752 MCSymbol *LineStartSym = MC->createTempSymbol();
753 MCSymbol *LineEndSym = MC->createTempSymbol();
754
755 // unit_length.
758 LineSectionSize += 4;
759 }
760 emitLabelDifference(LineEndSym, LineStartSym,
761 LineTable.Prologue.FormParams.Format, LineSectionSize);
762 Asm->OutStreamer->emitLabel(LineStartSym);
763
764 // Emit prologue.
765 emitLineTablePrologue(LineTable.Prologue, DebugStrPool, DebugLineStrPool);
766
767 // Emit rows.
768 emitLineTableRows(LineTable, LineEndSym,
769 Unit.getOrigUnit().getAddressByteSize());
770}
771
772void DwarfStreamer::emitLineTablePrologue(const DWARFDebugLine::Prologue &P,
773 OffsetsStringPool &DebugStrPool,
774 OffsetsStringPool &DebugLineStrPool) {
775 MCSymbol *PrologueStartSym = MC->createTempSymbol();
776 MCSymbol *PrologueEndSym = MC->createTempSymbol();
777
778 // version (uhalf).
779 MS->emitInt16(P.getVersion());
780 LineSectionSize += 2;
781 if (P.getVersion() == 5) {
782 // address_size (ubyte).
783 MS->emitInt8(P.getAddressSize());
784 LineSectionSize += 1;
785
786 // segment_selector_size (ubyte).
787 MS->emitInt8(P.SegSelectorSize);
788 LineSectionSize += 1;
789 }
790
791 // header_length.
792 emitLabelDifference(PrologueEndSym, PrologueStartSym, P.FormParams.Format,
793 LineSectionSize);
794
795 Asm->OutStreamer->emitLabel(PrologueStartSym);
796 emitLineTableProloguePayload(P, DebugStrPool, DebugLineStrPool);
797 Asm->OutStreamer->emitLabel(PrologueEndSym);
798}
799
800void DwarfStreamer::emitLineTablePrologueV2IncludeAndFileTable(
801 const DWARFDebugLine::Prologue &P, OffsetsStringPool &DebugStrPool,
802 OffsetsStringPool &DebugLineStrPool) {
803 // include_directories (sequence of path names).
804 for (const DWARFFormValue &Include : P.IncludeDirectories)
805 emitLineTableString(P, Include, DebugStrPool, DebugLineStrPool);
806 // The last entry is followed by a single null byte.
807 MS->emitInt8(0);
808 LineSectionSize += 1;
809
810 // file_names (sequence of file entries).
811 for (const DWARFDebugLine::FileNameEntry &File : P.FileNames) {
812 // A null-terminated string containing the full or relative path name of a
813 // source file.
814 emitLineTableString(P, File.Name, DebugStrPool, DebugLineStrPool);
815 // An unsigned LEB128 number representing the directory index of a directory
816 // in the include_directories section.
817 LineSectionSize += MS->emitULEB128IntValue(File.DirIdx);
818 // An unsigned LEB128 number representing the (implementation-defined) time
819 // of last modification for the file, or 0 if not available.
820 LineSectionSize += MS->emitULEB128IntValue(File.ModTime);
821 // An unsigned LEB128 number representing the length in bytes of the file,
822 // or 0 if not available.
823 LineSectionSize += MS->emitULEB128IntValue(File.Length);
824 }
825 // The last entry is followed by a single null byte.
826 MS->emitInt8(0);
827 LineSectionSize += 1;
828}
829
830void DwarfStreamer::emitLineTablePrologueV5IncludeAndFileTable(
831 const DWARFDebugLine::Prologue &P, OffsetsStringPool &DebugStrPool,
832 OffsetsStringPool &DebugLineStrPool) {
833 if (P.IncludeDirectories.empty()) {
834 // directory_entry_format_count(ubyte).
835 MS->emitInt8(0);
836 LineSectionSize += 1;
837 } else {
838 // directory_entry_format_count(ubyte).
839 MS->emitInt8(1);
840 LineSectionSize += 1;
841
842 // directory_entry_format (sequence of ULEB128 pairs).
843 LineSectionSize += MS->emitULEB128IntValue(dwarf::DW_LNCT_path);
844 LineSectionSize +=
845 MS->emitULEB128IntValue(P.IncludeDirectories[0].getForm());
846 }
847
848 // directories_count (ULEB128).
849 LineSectionSize += MS->emitULEB128IntValue(P.IncludeDirectories.size());
850 // directories (sequence of directory names).
851 for (auto Include : P.IncludeDirectories)
852 emitLineTableString(P, Include, DebugStrPool, DebugLineStrPool);
853
854 if (P.FileNames.empty()) {
855 // file_name_entry_format_count (ubyte).
856 MS->emitInt8(0);
857 LineSectionSize += 1;
858 } else {
859 // file_name_entry_format_count (ubyte).
860 MS->emitInt8(2);
861 LineSectionSize += 1;
862
863 // file_name_entry_format (sequence of ULEB128 pairs).
864 LineSectionSize += MS->emitULEB128IntValue(dwarf::DW_LNCT_path);
865 LineSectionSize += MS->emitULEB128IntValue(P.FileNames[0].Name.getForm());
866
867 LineSectionSize += MS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
868 LineSectionSize += MS->emitULEB128IntValue(dwarf::DW_FORM_data1);
869 }
870
871 // file_names_count (ULEB128).
872 LineSectionSize += MS->emitULEB128IntValue(P.FileNames.size());
873
874 // file_names (sequence of file name entries).
875 for (auto File : P.FileNames) {
876 emitLineTableString(P, File.Name, DebugStrPool, DebugLineStrPool);
877 MS->emitInt8(File.DirIdx);
878 LineSectionSize += 1;
879 }
880}
881
882void DwarfStreamer::emitLineTableString(const DWARFDebugLine::Prologue &P,
883 const DWARFFormValue &String,
884 OffsetsStringPool &DebugStrPool,
885 OffsetsStringPool &DebugLineStrPool) {
886 std::optional<const char *> StringVal = dwarf::toString(String);
887 if (!StringVal) {
888 warn("Cann't read string from line table.");
889 return;
890 }
891
892 switch (String.getForm()) {
893 case dwarf::DW_FORM_string: {
894 StringRef TranslatedString =
895 (Translator) ? Translator(*StringVal) : *StringVal;
896 Asm->OutStreamer->emitBytes(TranslatedString.data());
897 Asm->emitInt8(0);
898 LineSectionSize += TranslatedString.size() + 1;
899 } break;
900 case dwarf::DW_FORM_strp:
901 case dwarf::DW_FORM_line_strp: {
902 DwarfStringPoolEntryRef StringRef =
903 String.getForm() == dwarf::DW_FORM_strp
904 ? DebugStrPool.getEntry(*StringVal)
905 : DebugLineStrPool.getEntry(*StringVal);
906
907 emitIntOffset(StringRef.getOffset(), P.FormParams.Format, LineSectionSize);
908 } break;
909 default:
910 warn("Unsupported string form inside line table.");
911 break;
912 };
913}
914
915void DwarfStreamer::emitLineTableProloguePayload(
916 const DWARFDebugLine::Prologue &P, OffsetsStringPool &DebugStrPool,
917 OffsetsStringPool &DebugLineStrPool) {
918 // minimum_instruction_length (ubyte).
919 MS->emitInt8(P.MinInstLength);
920 LineSectionSize += 1;
921 if (P.FormParams.Version >= 4) {
922 // maximum_operations_per_instruction (ubyte).
923 MS->emitInt8(P.MaxOpsPerInst);
924 LineSectionSize += 1;
925 }
926 // default_is_stmt (ubyte).
927 MS->emitInt8(P.DefaultIsStmt);
928 LineSectionSize += 1;
929 // line_base (sbyte).
930 MS->emitInt8(P.LineBase);
931 LineSectionSize += 1;
932 // line_range (ubyte).
933 MS->emitInt8(P.LineRange);
934 LineSectionSize += 1;
935 // opcode_base (ubyte).
936 MS->emitInt8(P.OpcodeBase);
937 LineSectionSize += 1;
938
939 // standard_opcode_lengths (array of ubyte).
940 for (auto Length : P.StandardOpcodeLengths) {
941 MS->emitInt8(Length);
942 LineSectionSize += 1;
943 }
944
945 if (P.FormParams.Version < 5)
946 emitLineTablePrologueV2IncludeAndFileTable(P, DebugStrPool,
947 DebugLineStrPool);
948 else
949 emitLineTablePrologueV5IncludeAndFileTable(P, DebugStrPool,
950 DebugLineStrPool);
951}
952
953void DwarfStreamer::emitLineTableRows(
954 const DWARFDebugLine::LineTable &LineTable, MCSymbol *LineEndSym,
955 unsigned AddressByteSize) {
956
957 MCDwarfLineTableParams Params;
958 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
959 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
960 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
961
962 SmallString<128> EncodingBuffer;
963
964 if (LineTable.Rows.empty()) {
965 // We only have the dummy entry, dsymutil emits an entry with a 0
966 // address in that case.
967 MCDwarfLineAddr::encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
968 EncodingBuffer);
969 MS->emitBytes(EncodingBuffer);
970 LineSectionSize += EncodingBuffer.size();
971 MS->emitLabel(LineEndSym);
972 return;
973 }
974
975 // Line table state machine fields
976 unsigned FileNum = 1;
977 unsigned LastLine = 1;
978 unsigned Column = 0;
979 unsigned IsStatement = 1;
980 unsigned Isa = 0;
981 uint64_t Address = -1ULL;
982
983 unsigned RowsSinceLastSequence = 0;
984
985 for (const DWARFDebugLine::Row &Row : LineTable.Rows) {
986 int64_t AddressDelta;
987 if (Address == -1ULL) {
988 MS->emitIntValue(dwarf::DW_LNS_extended_op, 1);
989 MS->emitULEB128IntValue(AddressByteSize + 1);
990 MS->emitIntValue(dwarf::DW_LNE_set_address, 1);
991 MS->emitIntValue(Row.Address.Address, AddressByteSize);
992 LineSectionSize +=
993 2 + AddressByteSize + getULEB128Size(AddressByteSize + 1);
994 AddressDelta = 0;
995 } else {
997 (Row.Address.Address - Address) / LineTable.Prologue.MinInstLength;
998 }
999
1000 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
1001 // We should find a way to share this code, but the current compatibility
1002 // requirement with classic dsymutil makes it hard. Revisit that once this
1003 // requirement is dropped.
1004
1005 if (FileNum != Row.File) {
1006 FileNum = Row.File;
1007 MS->emitIntValue(dwarf::DW_LNS_set_file, 1);
1008 MS->emitULEB128IntValue(FileNum);
1009 LineSectionSize += 1 + getULEB128Size(FileNum);
1010 }
1011 if (Column != Row.Column) {
1012 Column = Row.Column;
1013 MS->emitIntValue(dwarf::DW_LNS_set_column, 1);
1014 MS->emitULEB128IntValue(Column);
1015 LineSectionSize += 1 + getULEB128Size(Column);
1016 }
1017
1018 // FIXME: We should handle the discriminator here, but dsymutil doesn't
1019 // consider it, thus ignore it for now.
1020
1021 if (Isa != Row.Isa) {
1022 Isa = Row.Isa;
1023 MS->emitIntValue(dwarf::DW_LNS_set_isa, 1);
1024 MS->emitULEB128IntValue(Isa);
1025 LineSectionSize += 1 + getULEB128Size(Isa);
1026 }
1027 if (IsStatement != Row.IsStmt) {
1028 IsStatement = Row.IsStmt;
1029 MS->emitIntValue(dwarf::DW_LNS_negate_stmt, 1);
1030 LineSectionSize += 1;
1031 }
1032 if (Row.BasicBlock) {
1033 MS->emitIntValue(dwarf::DW_LNS_set_basic_block, 1);
1034 LineSectionSize += 1;
1035 }
1036
1037 if (Row.PrologueEnd) {
1038 MS->emitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
1039 LineSectionSize += 1;
1040 }
1041
1042 if (Row.EpilogueBegin) {
1043 MS->emitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
1044 LineSectionSize += 1;
1045 }
1046
1047 int64_t LineDelta = int64_t(Row.Line) - LastLine;
1048 if (!Row.EndSequence) {
1049 MCDwarfLineAddr::encode(*MC, Params, LineDelta, AddressDelta,
1050 EncodingBuffer);
1051 MS->emitBytes(EncodingBuffer);
1052 LineSectionSize += EncodingBuffer.size();
1053 EncodingBuffer.resize(0);
1054 Address = Row.Address.Address;
1055 LastLine = Row.Line;
1056 RowsSinceLastSequence++;
1057 } else {
1058 if (LineDelta) {
1059 MS->emitIntValue(dwarf::DW_LNS_advance_line, 1);
1060 MS->emitSLEB128IntValue(LineDelta);
1061 LineSectionSize += 1 + getSLEB128Size(LineDelta);
1062 }
1063 if (AddressDelta) {
1064 MS->emitIntValue(dwarf::DW_LNS_advance_pc, 1);
1066 LineSectionSize += 1 + getULEB128Size(AddressDelta);
1067 }
1068 MCDwarfLineAddr::encode(*MC, Params, std::numeric_limits<int64_t>::max(),
1069 0, EncodingBuffer);
1070 MS->emitBytes(EncodingBuffer);
1071 LineSectionSize += EncodingBuffer.size();
1072 EncodingBuffer.resize(0);
1073 Address = -1ULL;
1074 LastLine = FileNum = IsStatement = 1;
1075 RowsSinceLastSequence = Column = Isa = 0;
1076 }
1077 }
1078
1079 if (RowsSinceLastSequence) {
1080 MCDwarfLineAddr::encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
1081 EncodingBuffer);
1082 MS->emitBytes(EncodingBuffer);
1083 LineSectionSize += EncodingBuffer.size();
1084 EncodingBuffer.resize(0);
1085 }
1086
1087 MS->emitLabel(LineEndSym);
1088}
1089
1090void DwarfStreamer::emitIntOffset(uint64_t Offset, dwarf::DwarfFormat Format,
1091 uint64_t &SectionSize) {
1093 MS->emitIntValue(Offset, Size);
1094 SectionSize += Size;
1095}
1096
1097void DwarfStreamer::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1099 uint64_t &SectionSize) {
1101 Asm->emitLabelDifference(Hi, Lo, Size);
1102 SectionSize += Size;
1103}
1104
1105/// Emit the pubnames or pubtypes section contribution for \p
1106/// Unit into \p Sec. The data is provided in \p Names.
1107void DwarfStreamer::emitPubSectionForUnit(
1108 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1109 const std::vector<CompileUnit::AccelInfo> &Names) {
1110 if (Names.empty())
1111 return;
1112
1113 // Start the dwarf pubnames section.
1114 Asm->OutStreamer->switchSection(Sec);
1115 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1116 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1117
1118 bool HeaderEmitted = false;
1119 // Emit the pubnames for this compilation unit.
1120 for (const auto &Name : Names) {
1121 if (Name.SkipPubSection)
1122 continue;
1123
1124 if (!HeaderEmitted) {
1125 // Emit the header.
1126 Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Length
1127 Asm->OutStreamer->emitLabel(BeginLabel);
1128 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1129 Asm->emitInt32(Unit.getStartOffset()); // Unit offset
1130 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1131 HeaderEmitted = true;
1132 }
1133 Asm->emitInt32(Name.Die->getOffset());
1134
1135 // Emit the string itself.
1136 Asm->OutStreamer->emitBytes(Name.Name.getString());
1137 // Emit a null terminator.
1138 Asm->emitInt8(0);
1139 }
1140
1141 if (!HeaderEmitted)
1142 return;
1143 Asm->emitInt32(0); // End marker.
1144 Asm->OutStreamer->emitLabel(EndLabel);
1145}
1146
1147/// Emit .debug_pubnames for \p Unit.
1149 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1150 "names", Unit, Unit.getPubnames());
1151}
1152
1153/// Emit .debug_pubtypes for \p Unit.
1155 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1156 "types", Unit, Unit.getPubtypes());
1157}
1158
1159/// Emit a CIE into the debug_frame section.
1161 MS->switchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1162
1163 MS->emitBytes(CIEBytes);
1164 FrameSectionSize += CIEBytes.size();
1165}
1166
1167/// Emit a FDE into the debug_frame section. \p FDEBytes
1168/// contains the FDE data without the length, CIE offset and address
1169/// which will be replaced with the parameter values.
1171 uint64_t Address, StringRef FDEBytes) {
1172 MS->switchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1173
1174 MS->emitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1175 MS->emitIntValue(CIEOffset, 4);
1176 MS->emitIntValue(Address, AddrSize);
1177 MS->emitBytes(FDEBytes);
1178 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1179}
1180
1182 const Offset2UnitMap &UnitMacroMap,
1183 OffsetsStringPool &StringPool) {
1184 assert(Context != nullptr && "Empty DWARF context");
1185
1186 // Check for .debug_macinfo table.
1187 if (const DWARFDebugMacro *Table = Context->getDebugMacinfo()) {
1188 MS->switchSection(MC->getObjectFileInfo()->getDwarfMacinfoSection());
1189 emitMacroTableImpl(Table, UnitMacroMap, StringPool, MacInfoSectionSize);
1190 }
1191
1192 // Check for .debug_macro table.
1193 if (const DWARFDebugMacro *Table = Context->getDebugMacro()) {
1194 MS->switchSection(MC->getObjectFileInfo()->getDwarfMacroSection());
1195 emitMacroTableImpl(Table, UnitMacroMap, StringPool, MacroSectionSize);
1196 }
1197}
1198
1199void DwarfStreamer::emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
1200 const Offset2UnitMap &UnitMacroMap,
1201 OffsetsStringPool &StringPool,
1202 uint64_t &OutOffset) {
1203 bool DefAttributeIsReported = false;
1204 bool UndefAttributeIsReported = false;
1205 bool ImportAttributeIsReported = false;
1206 for (const DWARFDebugMacro::MacroList &List : MacroTable->MacroLists) {
1207 Offset2UnitMap::const_iterator UnitIt = UnitMacroMap.find(List.Offset);
1208 if (UnitIt == UnitMacroMap.end()) {
1209 warn(formatv(
1210 "couldn`t find compile unit for the macro table with offset = {0:x}",
1211 List.Offset));
1212 continue;
1213 }
1214
1215 // Skip macro table if the unit was not cloned.
1216 DIE *OutputUnitDIE = UnitIt->second->getOutputUnitDIE();
1217 if (OutputUnitDIE == nullptr)
1218 continue;
1219
1220 // Update macro attribute of cloned compile unit with the proper offset to
1221 // the macro table.
1222 bool hasDWARFv5Header = false;
1223 for (auto &V : OutputUnitDIE->values()) {
1224 if (V.getAttribute() == dwarf::DW_AT_macro_info) {
1225 V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
1226 break;
1227 } else if (V.getAttribute() == dwarf::DW_AT_macros) {
1228 hasDWARFv5Header = true;
1229 V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
1230 break;
1231 }
1232 }
1233
1234 // Write DWARFv5 header.
1235 if (hasDWARFv5Header) {
1236 // Write header version.
1237 MS->emitIntValue(List.Header.Version, sizeof(List.Header.Version));
1238 OutOffset += sizeof(List.Header.Version);
1239
1240 uint8_t Flags = List.Header.Flags;
1241
1242 // Check for OPCODE_OPERANDS_TABLE.
1243 if (Flags &
1244 DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE) {
1245 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE;
1246 warn("opcode_operands_table is not supported yet.");
1247 }
1248
1249 // Check for DEBUG_LINE_OFFSET.
1250 std::optional<uint64_t> StmtListOffset;
1251 if (Flags & DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET) {
1252 // Get offset to the line table from the cloned compile unit.
1253 for (auto &V : OutputUnitDIE->values()) {
1254 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1255 StmtListOffset = V.getDIEInteger().getValue();
1256 break;
1257 }
1258 }
1259
1260 if (!StmtListOffset) {
1261 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET;
1262 warn("couldn`t find line table for macro table.");
1263 }
1264 }
1265
1266 // Write flags.
1267 MS->emitIntValue(Flags, sizeof(Flags));
1268 OutOffset += sizeof(Flags);
1269
1270 // Write offset to line table.
1271 if (StmtListOffset) {
1272 MS->emitIntValue(*StmtListOffset, List.Header.getOffsetByteSize());
1273 OutOffset += List.Header.getOffsetByteSize();
1274 }
1275 }
1276
1277 // Write macro entries.
1278 for (const DWARFDebugMacro::Entry &MacroEntry : List.Macros) {
1279 if (MacroEntry.Type == 0) {
1280 OutOffset += MS->emitULEB128IntValue(MacroEntry.Type);
1281 continue;
1282 }
1283
1284 uint8_t MacroType = MacroEntry.Type;
1285 switch (MacroType) {
1286 default: {
1287 bool HasVendorSpecificExtension =
1288 (!hasDWARFv5Header && MacroType == dwarf::DW_MACINFO_vendor_ext) ||
1289 (hasDWARFv5Header && (MacroType >= dwarf::DW_MACRO_lo_user &&
1290 MacroType <= dwarf::DW_MACRO_hi_user));
1291
1292 if (HasVendorSpecificExtension) {
1293 // Write macinfo type.
1294 MS->emitIntValue(MacroType, 1);
1295 OutOffset++;
1296
1297 // Write vendor extension constant.
1298 OutOffset += MS->emitULEB128IntValue(MacroEntry.ExtConstant);
1299
1300 // Write vendor extension string.
1301 StringRef String = MacroEntry.ExtStr;
1302 MS->emitBytes(String);
1303 MS->emitIntValue(0, 1);
1304 OutOffset += String.size() + 1;
1305 } else
1306 warn("unknown macro type. skip.");
1307 } break;
1308 // debug_macro and debug_macinfo share some common encodings.
1309 // DW_MACRO_define == DW_MACINFO_define
1310 // DW_MACRO_undef == DW_MACINFO_undef
1311 // DW_MACRO_start_file == DW_MACINFO_start_file
1312 // DW_MACRO_end_file == DW_MACINFO_end_file
1313 // For readibility/uniformity we are using DW_MACRO_*.
1314 case dwarf::DW_MACRO_define:
1315 case dwarf::DW_MACRO_undef: {
1316 // Write macinfo type.
1317 MS->emitIntValue(MacroType, 1);
1318 OutOffset++;
1319
1320 // Write source line.
1321 OutOffset += MS->emitULEB128IntValue(MacroEntry.Line);
1322
1323 // Write macro string.
1324 StringRef String = MacroEntry.MacroStr;
1325 MS->emitBytes(String);
1326 MS->emitIntValue(0, 1);
1327 OutOffset += String.size() + 1;
1328 } break;
1329 case dwarf::DW_MACRO_define_strp:
1330 case dwarf::DW_MACRO_undef_strp:
1331 case dwarf::DW_MACRO_define_strx:
1332 case dwarf::DW_MACRO_undef_strx: {
1333 assert(UnitIt->second->getOrigUnit().getVersion() >= 5);
1334
1335 // DW_MACRO_*_strx forms are not supported currently.
1336 // Convert to *_strp.
1337 switch (MacroType) {
1338 case dwarf::DW_MACRO_define_strx: {
1339 MacroType = dwarf::DW_MACRO_define_strp;
1340 if (!DefAttributeIsReported) {
1341 warn("DW_MACRO_define_strx unsupported yet. Convert to "
1342 "DW_MACRO_define_strp.");
1343 DefAttributeIsReported = true;
1344 }
1345 } break;
1346 case dwarf::DW_MACRO_undef_strx: {
1347 MacroType = dwarf::DW_MACRO_undef_strp;
1348 if (!UndefAttributeIsReported) {
1349 warn("DW_MACRO_undef_strx unsupported yet. Convert to "
1350 "DW_MACRO_undef_strp.");
1351 UndefAttributeIsReported = true;
1352 }
1353 } break;
1354 default:
1355 // Nothing to do.
1356 break;
1357 }
1358
1359 // Write macinfo type.
1360 MS->emitIntValue(MacroType, 1);
1361 OutOffset++;
1362
1363 // Write source line.
1364 OutOffset += MS->emitULEB128IntValue(MacroEntry.Line);
1365
1366 // Write macro string.
1367 DwarfStringPoolEntryRef EntryRef =
1368 StringPool.getEntry(MacroEntry.MacroStr);
1369 MS->emitIntValue(EntryRef.getOffset(), List.Header.getOffsetByteSize());
1370 OutOffset += List.Header.getOffsetByteSize();
1371 break;
1372 }
1373 case dwarf::DW_MACRO_start_file: {
1374 // Write macinfo type.
1375 MS->emitIntValue(MacroType, 1);
1376 OutOffset++;
1377 // Write source line.
1378 OutOffset += MS->emitULEB128IntValue(MacroEntry.Line);
1379 // Write source file id.
1380 OutOffset += MS->emitULEB128IntValue(MacroEntry.File);
1381 } break;
1382 case dwarf::DW_MACRO_end_file: {
1383 // Write macinfo type.
1384 MS->emitIntValue(MacroType, 1);
1385 OutOffset++;
1386 } break;
1387 case dwarf::DW_MACRO_import:
1388 case dwarf::DW_MACRO_import_sup: {
1389 if (!ImportAttributeIsReported) {
1390 warn("DW_MACRO_import and DW_MACRO_import_sup are unsupported yet. "
1391 "remove.");
1392 ImportAttributeIsReported = true;
1393 }
1394 } break;
1395 }
1396 }
1397 }
1398}
1399
1400} // namespace llvm
uint64_t Addr
std::string Name
uint64_t Size
LLVMContext & Context
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
Definition: AccelTable.h:194
A class that represents an address range.
Definition: AddressRanges.h:22
The AddressRanges class helps normalize address range collections.
Stores all information relating to a compile unit, be it in its original instance in the object file ...
A structured debug information entry.
Definition: DIE.h:819
unsigned getSize() const
Definition: DIE.h:862
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Definition: DWARFContext.h:48
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
void emitMacroTables(DWARFContext *Context, const Offset2UnitMap &UnitMacroMap, OffsetsStringPool &StringPool) override
Emit all available macro tables(DWARFv4 and DWARFv5).
void emitAppleNamespaces(AccelTable< AppleAccelTableStaticOffsetData > &Table) override
Emit Apple namespaces accelerator table.
void emitStrings(const NonRelocatableStringpool &Pool) override
Emit the string table described by Pool into .debug_str table.
void emitAppleNames(AccelTable< AppleAccelTableStaticOffsetData > &Table) override
Emit Apple names accelerator table.
void emitDwarfDebugArangesTable(const CompileUnit &Unit, const AddressRanges &LinkedRanges) override
Emit .debug_aranges entries for Unit.
void finish() override
Dump the file to the disk.
void emitDwarfDebugRangeListFragment(const CompileUnit &Unit, const AddressRanges &LinkedRanges, PatchLocation Patch, DebugDieValuePool &AddrPool) override
Emit debug ranges(.debug_ranges, .debug_rnglists) fragment.
void emitAppleObjc(AccelTable< AppleAccelTableStaticOffsetData > &Table) override
Emit Apple Objective-C accelerator table.
void emitStringOffsets(const SmallVector< uint64_t > &StringOffset, uint16_t TargetDWARFVersion) override
Emit the debug string offset table described by StringOffsets into the .debug_str_offsets table.
void emitDwarfDebugRangeListFooter(const CompileUnit &Unit, MCSymbol *EndLabel) override
Emit debug ranges(.debug_ranges, .debug_rnglists) footer.
void emitAppleTypes(AccelTable< AppleAccelTableStaticTypeData > &Table) override
Emit Apple type accelerator table.
void emitSectionContents(StringRef SecData, StringRef SecName) override
Emit contents of section SecName From Obj.
void emitDwarfDebugLocListFragment(const CompileUnit &Unit, const DWARFLocationExpressionsVector &LinkedLocationExpression, PatchLocation Patch, DebugDieValuePool &AddrPool) override
Emit debug ranges(.debug_loc, .debug_loclists) fragment.
void emitPubNamesForUnit(const CompileUnit &Unit) override
Emit the .debug_pubnames contribution for Unit.
void emitDwarfDebugAddrs(const SmallVector< uint64_t > &Addrs, uint8_t AddrSize) override
Emit the addresses described by Addrs into .debug_addr table.
void emitCIE(StringRef CIEBytes) override
Emit a CIE.
void emitDIE(DIE &Die) override
Recursively emit the DIE tree rooted at Die.
void emitDwarfDebugAddrsFooter(const CompileUnit &Unit, MCSymbol *EndLabel) override
Emit .debug_addr footer.
void emitDwarfDebugLocListFooter(const CompileUnit &Unit, MCSymbol *EndLabel) override
Emit debug ranges(.debug_loc, .debug_loclists) footer.
void emitLineStrings(const NonRelocatableStringpool &Pool) override
Emit the string table described by Pool into .debug_line_str table.
void emitSwiftReflectionSection(llvm::binaryformat::Swift5ReflectionSectionKind ReflSectionKind, StringRef Buffer, uint32_t Alignment, uint32_t Size) override
Emit the swift reflection section stored in Buffer.
void emitCompileUnitHeader(CompileUnit &Unit, unsigned DwarfVersion) override
Emit the compilation unit header for Unit in the debug_info section.
MCSymbol * emitDwarfDebugLocListHeader(const CompileUnit &Unit) override
Emit debug locations(.debug_loc, .debug_loclists) header.
void emitPubTypesForUnit(const CompileUnit &Unit) override
Emit the .debug_pubtypes contribution for Unit.
void emitLineTableForUnit(const DWARFDebugLine::LineTable &LineTable, const CompileUnit &Unit, OffsetsStringPool &DebugStrPool, OffsetsStringPool &DebugLineStrPool) override
Emit .debug_line table entry for specified LineTable.
void emitAbbrevs(const std::vector< std::unique_ptr< DIEAbbrev > > &Abbrevs, unsigned DwarfVersion) override
Emit the abbreviation table Abbrevs to the debug_abbrev section.
MCSymbol * emitDwarfDebugAddrsHeader(const CompileUnit &Unit) override
Emit .debug_addr header.
void emitSwiftAST(StringRef Buffer) override
Emit the swift_ast section stored in Buffer.
MCSymbol * emitDwarfDebugRangeListHeader(const CompileUnit &Unit) override
Emit debug ranges(.debug_ranges, .debug_rnglists) header.
Error init(Triple TheTriple, StringRef Swift5ReflectionSegmentName)
void switchToDebugInfoSection(unsigned DwarfVersion)
Set the current output section to debug_info and change the MC Dwarf version to DwarfVersion.
void emitDebugNames(AccelTable< DWARF5AccelTableStaticData > &Table) override
Emit DWARF debug names.
void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint64_t Address, StringRef Bytes) override
Emit an FDE with data Bytes.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
std::unique_ptr< MCObjectWriter > createObjectWriter(raw_pwrite_stream &OS) const
Create a new MCObjectWriter instance for use by the assembler backend to emit the final object file.
Context object for machine code objects.
Definition: MCContext.h:76
static void encode(MCContext &Context, MCDwarfLineTableParams Params, int64_t LineDelta, uint64_t AddrDelta, SmallVectorImpl< char > &OS)
Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
Definition: MCDwarf.cpp:688
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:39
void setAlignment(Align Value)
Definition: MCSection.h:141
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:424
virtual void emitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers.
Definition: MCStreamer.cpp:134
void emitInt16(uint64_t Value)
Definition: MCStreamer.h:753
unsigned emitULEB128IntValue(uint64_t Value, unsigned PadTo=0)
Special case of EmitULEB128Value that avoids the client having to pass in a MCExpr for constant integ...
Definition: MCStreamer.cpp:162
virtual void switchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
void emitInt32(uint64_t Value)
Definition: MCStreamer.h:754
unsigned emitSLEB128IntValue(int64_t Value)
Special case of EmitSLEB128Value that avoids the client having to pass in a MCExpr for constant integ...
Definition: MCStreamer.cpp:172
void emitInt8(uint64_t Value)
Definition: MCStreamer.h:752
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
void finish(SMLoc EndLoc=SMLoc())
Finish emission of machine code.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
A string table that doesn't need relocations.
std::vector< DwarfStringPoolEntryRef > getEntriesForEmission() const
Return the list of strings to be emitted.
bool empty() const
Definition: SmallVector.h:94
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
Helper for making strong types.
Target - Wrapper for Target specific information.
MCCodeEmitter * createMCCodeEmitter(const MCInstrInfo &II, MCContext &Ctx) const
createMCCodeEmitter - Create a target specific code emitter.
MCObjectFileInfo * createMCObjectFileInfo(MCContext &Ctx, bool PIC, bool LargeCodeModel=false) const
Create a MCObjectFileInfo implementation for the specified target triple.
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
MCStreamer * createAsmStreamer(MCContext &Ctx, std::unique_ptr< formatted_raw_ostream > OS, bool IsVerboseAsm, bool UseDwarfDirectory, MCInstPrinter *InstPrint, std::unique_ptr< MCCodeEmitter > &&CE, std::unique_ptr< MCAsmBackend > &&TAB, bool ShowInst) const
MCAsmBackend * createMCAsmBackend(const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options) const
createMCAsmBackend - Create a target specific assembly parser.
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple, const MCTargetOptions &Options) const
createMCAsmInfo - Create a MCAsmInfo implementation for the specified target triple.
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
MCStreamer * createMCObjectStreamer(const Triple &T, MCContext &Ctx, std::unique_ptr< MCAsmBackend > &&TAB, std::unique_ptr< MCObjectWriter > &&OW, std::unique_ptr< MCCodeEmitter > &&Emitter, const MCSubtargetInfo &STI, bool RelaxAll, bool IncrementalLinkerCompatible, bool DWARFMustBeAtTheEnd) const
Create a target specific MCStreamer.
AsmPrinter * createAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > &&Streamer) const
createAsmPrinter - Create a target specific assembly printer pass.
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
const std::string & getTriple() const
Definition: Triple.h:416
@ SectionSize
Definition: COFF.h:60
Swift5ReflectionSectionKind
Definition: Swift.h:14
@ DW_MACRO_lo_user
Definition: Dwarf.h:483
@ DW_MACRO_hi_user
Definition: Dwarf.h:484
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
DwarfFormat
Constants that define the DWARF format as 32 or 64 bit.
Definition: Dwarf.h:91
@ DWARF64
Definition: Dwarf.h:91
@ DW_MACINFO_vendor_ext
Definition: Dwarf.h:476
uint8_t getDwarfOffsetByteSize(DwarfFormat Format)
The size of a reference determined by the DWARF 32/64-bit format.
Definition: Dwarf.h:730
@ DW_ARANGES_VERSION
Section version number for .debug_aranges.
Definition: Dwarf.h:64
@ DW_PUBNAMES_VERSION
Section version number for .debug_pubnames.
Definition: Dwarf.h:63
@ DW_LENGTH_DWARF64
Indicator of 64-bit DWARF format.
Definition: Dwarf.h:55
MCTargetOptions InitMCTargetOptionsFromFlags()
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:440
@ Length
Definition: DWP.cpp:440
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1244
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
void emitDWARF5AccelTable(AsmPrinter *Asm, AccelTable< DWARF5AccelTableData > &Contents, const DwarfDebug &DD, ArrayRef< std::unique_ptr< DwarfCompileUnit > > CUs)
Definition: AccelTable.cpp:548
StrongType< NonRelocatableStringpool, OffsetsTag > OffsetsStringPool
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: Alignment.h:197
unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
Definition: LEB128.cpp:19
void emitAppleAccelTable(AsmPrinter *Asm, AccelTable< DataT > &Contents, StringRef Prefix, const MCSymbol *SecBegin)
Emit an Apple Accelerator Table consisting of entries in the specified AccelTable.
Definition: AccelTable.h:303
unsigned getSLEB128Size(int64_t Value)
Utility function to get the size of the SLEB128-encoded value.
Definition: LEB128.cpp:29
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
dwarf::FormParams FormParams
Version, address size (starting in v5), and DWARF32/64 format; these parameters affect interpretation...
Represents a single DWARF expression, whose value is location-dependent.
uint64_t getValueIndex(uint64_t Value)
Definition: DWARFLinker.h:82
void set(uint64_t New) const
static const Target * lookupTarget(StringRef Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
DwarfFormat Format
Definition: Dwarf.h:746