1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCDwarf.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include "llvm/ADT/Hashing.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectStreamer.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/StringTableBuilder.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/Endian.h"
33 #include "llvm/Support/EndianStream.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/LEB128.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
48 MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
50 S.getContext().createTempSymbol("debug_list_header_start", true, true);
52 S.getContext().createTempSymbol("debug_list_header_end", true, true);
53 auto DwarfFormat = S.getContext().getDwarfFormat();
54 if (DwarfFormat == dwarf::DWARF64) {
55 S.AddComment("DWARF64 mark");
56 S.emitInt32(dwarf::DW_LENGTH_DWARF64);
58 S.AddComment("Length");
59 S.emitAbsoluteSymbolDiff(End, Start,
60 dwarf::getDwarfOffsetByteSize(DwarfFormat));
62 S.AddComment("Version");
63 S.emitInt16(S.getContext().getDwarfVersion());
64 S.AddComment("Address size");
65 S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());
66 S.AddComment("Segment selector size");
71 /// Manage the .debug_line_str section contents, if we use it.
72 class llvm::MCDwarfLineStr {
73 MCSymbol *LineStrLabel = nullptr;
74 StringTableBuilder LineStrings{StringTableBuilder::DWARF};
75 bool UseRelocs = false;
78 /// Construct an instance that can emit .debug_line_str (for use in a normal
80 explicit MCDwarfLineStr(MCContext &Ctx) {
81 UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
84 Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol();
87 /// Emit a reference to the string.
88 void emitRef(MCStreamer *MCOS, StringRef Path);
90 /// Emit the .debug_line_str section if appropriate.
91 void emitSection(MCStreamer *MCOS);
94 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
95 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
96 if (MinInsnLength == 1)
98 if (AddrDelta % MinInsnLength != 0) {
99 // TODO: report this error, but really only once.
102 return AddrDelta / MinInsnLength;
106 // This is called when an instruction is assembled into the specified section
107 // and if there is information from the last .loc directive that has yet to have
108 // a line entry made for it is made.
110 void MCDwarfLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) {
111 if (!MCOS->getContext().getDwarfLocSeen())
114 // Create a symbol at in the current section for use in the line entry.
115 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
116 // Set the value of the symbol to use for the MCDwarfLineEntry.
117 MCOS->emitLabel(LineSym);
119 // Get the current .loc info saved in the context.
120 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
122 // Create a (local) line entry with the symbol and the current .loc info.
123 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
125 // clear DwarfLocSeen saying the current .loc info is now used.
126 MCOS->getContext().clearDwarfLocSeen();
128 // Add the line entry to this section's entries.
130 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
132 .addLineEntry(LineEntry, Section);
136 // This helper routine returns an expression of End - Start + IntVal .
138 static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
139 const MCSymbol &Start,
142 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
143 const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);
144 const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
145 const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);
146 const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);
147 const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);
152 // This helper routine returns an expression of Start + IntVal .
154 static inline const MCExpr *
155 makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {
156 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
157 const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
158 const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);
159 const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);
164 // This emits the Dwarf line table for the specified section from the entries
165 // in the LineSection.
167 static inline void emitDwarfLineTable(
168 MCObjectStreamer *MCOS, MCSection *Section,
169 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
170 unsigned FileNum = 1;
171 unsigned LastLine = 1;
173 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
175 unsigned Discriminator = 0;
176 MCSymbol *LastLabel = nullptr;
178 // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
179 for (const MCDwarfLineEntry &LineEntry : LineEntries) {
180 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
182 if (FileNum != LineEntry.getFileNum()) {
183 FileNum = LineEntry.getFileNum();
184 MCOS->emitInt8(dwarf::DW_LNS_set_file);
185 MCOS->emitULEB128IntValue(FileNum);
187 if (Column != LineEntry.getColumn()) {
188 Column = LineEntry.getColumn();
189 MCOS->emitInt8(dwarf::DW_LNS_set_column);
190 MCOS->emitULEB128IntValue(Column);
192 if (Discriminator != LineEntry.getDiscriminator() &&
193 MCOS->getContext().getDwarfVersion() >= 4) {
194 Discriminator = LineEntry.getDiscriminator();
195 unsigned Size = getULEB128Size(Discriminator);
196 MCOS->emitInt8(dwarf::DW_LNS_extended_op);
197 MCOS->emitULEB128IntValue(Size + 1);
198 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
199 MCOS->emitULEB128IntValue(Discriminator);
201 if (Isa != LineEntry.getIsa()) {
202 Isa = LineEntry.getIsa();
203 MCOS->emitInt8(dwarf::DW_LNS_set_isa);
204 MCOS->emitULEB128IntValue(Isa);
206 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
207 Flags = LineEntry.getFlags();
208 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
210 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
211 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
212 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
213 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
214 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
215 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
217 MCSymbol *Label = LineEntry.getLabel();
219 // At this point we want to emit/create the sequence to encode the delta in
220 // line numbers and the increment of the address from the previous Label
221 // and the current Label.
222 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
223 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
224 asmInfo->getCodePointerSize());
227 LastLine = LineEntry.getLine();
231 // Emit a DW_LNE_end_sequence for the end of the section.
232 // Use the section end label to compute the address delta and use INT64_MAX
233 // as the line delta which is the signal that this is actually a
234 // DW_LNE_end_sequence.
235 MCSymbol *SectionEnd = MCOS->endSection(Section);
237 // Switch back the dwarf line section, in case endSection had to switch the
239 MCContext &Ctx = MCOS->getContext();
240 MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
242 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
243 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
244 AsmInfo->getCodePointerSize());
248 // This emits the Dwarf file and the line tables.
250 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS,
251 MCDwarfLineTableParams Params) {
252 MCContext &context = MCOS->getContext();
254 auto &LineTables = context.getMCDwarfLineTables();
256 // Bail out early so we don't switch to the debug_line section needlessly and
257 // in doing so create an unnecessary (if empty) section.
258 if (LineTables.empty())
261 // In a v5 non-split line table, put the strings in a separate section.
262 Optional<MCDwarfLineStr> LineStr;
263 if (context.getDwarfVersion() >= 5)
264 LineStr = MCDwarfLineStr(context);
266 // Switch to the section where the table will be emitted into.
267 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
269 // Handle the rest of the Compile Units.
270 for (const auto &CUIDTablePair : LineTables) {
271 CUIDTablePair.second.EmitCU(MCOS, Params, LineStr);
275 LineStr->emitSection(MCOS);
278 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
279 MCSection *Section) const {
280 if (!HasSplitLineTable)
282 Optional<MCDwarfLineStr> NoLineStr(None);
283 MCOS.SwitchSection(Section);
284 MCOS.emitLabel(Header.Emit(&MCOS, Params, None, NoLineStr).second);
287 std::pair<MCSymbol *, MCSymbol *>
288 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
289 Optional<MCDwarfLineStr> &LineStr) const {
290 static const char StandardOpcodeLengths[] = {
291 0, // length of DW_LNS_copy
292 1, // length of DW_LNS_advance_pc
293 1, // length of DW_LNS_advance_line
294 1, // length of DW_LNS_set_file
295 1, // length of DW_LNS_set_column
296 0, // length of DW_LNS_negate_stmt
297 0, // length of DW_LNS_set_basic_block
298 0, // length of DW_LNS_const_add_pc
299 1, // length of DW_LNS_fixed_advance_pc
300 0, // length of DW_LNS_set_prologue_end
301 0, // length of DW_LNS_set_epilogue_begin
304 assert(array_lengthof(StandardOpcodeLengths) >=
305 (Params.DWARF2LineOpcodeBase - 1U));
308 makeArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
312 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
313 MCContext &Context = OS.getContext();
314 assert(!isa<MCSymbolRefExpr>(Expr));
315 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
318 MCSymbol *ABS = Context.createTempSymbol();
319 OS.emitAssignment(ABS, Expr);
320 return MCSymbolRefExpr::create(ABS, Context);
323 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
324 const MCExpr *ABS = forceExpAbs(OS, Value);
325 OS.emitValue(ABS, Size);
328 void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
329 // Switch to the .debug_line_str section.
331 MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
332 // Emit the strings without perturbing the offsets we used.
333 LineStrings.finalizeInOrder();
335 Data.resize(LineStrings.getSize());
336 LineStrings.write((uint8_t *)Data.data());
337 MCOS->emitBinaryData(Data.str());
340 void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
342 dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());
343 size_t Offset = LineStrings.add(Path);
345 MCContext &Ctx = MCOS->getContext();
346 MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize);
348 MCOS->emitIntValue(Offset, RefSize);
351 void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
352 // First the directory table.
353 for (auto &Dir : MCDwarfDirs) {
354 MCOS->emitBytes(Dir); // The DirectoryName, and...
355 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
357 MCOS->emitInt8(0); // Terminate the directory list.
359 // Second the file table.
360 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
361 assert(!MCDwarfFiles[i].Name.empty());
362 MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and...
363 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
364 MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number.
365 MCOS->emitInt8(0); // Last modification timestamp (always 0).
366 MCOS->emitInt8(0); // File size (always 0).
368 MCOS->emitInt8(0); // Terminate the file list.
371 static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
372 bool EmitMD5, bool HasSource,
373 Optional<MCDwarfLineStr> &LineStr) {
374 assert(!DwarfFile.Name.empty());
376 LineStr->emitRef(MCOS, DwarfFile.Name);
378 MCOS->emitBytes(DwarfFile.Name); // FileName and...
379 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
381 MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number.
383 const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
384 MCOS->emitBinaryData(
385 StringRef(reinterpret_cast<const char *>(Cksum.Bytes.data()),
386 Cksum.Bytes.size()));
390 LineStr->emitRef(MCOS, DwarfFile.Source.getValueOr(StringRef()));
393 DwarfFile.Source.getValueOr(StringRef())); // Source and...
394 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
399 void MCDwarfLineTableHeader::emitV5FileDirTables(
400 MCStreamer *MCOS, Optional<MCDwarfLineStr> &LineStr) const {
401 // The directory format, which is just a list of the directory paths. In a
402 // non-split object, these are references to .debug_line_str; in a split
403 // object, they are inline strings.
405 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
406 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
407 : dwarf::DW_FORM_string);
408 MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);
409 // Try not to emit an empty compilation directory.
410 const StringRef CompDir = CompilationDir.empty()
411 ? MCOS->getContext().getCompilationDir()
412 : StringRef(CompilationDir);
414 // Record path strings, emit references here.
415 LineStr->emitRef(MCOS, CompDir);
416 for (const auto &Dir : MCDwarfDirs)
417 LineStr->emitRef(MCOS, Dir);
419 // The list of directory paths. Compilation directory comes first.
420 MCOS->emitBytes(CompDir);
421 MCOS->emitBytes(StringRef("\0", 1));
422 for (const auto &Dir : MCDwarfDirs) {
423 MCOS->emitBytes(Dir); // The DirectoryName, and...
424 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
428 // The file format, which is the inline null-terminated filename and a
429 // directory index. We don't track file size/timestamp so don't emit them
430 // in the v5 table. Emit MD5 checksums and source if we have them.
431 uint64_t Entries = 2;
436 MCOS->emitInt8(Entries);
437 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
438 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
439 : dwarf::DW_FORM_string);
440 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
441 MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);
443 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);
444 MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);
447 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);
448 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
449 : dwarf::DW_FORM_string);
451 // Then the counted list of files. The root file is file #0, then emit the
452 // files as provide by .file directives.
453 // MCDwarfFiles has an unused element [0] so use size() not size()+1.
454 // But sometimes MCDwarfFiles is empty, in which case we still emit one file.
455 MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
456 // To accommodate assembler source written for DWARF v4 but trying to emit
457 // v5: If we didn't see a root file explicitly, replicate file #1.
458 assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
459 "No root file and no .file directives");
460 emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
461 HasAllMD5, HasSource, LineStr);
462 for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
463 emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr);
466 std::pair<MCSymbol *, MCSymbol *>
467 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
468 ArrayRef<char> StandardOpcodeLengths,
469 Optional<MCDwarfLineStr> &LineStr) const {
470 MCContext &context = MCOS->getContext();
472 // Create a symbol at the beginning of the line table.
473 MCSymbol *LineStartSym = Label;
475 LineStartSym = context.createTempSymbol();
476 // Set the value of the symbol, as we are at the start of the line table.
477 MCOS->emitLabel(LineStartSym);
479 // Create a symbol for the end of the section (to be set when we get there).
480 MCSymbol *LineEndSym = context.createTempSymbol();
482 unsigned UnitLengthBytes =
483 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
484 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
486 if (context.getDwarfFormat() == dwarf::DWARF64)
487 // Emit DWARF64 mark.
488 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
490 // The length field does not include itself and, in case of the 64-bit DWARF
491 // format, the DWARF64 mark.
493 makeEndMinusStartExpr(context, *LineStartSym, *LineEndSym,
497 // Next 2 bytes is the Version.
498 unsigned LineTableVersion = context.getDwarfVersion();
499 MCOS->emitInt16(LineTableVersion);
501 // Keep track of the bytes between the very start and where the header length
503 unsigned PreHeaderLengthBytes = UnitLengthBytes + 2;
505 // In v5, we get address info next.
506 if (LineTableVersion >= 5) {
507 MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());
508 MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges.
509 PreHeaderLengthBytes += 2;
512 // Create a symbol for the end of the prologue (to be set when we get there).
513 MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
515 // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is
516 // actually the length from after the length word, to the end of the prologue.
518 makeEndMinusStartExpr(context, *LineStartSym, *ProEndSym,
519 (PreHeaderLengthBytes + OffsetSize)),
522 // Parameters of the state machine, are next.
523 MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
524 // maximum_operations_per_instruction
525 // For non-VLIW architectures this field is always 1.
526 // FIXME: VLIW architectures need to update this field accordingly.
527 if (LineTableVersion >= 4)
529 MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
530 MCOS->emitInt8(Params.DWARF2LineBase);
531 MCOS->emitInt8(Params.DWARF2LineRange);
532 MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
534 // Standard opcode lengths
535 for (char Length : StandardOpcodeLengths)
536 MCOS->emitInt8(Length);
538 // Put out the directory and file tables. The formats vary depending on
540 if (LineTableVersion >= 5)
541 emitV5FileDirTables(MCOS, LineStr);
543 emitV2FileDirTables(MCOS);
545 // This is the end of the prologue, so set the value of the symbol at the
546 // end of the prologue (that was used in a previous expression).
547 MCOS->emitLabel(ProEndSym);
549 return std::make_pair(LineStartSym, LineEndSym);
552 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS,
553 MCDwarfLineTableParams Params,
554 Optional<MCDwarfLineStr> &LineStr) const {
555 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
557 // Put out the line tables.
558 for (const auto &LineSec : MCLineSections.getMCLineEntries())
559 emitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
561 // This is the end of the section, so set the value of the symbol at the end
562 // of this section (that was used in a previous expression).
563 MCOS->emitLabel(LineEndSym);
566 Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory,
568 Optional<MD5::MD5Result> Checksum,
569 Optional<StringRef> Source,
570 uint16_t DwarfVersion,
571 unsigned FileNumber) {
572 return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
576 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
577 StringRef &FileName, Optional<MD5::MD5Result> Checksum) {
578 if (RootFile.Name.empty() || RootFile.Name != FileName.data())
580 return RootFile.Checksum == Checksum;
584 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory,
586 Optional<MD5::MD5Result> Checksum,
587 Optional<StringRef> Source,
588 uint16_t DwarfVersion,
589 unsigned FileNumber) {
590 if (Directory == CompilationDir)
592 if (FileName.empty()) {
593 FileName = "<stdin>";
596 assert(!FileName.empty());
597 // Keep track of whether any or all files have an MD5 checksum.
598 // If any files have embedded source, they all must.
599 if (MCDwarfFiles.empty()) {
600 trackMD5Usage(Checksum.hasValue());
601 HasSource = (Source != None);
603 if (isRootFile(RootFile, Directory, FileName, Checksum) && DwarfVersion >= 5)
605 if (FileNumber == 0) {
606 // File numbers start with 1 and/or after any file numbers
607 // allocated by inline-assembler .file directives.
608 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
609 SmallString<256> Buffer;
610 auto IterBool = SourceIdMap.insert(
611 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
613 if (!IterBool.second)
614 return IterBool.first->second;
616 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
617 if (FileNumber >= MCDwarfFiles.size())
618 MCDwarfFiles.resize(FileNumber + 1);
620 // Get the new MCDwarfFile slot for this FileNumber.
621 MCDwarfFile &File = MCDwarfFiles[FileNumber];
623 // It is an error to see the same number more than once.
624 if (!File.Name.empty())
625 return make_error<StringError>("file number already allocated",
626 inconvertibleErrorCode());
628 // If any files have embedded source, they all must.
629 if (HasSource != (Source != None))
630 return make_error<StringError>("inconsistent use of embedded source",
631 inconvertibleErrorCode());
633 if (Directory.empty()) {
634 // Separate the directory part from the basename of the FileName.
635 StringRef tFileName = sys::path::filename(FileName);
636 if (!tFileName.empty()) {
637 Directory = sys::path::parent_path(FileName);
638 if (!Directory.empty())
639 FileName = tFileName;
643 // Find or make an entry in the MCDwarfDirs vector for this Directory.
644 // Capture directory name.
646 if (Directory.empty()) {
647 // For FileNames with no directories a DirIndex of 0 is used.
650 DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
651 if (DirIndex >= MCDwarfDirs.size())
652 MCDwarfDirs.push_back(std::string(Directory));
653 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
654 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
655 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
656 // are stored at MCDwarfFiles[FileNumber].Name .
660 File.Name = std::string(FileName);
661 File.DirIndex = DirIndex;
662 File.Checksum = Checksum;
663 trackMD5Usage(Checksum.hasValue());
664 File.Source = Source;
668 // return the allocated FileNumber.
672 /// Utility function to emit the encoding to a streamer.
673 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
674 int64_t LineDelta, uint64_t AddrDelta) {
675 MCContext &Context = MCOS->getContext();
676 SmallString<256> Tmp;
677 raw_svector_ostream OS(Tmp);
678 MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS);
679 MCOS->emitBytes(OS.str());
682 /// Given a special op, return the address skip amount (in units of
683 /// DWARF2_LINE_MIN_INSN_LENGTH).
684 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
685 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
688 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
689 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params,
690 int64_t LineDelta, uint64_t AddrDelta,
692 uint64_t Temp, Opcode;
693 bool NeedCopy = false;
695 // The maximum address skip amount that can be encoded with a special op.
696 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
698 // Scale the address delta by the minimum instruction length.
699 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
701 // A LineDelta of INT64_MAX is a signal that this is actually a
702 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
703 // end_sequence to emit the matrix entry.
704 if (LineDelta == INT64_MAX) {
705 if (AddrDelta == MaxSpecialAddrDelta)
706 OS << char(dwarf::DW_LNS_const_add_pc);
707 else if (AddrDelta) {
708 OS << char(dwarf::DW_LNS_advance_pc);
709 encodeULEB128(AddrDelta, OS);
711 OS << char(dwarf::DW_LNS_extended_op);
713 OS << char(dwarf::DW_LNE_end_sequence);
717 // Bias the line delta by the base.
718 Temp = LineDelta - Params.DWARF2LineBase;
720 // If the line increment is out of range of a special opcode, we must encode
721 // it with DW_LNS_advance_line.
722 if (Temp >= Params.DWARF2LineRange ||
723 Temp + Params.DWARF2LineOpcodeBase > 255) {
724 OS << char(dwarf::DW_LNS_advance_line);
725 encodeSLEB128(LineDelta, OS);
728 Temp = 0 - Params.DWARF2LineBase;
732 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
733 if (LineDelta == 0 && AddrDelta == 0) {
734 OS << char(dwarf::DW_LNS_copy);
738 // Bias the opcode by the special opcode base.
739 Temp += Params.DWARF2LineOpcodeBase;
741 // Avoid overflow when addr_delta is large.
742 if (AddrDelta < 256 + MaxSpecialAddrDelta) {
743 // Try using a special opcode.
744 Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
750 // Try using DW_LNS_const_add_pc followed by special op.
751 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
753 OS << char(dwarf::DW_LNS_const_add_pc);
759 // Otherwise use DW_LNS_advance_pc.
760 OS << char(dwarf::DW_LNS_advance_pc);
761 encodeULEB128(AddrDelta, OS);
764 OS << char(dwarf::DW_LNS_copy);
766 assert(Temp <= 255 && "Buggy special opcode encoding.");
771 bool MCDwarfLineAddr::FixedEncode(MCContext &Context,
772 MCDwarfLineTableParams Params,
773 int64_t LineDelta, uint64_t AddrDelta,
775 uint32_t *Offset, uint32_t *Size) {
776 if (LineDelta != INT64_MAX) {
777 OS << char(dwarf::DW_LNS_advance_line);
778 encodeSLEB128(LineDelta, OS);
781 // Use address delta to adjust address or use absolute address to adjust
784 // According to DWARF spec., the DW_LNS_fixed_advance_pc opcode takes a
785 // single uhalf (unencoded) operand. So, the maximum value of AddrDelta
786 // is 65535. We set a conservative upper bound for it for relaxation.
787 if (AddrDelta > 60000) {
788 const MCAsmInfo *asmInfo = Context.getAsmInfo();
789 unsigned AddrSize = asmInfo->getCodePointerSize();
791 OS << char(dwarf::DW_LNS_extended_op);
792 encodeULEB128(1 + AddrSize, OS);
793 OS << char(dwarf::DW_LNE_set_address);
794 // Generate fixup for the address.
798 OS.write_zeros(AddrSize);
800 OS << char(dwarf::DW_LNS_fixed_advance_pc);
801 // Generate fixup for 2-bytes address delta.
809 if (LineDelta == INT64_MAX) {
810 OS << char(dwarf::DW_LNS_extended_op);
812 OS << char(dwarf::DW_LNE_end_sequence);
814 OS << char(dwarf::DW_LNS_copy);
820 // Utility function to write a tuple for .debug_abbrev.
821 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
822 MCOS->emitULEB128IntValue(Name);
823 MCOS->emitULEB128IntValue(Form);
826 // When generating dwarf for assembly source files this emits
827 // the data for .debug_abbrev section which contains three DIEs.
828 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
829 MCContext &context = MCOS->getContext();
830 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
832 // DW_TAG_compile_unit DIE abbrev (1).
833 MCOS->emitULEB128IntValue(1);
834 MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
835 MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
836 dwarf::Form SecOffsetForm =
837 context.getDwarfVersion() >= 4
838 ? dwarf::DW_FORM_sec_offset
839 : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
840 : dwarf::DW_FORM_data4);
841 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
842 if (context.getGenDwarfSectionSyms().size() > 1 &&
843 context.getDwarfVersion() >= 3) {
844 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
846 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
847 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
849 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
850 if (!context.getCompilationDir().empty())
851 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
852 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
853 if (!DwarfDebugFlags.empty())
854 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
855 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
856 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
857 EmitAbbrev(MCOS, 0, 0);
859 // DW_TAG_label DIE abbrev (2).
860 MCOS->emitULEB128IntValue(2);
861 MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
862 MCOS->emitInt8(dwarf::DW_CHILDREN_no);
863 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
864 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
865 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
866 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
867 EmitAbbrev(MCOS, 0, 0);
869 // Terminate the abbreviations for this compilation unit.
873 // When generating dwarf for assembly source files this emits the data for
874 // .debug_aranges section. This section contains a header and a table of pairs
875 // of PointerSize'ed values for the address and size of section(s) with line
877 static void EmitGenDwarfAranges(MCStreamer *MCOS,
878 const MCSymbol *InfoSectionSymbol) {
879 MCContext &context = MCOS->getContext();
881 auto &Sections = context.getGenDwarfSectionSyms();
883 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
885 unsigned UnitLengthBytes =
886 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
887 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
889 // This will be the length of the .debug_aranges section, first account for
890 // the size of each item in the header (see below where we emit these items).
891 int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
893 // Figure the padding after the header before the table of address and size
894 // pairs who's values are PointerSize'ed.
895 const MCAsmInfo *asmInfo = context.getAsmInfo();
896 int AddrSize = asmInfo->getCodePointerSize();
897 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
898 if (Pad == 2 * AddrSize)
902 // Add the size of the pair of PointerSize'ed values for the address and size
903 // of each section we have in the table.
904 Length += 2 * AddrSize * Sections.size();
905 // And the pair of terminating zeros.
906 Length += 2 * AddrSize;
908 // Emit the header for this section.
909 if (context.getDwarfFormat() == dwarf::DWARF64)
911 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
912 // The 4 (8 for DWARF64) byte length not including the length of the unit
913 // length field itself.
914 MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
915 // The 2 byte version, which is 2.
917 // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
918 // from the start of the .debug_info.
919 if (InfoSectionSymbol)
920 MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
921 asmInfo->needsDwarfSectionOffsetDirective());
923 MCOS->emitIntValue(0, OffsetSize);
924 // The 1 byte size of an address.
925 MCOS->emitInt8(AddrSize);
926 // The 1 byte size of a segment descriptor, we use a value of zero.
928 // Align the header with the padding if needed, before we put out the table.
929 for(int i = 0; i < Pad; i++)
932 // Now emit the table of pairs of PointerSize'ed values for the section
933 // addresses and sizes.
934 for (MCSection *Sec : Sections) {
935 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
936 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
937 assert(StartSymbol && "StartSymbol must not be NULL");
938 assert(EndSymbol && "EndSymbol must not be NULL");
940 const MCExpr *Addr = MCSymbolRefExpr::create(
941 StartSymbol, MCSymbolRefExpr::VK_None, context);
943 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
944 MCOS->emitValue(Addr, AddrSize);
945 emitAbsValue(*MCOS, Size, AddrSize);
948 // And finally the pair of terminating zeros.
949 MCOS->emitIntValue(0, AddrSize);
950 MCOS->emitIntValue(0, AddrSize);
953 // When generating dwarf for assembly source files this emits the data for
954 // .debug_info section which contains three parts. The header, the compile_unit
955 // DIE and a list of label DIEs.
956 static void EmitGenDwarfInfo(MCStreamer *MCOS,
957 const MCSymbol *AbbrevSectionSymbol,
958 const MCSymbol *LineSectionSymbol,
959 const MCSymbol *RangesSymbol) {
960 MCContext &context = MCOS->getContext();
962 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
964 // Create a symbol at the start and end of this section used in here for the
965 // expression to calculate the length in the header.
966 MCSymbol *InfoStart = context.createTempSymbol();
967 MCOS->emitLabel(InfoStart);
968 MCSymbol *InfoEnd = context.createTempSymbol();
970 // First part: the header.
972 unsigned UnitLengthBytes =
973 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
974 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
976 if (context.getDwarfFormat() == dwarf::DWARF64)
977 // Emit DWARF64 mark.
978 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
980 // The 4 (8 for DWARF64) byte total length of the information for this
981 // compilation unit, not including the unit length field itself.
982 const MCExpr *Length =
983 makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
984 emitAbsValue(*MCOS, Length, OffsetSize);
986 // The 2 byte DWARF version.
987 MCOS->emitInt16(context.getDwarfVersion());
989 // The DWARF v5 header has unit type, address size, abbrev offset.
990 // Earlier versions have abbrev offset, address size.
991 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
992 int AddrSize = AsmInfo.getCodePointerSize();
993 if (context.getDwarfVersion() >= 5) {
994 MCOS->emitInt8(dwarf::DW_UT_compile);
995 MCOS->emitInt8(AddrSize);
997 // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
998 // the .debug_abbrev.
999 if (AbbrevSectionSymbol)
1000 MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
1001 AsmInfo.needsDwarfSectionOffsetDirective());
1003 // Since the abbrevs are at the start of the section, the offset is zero.
1004 MCOS->emitIntValue(0, OffsetSize);
1005 if (context.getDwarfVersion() <= 4)
1006 MCOS->emitInt8(AddrSize);
1008 // Second part: the compile_unit DIE.
1010 // The DW_TAG_compile_unit DIE abbrev (1).
1011 MCOS->emitULEB128IntValue(1);
1013 // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
1014 // .debug_line section.
1015 if (LineSectionSymbol)
1016 MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
1017 AsmInfo.needsDwarfSectionOffsetDirective());
1019 // The line table is at the start of the section, so the offset is zero.
1020 MCOS->emitIntValue(0, OffsetSize);
1023 // There are multiple sections containing code, so we must use
1024 // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
1025 // start of the .debug_ranges/.debug_rnglists.
1026 MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
1028 // If we only have one non-empty code section, we can use the simpler
1029 // AT_low_pc and AT_high_pc attributes.
1031 // Find the first (and only) non-empty text section
1032 auto &Sections = context.getGenDwarfSectionSyms();
1033 const auto TextSection = Sections.begin();
1034 assert(TextSection != Sections.end() && "No text section found");
1036 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
1037 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
1038 assert(StartSymbol && "StartSymbol must not be NULL");
1039 assert(EndSymbol && "EndSymbol must not be NULL");
1041 // AT_low_pc, the first address of the default .text section.
1042 const MCExpr *Start = MCSymbolRefExpr::create(
1043 StartSymbol, MCSymbolRefExpr::VK_None, context);
1044 MCOS->emitValue(Start, AddrSize);
1046 // AT_high_pc, the last address of the default .text section.
1047 const MCExpr *End = MCSymbolRefExpr::create(
1048 EndSymbol, MCSymbolRefExpr::VK_None, context);
1049 MCOS->emitValue(End, AddrSize);
1052 // AT_name, the name of the source file. Reconstruct from the first directory
1053 // and file table entries.
1054 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
1055 if (MCDwarfDirs.size() > 0) {
1056 MCOS->emitBytes(MCDwarfDirs[0]);
1057 MCOS->emitBytes(sys::path::get_separator());
1059 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
1060 // MCDwarfFiles might be empty if we have an empty source file.
1061 // If it's not empty, [0] is unused and [1] is the first actual file.
1062 assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
1063 const MCDwarfFile &RootFile =
1064 MCDwarfFiles.empty()
1065 ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
1067 MCOS->emitBytes(RootFile.Name);
1068 MCOS->emitInt8(0); // NULL byte to terminate the string.
1070 // AT_comp_dir, the working directory the assembly was done in.
1071 if (!context.getCompilationDir().empty()) {
1072 MCOS->emitBytes(context.getCompilationDir());
1073 MCOS->emitInt8(0); // NULL byte to terminate the string.
1076 // AT_APPLE_flags, the command line arguments of the assembler tool.
1077 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
1078 if (!DwarfDebugFlags.empty()){
1079 MCOS->emitBytes(DwarfDebugFlags);
1080 MCOS->emitInt8(0); // NULL byte to terminate the string.
1083 // AT_producer, the version of the assembler tool.
1084 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
1085 if (!DwarfDebugProducer.empty())
1086 MCOS->emitBytes(DwarfDebugProducer);
1088 MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
1089 MCOS->emitInt8(0); // NULL byte to terminate the string.
1091 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
1092 // draft has no standard code for assembler.
1093 MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
1095 // Third part: the list of label DIEs.
1097 // Loop on saved info for dwarf labels and create the DIEs for them.
1098 const std::vector<MCGenDwarfLabelEntry> &Entries =
1099 MCOS->getContext().getMCGenDwarfLabelEntries();
1100 for (const auto &Entry : Entries) {
1101 // The DW_TAG_label DIE abbrev (2).
1102 MCOS->emitULEB128IntValue(2);
1104 // AT_name, of the label without any leading underbar.
1105 MCOS->emitBytes(Entry.getName());
1106 MCOS->emitInt8(0); // NULL byte to terminate the string.
1108 // AT_decl_file, index into the file table.
1109 MCOS->emitInt32(Entry.getFileNumber());
1111 // AT_decl_line, source line number.
1112 MCOS->emitInt32(Entry.getLineNumber());
1114 // AT_low_pc, start address of the label.
1115 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
1116 MCSymbolRefExpr::VK_None, context);
1117 MCOS->emitValue(AT_low_pc, AddrSize);
1120 // Add the NULL DIE terminating the Compile Unit DIE's.
1123 // Now set the value of the symbol at the end of the info section.
1124 MCOS->emitLabel(InfoEnd);
1127 // When generating dwarf for assembly source files this emits the data for
1128 // .debug_ranges section. We only emit one range list, which spans all of the
1129 // executable sections of this file.
1130 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
1131 MCContext &context = MCOS->getContext();
1132 auto &Sections = context.getGenDwarfSectionSyms();
1134 const MCAsmInfo *AsmInfo = context.getAsmInfo();
1135 int AddrSize = AsmInfo->getCodePointerSize();
1136 MCSymbol *RangesSymbol;
1138 if (MCOS->getContext().getDwarfVersion() >= 5) {
1139 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
1140 MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
1141 MCOS->AddComment("Offset entry count");
1143 RangesSymbol = context.createTempSymbol("debug_rnglist0_start", true, true);
1144 MCOS->emitLabel(RangesSymbol);
1145 for (MCSection *Sec : Sections) {
1146 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1147 const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1148 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1149 StartSymbol, MCSymbolRefExpr::VK_None, context);
1150 const MCExpr *SectionSize =
1151 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1152 MCOS->emitInt8(dwarf::DW_RLE_start_length);
1153 MCOS->emitValue(SectionStartAddr, AddrSize);
1154 MCOS->emitULEB128Value(SectionSize);
1156 MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
1157 MCOS->emitLabel(EndSymbol);
1159 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
1160 RangesSymbol = context.createTempSymbol("debug_ranges_start", true, true);
1161 MCOS->emitLabel(RangesSymbol);
1162 for (MCSection *Sec : Sections) {
1163 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1164 const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1166 // Emit a base address selection entry for the section start.
1167 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1168 StartSymbol, MCSymbolRefExpr::VK_None, context);
1169 MCOS->emitFill(AddrSize, 0xFF);
1170 MCOS->emitValue(SectionStartAddr, AddrSize);
1172 // Emit a range list entry spanning this section.
1173 const MCExpr *SectionSize =
1174 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1175 MCOS->emitIntValue(0, AddrSize);
1176 emitAbsValue(*MCOS, SectionSize, AddrSize);
1179 // Emit end of list entry
1180 MCOS->emitIntValue(0, AddrSize);
1181 MCOS->emitIntValue(0, AddrSize);
1184 return RangesSymbol;
1188 // When generating dwarf for assembly source files this emits the Dwarf
1191 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
1192 MCContext &context = MCOS->getContext();
1194 // Create the dwarf sections in this order (.debug_line already created).
1195 const MCAsmInfo *AsmInfo = context.getAsmInfo();
1196 bool CreateDwarfSectionSymbols =
1197 AsmInfo->doesDwarfUseRelocationsAcrossSections();
1198 MCSymbol *LineSectionSymbol = nullptr;
1199 if (CreateDwarfSectionSymbols)
1200 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
1201 MCSymbol *AbbrevSectionSymbol = nullptr;
1202 MCSymbol *InfoSectionSymbol = nullptr;
1203 MCSymbol *RangesSymbol = nullptr;
1205 // Create end symbols for each section, and remove empty sections
1206 MCOS->getContext().finalizeDwarfSections(*MCOS);
1208 // If there are no sections to generate debug info for, we don't need
1210 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
1213 // We only use the .debug_ranges section if we have multiple code sections,
1214 // and we are emitting a DWARF version which supports it.
1215 const bool UseRangesSection =
1216 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
1217 MCOS->getContext().getDwarfVersion() >= 3;
1218 CreateDwarfSectionSymbols |= UseRangesSection;
1220 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
1221 if (CreateDwarfSectionSymbols) {
1222 InfoSectionSymbol = context.createTempSymbol();
1223 MCOS->emitLabel(InfoSectionSymbol);
1225 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
1226 if (CreateDwarfSectionSymbols) {
1227 AbbrevSectionSymbol = context.createTempSymbol();
1228 MCOS->emitLabel(AbbrevSectionSymbol);
1231 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
1233 // Output the data for .debug_aranges section.
1234 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
1236 if (UseRangesSection) {
1237 RangesSymbol = emitGenDwarfRanges(MCOS);
1238 assert(RangesSymbol);
1241 // Output the data for .debug_abbrev section.
1242 EmitGenDwarfAbbrev(MCOS);
1244 // Output the data for .debug_info section.
1245 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
1249 // When generating dwarf for assembly source files this is called when symbol
1250 // for a label is created. If this symbol is not a temporary and is in the
1251 // section that dwarf is being generated for, save the needed info to create
1254 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
1255 SourceMgr &SrcMgr, SMLoc &Loc) {
1256 // We won't create dwarf labels for temporary symbols.
1257 if (Symbol->isTemporary())
1259 MCContext &context = MCOS->getContext();
1260 // We won't create dwarf labels for symbols in sections that we are not
1261 // generating debug info for.
1262 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
1265 // The dwarf label's name does not have the symbol name's leading
1267 StringRef Name = Symbol->getName();
1268 if (Name.startswith("_"))
1269 Name = Name.substr(1, Name.size()-1);
1271 // Get the dwarf file number to be used for the dwarf label.
1272 unsigned FileNumber = context.getGenDwarfFileNumber();
1274 // Finding the line number is the expensive part which is why we just don't
1275 // pass it in as for some symbols we won't create a dwarf label.
1276 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
1277 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
1279 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
1280 // values so that they don't have things like an ARM thumb bit from the
1281 // original symbol. So when used they won't get a low bit set after
1283 MCSymbol *Label = context.createTempSymbol();
1284 MCOS->emitLabel(Label);
1286 // Create and entry for the info and add it to the other entries.
1287 MCOS->getContext().addMCGenDwarfLabelEntry(
1288 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
1291 static int getDataAlignmentFactor(MCStreamer &streamer) {
1292 MCContext &context = streamer.getContext();
1293 const MCAsmInfo *asmInfo = context.getAsmInfo();
1294 int size = asmInfo->getCalleeSaveStackSlotSize();
1295 if (asmInfo->isStackGrowthDirectionUp())
1301 static unsigned getSizeForEncoding(MCStreamer &streamer,
1302 unsigned symbolEncoding) {
1303 MCContext &context = streamer.getContext();
1304 unsigned format = symbolEncoding & 0x0f;
1306 default: llvm_unreachable("Unknown Encoding");
1307 case dwarf::DW_EH_PE_absptr:
1308 case dwarf::DW_EH_PE_signed:
1309 return context.getAsmInfo()->getCodePointerSize();
1310 case dwarf::DW_EH_PE_udata2:
1311 case dwarf::DW_EH_PE_sdata2:
1313 case dwarf::DW_EH_PE_udata4:
1314 case dwarf::DW_EH_PE_sdata4:
1316 case dwarf::DW_EH_PE_udata8:
1317 case dwarf::DW_EH_PE_sdata8:
1322 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
1323 unsigned symbolEncoding, bool isEH) {
1324 MCContext &context = streamer.getContext();
1325 const MCAsmInfo *asmInfo = context.getAsmInfo();
1326 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
1329 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1330 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
1331 emitAbsValue(streamer, v, size);
1333 streamer.emitValue(v, size);
1336 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1337 unsigned symbolEncoding) {
1338 MCContext &context = streamer.getContext();
1339 const MCAsmInfo *asmInfo = context.getAsmInfo();
1340 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1343 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1344 streamer.emitValue(v, size);
1349 class FrameEmitterImpl {
1351 int InitialCFAOffset = 0;
1353 MCObjectStreamer &Streamer;
1356 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
1357 : IsEH(IsEH), Streamer(Streamer) {}
1359 /// Emit the unwind information in a compact way.
1360 void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
1362 const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
1363 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
1364 bool LastInSection, const MCSymbol &SectionStart);
1365 void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1366 MCSymbol *BaseLabel);
1367 void emitCFIInstruction(const MCCFIInstruction &Instr);
1370 } // end anonymous namespace
1372 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1373 Streamer.emitInt8(Encoding);
1376 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
1377 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1378 auto *MRI = Streamer.getContext().getRegisterInfo();
1380 switch (Instr.getOperation()) {
1381 case MCCFIInstruction::OpRegister: {
1382 unsigned Reg1 = Instr.getRegister();
1383 unsigned Reg2 = Instr.getRegister2();
1385 Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
1386 Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
1388 Streamer.emitInt8(dwarf::DW_CFA_register);
1389 Streamer.emitULEB128IntValue(Reg1);
1390 Streamer.emitULEB128IntValue(Reg2);
1393 case MCCFIInstruction::OpWindowSave:
1394 Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
1397 case MCCFIInstruction::OpNegateRAState:
1398 Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
1401 case MCCFIInstruction::OpUndefined: {
1402 unsigned Reg = Instr.getRegister();
1403 Streamer.emitInt8(dwarf::DW_CFA_undefined);
1404 Streamer.emitULEB128IntValue(Reg);
1407 case MCCFIInstruction::OpAdjustCfaOffset:
1408 case MCCFIInstruction::OpDefCfaOffset: {
1409 const bool IsRelative =
1410 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1412 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
1415 CFAOffset += Instr.getOffset();
1417 CFAOffset = Instr.getOffset();
1419 Streamer.emitULEB128IntValue(CFAOffset);
1423 case MCCFIInstruction::OpDefCfa: {
1424 unsigned Reg = Instr.getRegister();
1426 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1427 Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
1428 Streamer.emitULEB128IntValue(Reg);
1429 CFAOffset = Instr.getOffset();
1430 Streamer.emitULEB128IntValue(CFAOffset);
1434 case MCCFIInstruction::OpDefCfaRegister: {
1435 unsigned Reg = Instr.getRegister();
1437 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1438 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
1439 Streamer.emitULEB128IntValue(Reg);
1443 case MCCFIInstruction::OpOffset:
1444 case MCCFIInstruction::OpRelOffset: {
1445 const bool IsRelative =
1446 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1448 unsigned Reg = Instr.getRegister();
1450 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1452 int Offset = Instr.getOffset();
1454 Offset -= CFAOffset;
1455 Offset = Offset / dataAlignmentFactor;
1458 Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
1459 Streamer.emitULEB128IntValue(Reg);
1460 Streamer.emitSLEB128IntValue(Offset);
1461 } else if (Reg < 64) {
1462 Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
1463 Streamer.emitULEB128IntValue(Offset);
1465 Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
1466 Streamer.emitULEB128IntValue(Reg);
1467 Streamer.emitULEB128IntValue(Offset);
1471 case MCCFIInstruction::OpRememberState:
1472 Streamer.emitInt8(dwarf::DW_CFA_remember_state);
1474 case MCCFIInstruction::OpRestoreState:
1475 Streamer.emitInt8(dwarf::DW_CFA_restore_state);
1477 case MCCFIInstruction::OpSameValue: {
1478 unsigned Reg = Instr.getRegister();
1479 Streamer.emitInt8(dwarf::DW_CFA_same_value);
1480 Streamer.emitULEB128IntValue(Reg);
1483 case MCCFIInstruction::OpRestore: {
1484 unsigned Reg = Instr.getRegister();
1486 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1488 Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
1490 Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
1491 Streamer.emitULEB128IntValue(Reg);
1495 case MCCFIInstruction::OpGnuArgsSize:
1496 Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
1497 Streamer.emitULEB128IntValue(Instr.getOffset());
1500 case MCCFIInstruction::OpEscape:
1501 Streamer.emitBytes(Instr.getValues());
1504 llvm_unreachable("Unhandled case in switch");
1507 /// Emit frame instructions to describe the layout of the frame.
1508 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1509 MCSymbol *BaseLabel) {
1510 for (const MCCFIInstruction &Instr : Instrs) {
1511 MCSymbol *Label = Instr.getLabel();
1512 // Throw out move if the label is invalid.
1513 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1515 // Advance row if new location.
1516 if (BaseLabel && Label) {
1517 MCSymbol *ThisSym = Label;
1518 if (ThisSym != BaseLabel) {
1519 Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1520 BaseLabel = ThisSym;
1524 emitCFIInstruction(Instr);
1528 /// Emit the unwind information in a compact way.
1529 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
1530 MCContext &Context = Streamer.getContext();
1531 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1533 // range-start range-length compact-unwind-enc personality-func lsda
1534 // _foo LfooEnd-_foo 0x00000023 0 0
1535 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1537 // .section __LD,__compact_unwind,regular,debug
1539 // # compact unwind for _foo
1541 // .set L1,LfooEnd-_foo
1547 // # compact unwind for _bar
1549 // .set L2,LbarEnd-_bar
1552 // .quad __gxx_personality
1553 // .quad except_tab1
1555 uint32_t Encoding = Frame.CompactUnwindEncoding;
1556 if (!Encoding) return;
1557 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1559 // The encoding needs to know we have an LSDA.
1560 if (!DwarfEHFrameOnly && Frame.Lsda)
1561 Encoding |= 0x40000000;
1564 unsigned FDEEncoding = MOFI->getFDEEncoding();
1565 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1566 Streamer.emitSymbolValue(Frame.Begin, Size);
1569 const MCExpr *Range =
1570 makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
1571 emitAbsValue(Streamer, Range, 4);
1574 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1575 Streamer.emitIntValue(Encoding, Size);
1577 // Personality Function
1578 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1579 if (!DwarfEHFrameOnly && Frame.Personality)
1580 Streamer.emitSymbolValue(Frame.Personality, Size);
1582 Streamer.emitIntValue(0, Size); // No personality fn
1585 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1586 if (!DwarfEHFrameOnly && Frame.Lsda)
1587 Streamer.emitSymbolValue(Frame.Lsda, Size);
1589 Streamer.emitIntValue(0, Size); // No LSDA
1592 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1595 switch (DwarfVersion) {
1604 llvm_unreachable("Unknown version");
1607 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
1608 MCContext &context = Streamer.getContext();
1609 const MCRegisterInfo *MRI = context.getRegisterInfo();
1610 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1612 MCSymbol *sectionStart = context.createTempSymbol();
1613 Streamer.emitLabel(sectionStart);
1615 MCSymbol *sectionEnd = context.createTempSymbol();
1617 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1618 unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
1619 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1620 bool IsDwarf64 = Format == dwarf::DWARF64;
1624 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1627 const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
1628 *sectionEnd, UnitLengthBytes);
1629 emitAbsValue(Streamer, Length, OffsetSize);
1633 IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
1634 Streamer.emitIntValue(CIE_ID, OffsetSize);
1637 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1638 Streamer.emitInt8(CIEVersion);
1641 SmallString<8> Augmentation;
1642 Augmentation += "z";
1643 if (Frame.Personality)
1644 Augmentation += "P";
1646 Augmentation += "L";
1647 Augmentation += "R";
1648 if (Frame.IsSignalFrame)
1649 Augmentation += "S";
1650 if (Frame.IsBKeyFrame)
1651 Augmentation += "B";
1652 Streamer.emitBytes(Augmentation);
1654 Streamer.emitInt8(0);
1656 if (CIEVersion >= 4) {
1658 Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
1660 // Segment Descriptor Size
1661 Streamer.emitInt8(0);
1664 // Code Alignment Factor
1665 Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1667 // Data Alignment Factor
1668 Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
1670 // Return Address Register
1671 unsigned RAReg = Frame.RAReg;
1672 if (RAReg == static_cast<unsigned>(INT_MAX))
1673 RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
1675 if (CIEVersion == 1) {
1676 assert(RAReg <= 255 &&
1677 "DWARF 2 encodes return_address_register in one byte");
1678 Streamer.emitInt8(RAReg);
1680 Streamer.emitULEB128IntValue(RAReg);
1683 // Augmentation Data Length (optional)
1684 unsigned augmentationLength = 0;
1686 if (Frame.Personality) {
1687 // Personality Encoding
1688 augmentationLength += 1;
1690 augmentationLength +=
1691 getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
1694 augmentationLength += 1;
1695 // Encoding of the FDE pointers
1696 augmentationLength += 1;
1698 Streamer.emitULEB128IntValue(augmentationLength);
1700 // Augmentation Data (optional)
1701 if (Frame.Personality) {
1702 // Personality Encoding
1703 emitEncodingByte(Streamer, Frame.PersonalityEncoding);
1705 EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
1709 emitEncodingByte(Streamer, Frame.LsdaEncoding);
1711 // Encoding of the FDE pointers
1712 emitEncodingByte(Streamer, MOFI->getFDEEncoding());
1715 // Initial Instructions
1717 const MCAsmInfo *MAI = context.getAsmInfo();
1718 if (!Frame.IsSimple) {
1719 const std::vector<MCCFIInstruction> &Instructions =
1720 MAI->getInitialFrameState();
1721 emitCFIInstructions(Instructions, nullptr);
1724 InitialCFAOffset = CFAOffset;
1727 Streamer.emitValueToAlignment(IsEH ? 4 : MAI->getCodePointerSize());
1729 Streamer.emitLabel(sectionEnd);
1730 return *sectionStart;
1733 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
1734 const MCDwarfFrameInfo &frame,
1736 const MCSymbol &SectionStart) {
1737 MCContext &context = Streamer.getContext();
1738 MCSymbol *fdeStart = context.createTempSymbol();
1739 MCSymbol *fdeEnd = context.createTempSymbol();
1740 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1742 CFAOffset = InitialCFAOffset;
1744 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1745 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1747 if (Format == dwarf::DWARF64)
1749 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1752 const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
1753 emitAbsValue(Streamer, Length, OffsetSize);
1755 Streamer.emitLabel(fdeStart);
1758 const MCAsmInfo *asmInfo = context.getAsmInfo();
1760 const MCExpr *offset =
1761 makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
1762 emitAbsValue(Streamer, offset, OffsetSize);
1763 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1764 const MCExpr *offset =
1765 makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
1766 emitAbsValue(Streamer, offset, OffsetSize);
1768 Streamer.emitSymbolValue(&cieStart, OffsetSize,
1769 asmInfo->needsDwarfSectionOffsetDirective());
1773 unsigned PCEncoding =
1774 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1775 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
1776 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
1779 const MCExpr *Range =
1780 makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
1781 emitAbsValue(Streamer, Range, PCSize);
1784 // Augmentation Data Length
1785 unsigned augmentationLength = 0;
1788 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
1790 Streamer.emitULEB128IntValue(augmentationLength);
1792 // Augmentation Data
1794 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
1797 // Call Frame Instructions
1798 emitCFIInstructions(frame.Instructions, frame.Begin);
1801 // The size of a .eh_frame section has to be a multiple of the alignment
1802 // since a null CIE is interpreted as the end. Old systems overaligned
1803 // .eh_frame, so we do too and account for it in the last FDE.
1804 unsigned Align = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
1805 Streamer.emitValueToAlignment(Align);
1807 Streamer.emitLabel(fdeEnd);
1813 static const CIEKey getEmptyKey() {
1814 return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX),
1818 static const CIEKey getTombstoneKey() {
1819 return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX),
1823 CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
1824 unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple,
1825 unsigned RAReg, bool IsBKeyFrame)
1826 : Personality(Personality), PersonalityEncoding(PersonalityEncoding),
1827 LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame),
1828 IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame) {}
1830 explicit CIEKey(const MCDwarfFrameInfo &Frame)
1831 : Personality(Frame.Personality),
1832 PersonalityEncoding(Frame.PersonalityEncoding),
1833 LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
1834 IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
1835 IsBKeyFrame(Frame.IsBKeyFrame) {}
1837 StringRef PersonalityName() const {
1840 return Personality->getName();
1843 bool operator<(const CIEKey &Other) const {
1844 return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
1845 IsSignalFrame, IsSimple, RAReg) <
1846 std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
1847 Other.LsdaEncoding, Other.IsSignalFrame,
1848 Other.IsSimple, Other.RAReg);
1851 const MCSymbol *Personality;
1852 unsigned PersonalityEncoding;
1853 unsigned LsdaEncoding;
1860 } // end anonymous namespace
1864 template <> struct DenseMapInfo<CIEKey> {
1865 static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); }
1866 static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); }
1868 static unsigned getHashValue(const CIEKey &Key) {
1869 return static_cast<unsigned>(hash_combine(
1870 Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding,
1871 Key.IsSignalFrame, Key.IsSimple, Key.RAReg, Key.IsBKeyFrame));
1874 static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) {
1875 return LHS.Personality == RHS.Personality &&
1876 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1877 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1878 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1879 LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg &&
1880 LHS.IsBKeyFrame == RHS.IsBKeyFrame;
1884 } // end namespace llvm
1886 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1888 Streamer.generateCompactUnwindEncodings(MAB);
1890 MCContext &Context = Streamer.getContext();
1891 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1892 const MCAsmInfo *AsmInfo = Context.getAsmInfo();
1893 FrameEmitterImpl Emitter(IsEH, Streamer);
1894 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1896 // Emit the compact unwind info if available.
1897 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1898 if (IsEH && MOFI->getCompactUnwindSection()) {
1899 bool SectionEmitted = false;
1900 for (const MCDwarfFrameInfo &Frame : FrameArray) {
1901 if (Frame.CompactUnwindEncoding == 0) continue;
1902 if (!SectionEmitted) {
1903 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1904 Streamer.emitValueToAlignment(AsmInfo->getCodePointerSize());
1905 SectionEmitted = true;
1907 NeedsEHFrameSection |=
1908 Frame.CompactUnwindEncoding ==
1909 MOFI->getCompactUnwindDwarfEHFrameOnly();
1910 Emitter.EmitCompactUnwind(Frame);
1914 if (!NeedsEHFrameSection) return;
1916 MCSection &Section =
1917 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1918 : *MOFI->getDwarfFrameSection();
1920 Streamer.SwitchSection(&Section);
1921 MCSymbol *SectionStart = Context.createTempSymbol();
1922 Streamer.emitLabel(SectionStart);
1924 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1926 const MCSymbol *DummyDebugKey = nullptr;
1927 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
1928 // Sort the FDEs by their corresponding CIE before we emit them.
1929 // This isn't technically necessary according to the DWARF standard,
1930 // but the Android libunwindstack rejects eh_frame sections where
1931 // an FDE refers to a CIE other than the closest previous CIE.
1932 std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
1933 llvm::stable_sort(FrameArrayX,
1934 [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
1935 return CIEKey(X) < CIEKey(Y);
1937 for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
1938 const MCDwarfFrameInfo &Frame = *I;
1940 if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
1941 MOFI->getCompactUnwindDwarfEHFrameOnly())
1942 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1943 // of by the compact unwind encoding.
1947 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1949 CIEStart = &Emitter.EmitCIE(Frame);
1951 Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart);
1955 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1956 uint64_t AddrDelta) {
1957 MCContext &Context = Streamer.getContext();
1958 SmallString<256> Tmp;
1959 raw_svector_ostream OS(Tmp);
1960 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1961 Streamer.emitBytes(OS.str());
1964 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1965 uint64_t AddrDelta, raw_ostream &OS,
1966 uint32_t *Offset, uint32_t *Size) {
1967 // Scale the address delta by the minimum instruction length.
1968 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1970 bool WithFixups = false;
1974 support::endianness E =
1975 Context.getAsmInfo()->isLittleEndian() ? support::little : support::big;
1976 if (AddrDelta == 0) {
1981 } else if (isUIntN(6, AddrDelta)) {
1982 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1984 *Offset = OS.tell();
1986 OS << uint8_t(dwarf::DW_CFA_advance_loc);
1989 } else if (isUInt<8>(AddrDelta)) {
1990 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1992 *Offset = OS.tell();
1996 OS << uint8_t(AddrDelta);
1997 } else if (isUInt<16>(AddrDelta)) {
1998 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
2000 *Offset = OS.tell();
2004 support::endian::write<uint16_t>(OS, AddrDelta, E);
2006 assert(isUInt<32>(AddrDelta));
2007 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
2009 *Offset = OS.tell();
2013 support::endian::write<uint32_t>(OS, AddrDelta, E);