[RISCV] Refactor predicates for rvv intrinsic patterns.
[llvm-project.git] / llvm / lib / MC / MCDwarf.cpp
blob9506b5cd59297ca9257f9c8d5f073f87b6791629
1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/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/STLExtras.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCObjectStreamer.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/Endian.h"
31 #include "llvm/Support/EndianStream.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/LEB128.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <cassert>
39 #include <cstdint>
40 #include <optional>
41 #include <string>
42 #include <utility>
43 #include <vector>
45 using namespace llvm;
47 MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
48 MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start");
49 MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end");
50 auto DwarfFormat = S.getContext().getDwarfFormat();
51 if (DwarfFormat == dwarf::DWARF64) {
52 S.AddComment("DWARF64 mark");
53 S.emitInt32(dwarf::DW_LENGTH_DWARF64);
55 S.AddComment("Length");
56 S.emitAbsoluteSymbolDiff(End, Start,
57 dwarf::getDwarfOffsetByteSize(DwarfFormat));
58 S.emitLabel(Start);
59 S.AddComment("Version");
60 S.emitInt16(S.getContext().getDwarfVersion());
61 S.AddComment("Address size");
62 S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());
63 S.AddComment("Segment selector size");
64 S.emitInt8(0);
65 return End;
68 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
69 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
70 if (MinInsnLength == 1)
71 return AddrDelta;
72 if (AddrDelta % MinInsnLength != 0) {
73 // TODO: report this error, but really only once.
76 return AddrDelta / MinInsnLength;
79 MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) {
80 UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
81 if (UseRelocs) {
82 MCSection *DwarfLineStrSection =
83 Ctx.getObjectFileInfo()->getDwarfLineStrSection();
84 assert(DwarfLineStrSection && "DwarfLineStrSection must not be NULL");
85 LineStrLabel = DwarfLineStrSection->getBeginSymbol();
90 // This is called when an instruction is assembled into the specified section
91 // and if there is information from the last .loc directive that has yet to have
92 // a line entry made for it is made.
94 void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) {
95 if (!MCOS->getContext().getDwarfLocSeen())
96 return;
98 // Create a symbol at in the current section for use in the line entry.
99 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
100 // Set the value of the symbol to use for the MCDwarfLineEntry.
101 MCOS->emitLabel(LineSym);
103 // Get the current .loc info saved in the context.
104 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
106 // Create a (local) line entry with the symbol and the current .loc info.
107 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
109 // clear DwarfLocSeen saying the current .loc info is now used.
110 MCOS->getContext().clearDwarfLocSeen();
112 // Add the line entry to this section's entries.
113 MCOS->getContext()
114 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
115 .getMCLineSections()
116 .addLineEntry(LineEntry, Section);
120 // This helper routine returns an expression of End - Start - IntVal .
122 static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
123 const MCSymbol &Start,
124 const MCSymbol &End,
125 int IntVal) {
126 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
127 const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);
128 const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
129 const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);
130 const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);
131 const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);
132 return Res3;
136 // This helper routine returns an expression of Start + IntVal .
138 static inline const MCExpr *
139 makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {
140 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
141 const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
142 const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);
143 const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);
144 return Res;
147 void MCLineSection::addEndEntry(MCSymbol *EndLabel) {
148 auto *Sec = &EndLabel->getSection();
149 // The line table may be empty, which we should skip adding an end entry.
150 // There are two cases:
151 // (1) MCAsmStreamer - emitDwarfLocDirective emits a location directive in
152 // place instead of adding a line entry if the target has
153 // usesDwarfFileAndLocDirectives.
154 // (2) MCObjectStreamer - if a function has incomplete debug info where
155 // instructions don't have DILocations, the line entries are missing.
156 auto I = MCLineDivisions.find(Sec);
157 if (I != MCLineDivisions.end()) {
158 auto &Entries = I->second;
159 auto EndEntry = Entries.back();
160 EndEntry.setEndLabel(EndLabel);
161 Entries.push_back(EndEntry);
166 // This emits the Dwarf line table for the specified section from the entries
167 // in the LineSection.
169 void MCDwarfLineTable::emitOne(
170 MCStreamer *MCOS, MCSection *Section,
171 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
173 unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator;
174 MCSymbol *LastLabel;
175 auto init = [&]() {
176 FileNum = 1;
177 LastLine = 1;
178 Column = 0;
179 Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
180 Isa = 0;
181 Discriminator = 0;
182 LastLabel = nullptr;
184 init();
186 // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
187 bool EndEntryEmitted = false;
188 for (const MCDwarfLineEntry &LineEntry : LineEntries) {
189 MCSymbol *Label = LineEntry.getLabel();
190 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
191 if (LineEntry.IsEndEntry) {
192 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label,
193 asmInfo->getCodePointerSize());
194 init();
195 EndEntryEmitted = true;
196 continue;
199 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
201 if (FileNum != LineEntry.getFileNum()) {
202 FileNum = LineEntry.getFileNum();
203 MCOS->emitInt8(dwarf::DW_LNS_set_file);
204 MCOS->emitULEB128IntValue(FileNum);
206 if (Column != LineEntry.getColumn()) {
207 Column = LineEntry.getColumn();
208 MCOS->emitInt8(dwarf::DW_LNS_set_column);
209 MCOS->emitULEB128IntValue(Column);
211 if (Discriminator != LineEntry.getDiscriminator() &&
212 MCOS->getContext().getDwarfVersion() >= 4) {
213 Discriminator = LineEntry.getDiscriminator();
214 unsigned Size = getULEB128Size(Discriminator);
215 MCOS->emitInt8(dwarf::DW_LNS_extended_op);
216 MCOS->emitULEB128IntValue(Size + 1);
217 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
218 MCOS->emitULEB128IntValue(Discriminator);
220 if (Isa != LineEntry.getIsa()) {
221 Isa = LineEntry.getIsa();
222 MCOS->emitInt8(dwarf::DW_LNS_set_isa);
223 MCOS->emitULEB128IntValue(Isa);
225 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
226 Flags = LineEntry.getFlags();
227 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
229 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
230 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
231 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
232 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
233 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
234 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
236 // At this point we want to emit/create the sequence to encode the delta in
237 // line numbers and the increment of the address from the previous Label
238 // and the current Label.
239 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
240 asmInfo->getCodePointerSize());
242 Discriminator = 0;
243 LastLine = LineEntry.getLine();
244 LastLabel = Label;
247 // Generate DWARF line end entry.
248 // We do not need this for DwarfDebug that explicitly terminates the line
249 // table using ranges whenever CU or section changes. However, the MC path
250 // does not track ranges nor terminate the line table. In that case,
251 // conservatively use the section end symbol to end the line table.
252 if (!EndEntryEmitted)
253 MCOS->emitDwarfLineEndEntry(Section, LastLabel);
257 // This emits the Dwarf file and the line tables.
259 void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) {
260 MCContext &context = MCOS->getContext();
262 auto &LineTables = context.getMCDwarfLineTables();
264 // Bail out early so we don't switch to the debug_line section needlessly and
265 // in doing so create an unnecessary (if empty) section.
266 if (LineTables.empty())
267 return;
269 // In a v5 non-split line table, put the strings in a separate section.
270 std::optional<MCDwarfLineStr> LineStr;
271 if (context.getDwarfVersion() >= 5)
272 LineStr.emplace(context);
274 // Switch to the section where the table will be emitted into.
275 MCOS->switchSection(context.getObjectFileInfo()->getDwarfLineSection());
277 // Handle the rest of the Compile Units.
278 for (const auto &CUIDTablePair : LineTables) {
279 CUIDTablePair.second.emitCU(MCOS, Params, LineStr);
282 if (LineStr)
283 LineStr->emitSection(MCOS);
286 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
287 MCSection *Section) const {
288 if (!HasSplitLineTable)
289 return;
290 std::optional<MCDwarfLineStr> NoLineStr(std::nullopt);
291 MCOS.switchSection(Section);
292 MCOS.emitLabel(Header.Emit(&MCOS, Params, std::nullopt, NoLineStr).second);
295 std::pair<MCSymbol *, MCSymbol *>
296 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
297 std::optional<MCDwarfLineStr> &LineStr) const {
298 static const char StandardOpcodeLengths[] = {
299 0, // length of DW_LNS_copy
300 1, // length of DW_LNS_advance_pc
301 1, // length of DW_LNS_advance_line
302 1, // length of DW_LNS_set_file
303 1, // length of DW_LNS_set_column
304 0, // length of DW_LNS_negate_stmt
305 0, // length of DW_LNS_set_basic_block
306 0, // length of DW_LNS_const_add_pc
307 1, // length of DW_LNS_fixed_advance_pc
308 0, // length of DW_LNS_set_prologue_end
309 0, // length of DW_LNS_set_epilogue_begin
310 1 // DW_LNS_set_isa
312 assert(std::size(StandardOpcodeLengths) >=
313 (Params.DWARF2LineOpcodeBase - 1U));
314 return Emit(MCOS, Params,
315 ArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
316 LineStr);
319 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
320 MCContext &Context = OS.getContext();
321 assert(!isa<MCSymbolRefExpr>(Expr));
322 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
323 return Expr;
325 MCSymbol *ABS = Context.createTempSymbol();
326 OS.emitAssignment(ABS, Expr);
327 return MCSymbolRefExpr::create(ABS, Context);
330 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
331 const MCExpr *ABS = forceExpAbs(OS, Value);
332 OS.emitValue(ABS, Size);
335 void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
336 // Switch to the .debug_line_str section.
337 MCOS->switchSection(
338 MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
339 SmallString<0> Data = getFinalizedData();
340 MCOS->emitBinaryData(Data.str());
343 SmallString<0> MCDwarfLineStr::getFinalizedData() {
344 // Emit the strings without perturbing the offsets we used.
345 if (!LineStrings.isFinalized())
346 LineStrings.finalizeInOrder();
347 SmallString<0> Data;
348 Data.resize(LineStrings.getSize());
349 LineStrings.write((uint8_t *)Data.data());
350 return Data;
353 void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
354 int RefSize =
355 dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());
356 size_t Offset = LineStrings.add(Path);
357 if (UseRelocs) {
358 MCContext &Ctx = MCOS->getContext();
359 MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize);
360 } else
361 MCOS->emitIntValue(Offset, RefSize);
364 void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
365 // First the directory table.
366 for (auto &Dir : MCDwarfDirs) {
367 MCOS->emitBytes(Dir); // The DirectoryName, and...
368 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
370 MCOS->emitInt8(0); // Terminate the directory list.
372 // Second the file table.
373 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
374 assert(!MCDwarfFiles[i].Name.empty());
375 MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and...
376 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
377 MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number.
378 MCOS->emitInt8(0); // Last modification timestamp (always 0).
379 MCOS->emitInt8(0); // File size (always 0).
381 MCOS->emitInt8(0); // Terminate the file list.
384 static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
385 bool EmitMD5, bool HasSource,
386 std::optional<MCDwarfLineStr> &LineStr) {
387 assert(!DwarfFile.Name.empty());
388 if (LineStr)
389 LineStr->emitRef(MCOS, DwarfFile.Name);
390 else {
391 MCOS->emitBytes(DwarfFile.Name); // FileName and...
392 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
394 MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number.
395 if (EmitMD5) {
396 const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
397 MCOS->emitBinaryData(
398 StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size()));
400 if (HasSource) {
401 if (LineStr)
402 LineStr->emitRef(MCOS, DwarfFile.Source.value_or(StringRef()));
403 else {
404 MCOS->emitBytes(DwarfFile.Source.value_or(StringRef())); // Source and...
405 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
410 void MCDwarfLineTableHeader::emitV5FileDirTables(
411 MCStreamer *MCOS, std::optional<MCDwarfLineStr> &LineStr) const {
412 // The directory format, which is just a list of the directory paths. In a
413 // non-split object, these are references to .debug_line_str; in a split
414 // object, they are inline strings.
415 MCOS->emitInt8(1);
416 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
417 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
418 : dwarf::DW_FORM_string);
419 MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);
420 // Try not to emit an empty compilation directory.
421 SmallString<256> Dir;
422 StringRef CompDir = MCOS->getContext().getCompilationDir();
423 if (!CompilationDir.empty()) {
424 Dir = CompilationDir;
425 MCOS->getContext().remapDebugPath(Dir);
426 CompDir = Dir.str();
427 if (LineStr)
428 CompDir = LineStr->getSaver().save(CompDir);
430 if (LineStr) {
431 // Record path strings, emit references here.
432 LineStr->emitRef(MCOS, CompDir);
433 for (const auto &Dir : MCDwarfDirs)
434 LineStr->emitRef(MCOS, Dir);
435 } else {
436 // The list of directory paths. Compilation directory comes first.
437 MCOS->emitBytes(CompDir);
438 MCOS->emitBytes(StringRef("\0", 1));
439 for (const auto &Dir : MCDwarfDirs) {
440 MCOS->emitBytes(Dir); // The DirectoryName, and...
441 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
445 // The file format, which is the inline null-terminated filename and a
446 // directory index. We don't track file size/timestamp so don't emit them
447 // in the v5 table. Emit MD5 checksums and source if we have them.
448 uint64_t Entries = 2;
449 if (HasAllMD5)
450 Entries += 1;
451 if (HasSource)
452 Entries += 1;
453 MCOS->emitInt8(Entries);
454 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
455 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
456 : dwarf::DW_FORM_string);
457 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
458 MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);
459 if (HasAllMD5) {
460 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);
461 MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);
463 if (HasSource) {
464 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);
465 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
466 : dwarf::DW_FORM_string);
468 // Then the counted list of files. The root file is file #0, then emit the
469 // files as provide by .file directives.
470 // MCDwarfFiles has an unused element [0] so use size() not size()+1.
471 // But sometimes MCDwarfFiles is empty, in which case we still emit one file.
472 MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
473 // To accommodate assembler source written for DWARF v4 but trying to emit
474 // v5: If we didn't see a root file explicitly, replicate file #1.
475 assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
476 "No root file and no .file directives");
477 emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
478 HasAllMD5, HasSource, LineStr);
479 for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
480 emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr);
483 std::pair<MCSymbol *, MCSymbol *>
484 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
485 ArrayRef<char> StandardOpcodeLengths,
486 std::optional<MCDwarfLineStr> &LineStr) const {
487 MCContext &context = MCOS->getContext();
489 // Create a symbol at the beginning of the line table.
490 MCSymbol *LineStartSym = Label;
491 if (!LineStartSym)
492 LineStartSym = context.createTempSymbol();
494 // Set the value of the symbol, as we are at the start of the line table.
495 MCOS->emitDwarfLineStartLabel(LineStartSym);
497 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
499 MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length");
501 // Next 2 bytes is the Version.
502 unsigned LineTableVersion = context.getDwarfVersion();
503 MCOS->emitInt16(LineTableVersion);
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.
511 // Create symbols for the start/end of the prologue.
512 MCSymbol *ProStartSym = context.createTempSymbol("prologue_start");
513 MCSymbol *ProEndSym = context.createTempSymbol("prologue_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.
517 MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize);
519 MCOS->emitLabel(ProStartSym);
521 // Parameters of the state machine, are next.
522 MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
523 // maximum_operations_per_instruction
524 // For non-VLIW architectures this field is always 1.
525 // FIXME: VLIW architectures need to update this field accordingly.
526 if (LineTableVersion >= 4)
527 MCOS->emitInt8(1);
528 MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
529 MCOS->emitInt8(Params.DWARF2LineBase);
530 MCOS->emitInt8(Params.DWARF2LineRange);
531 MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
533 // Standard opcode lengths
534 for (char Length : StandardOpcodeLengths)
535 MCOS->emitInt8(Length);
537 // Put out the directory and file tables. The formats vary depending on
538 // the version.
539 if (LineTableVersion >= 5)
540 emitV5FileDirTables(MCOS, LineStr);
541 else
542 emitV2FileDirTables(MCOS);
544 // This is the end of the prologue, so set the value of the symbol at the
545 // end of the prologue (that was used in a previous expression).
546 MCOS->emitLabel(ProEndSym);
548 return std::make_pair(LineStartSym, LineEndSym);
551 void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
552 std::optional<MCDwarfLineStr> &LineStr) const {
553 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
555 // Put out the line tables.
556 for (const auto &LineSec : MCLineSections.getMCLineEntries())
557 emitOne(MCOS, LineSec.first, LineSec.second);
559 // This is the end of the section, so set the value of the symbol at the end
560 // of this section (that was used in a previous expression).
561 MCOS->emitLabel(LineEndSym);
564 Expected<unsigned>
565 MCDwarfLineTable::tryGetFile(StringRef &Directory, StringRef &FileName,
566 std::optional<MD5::MD5Result> Checksum,
567 std::optional<StringRef> Source,
568 uint16_t DwarfVersion, unsigned FileNumber) {
569 return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
570 FileNumber);
573 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
574 StringRef &FileName,
575 std::optional<MD5::MD5Result> Checksum) {
576 if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)
577 return false;
578 return RootFile.Checksum == Checksum;
581 Expected<unsigned>
582 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, StringRef &FileName,
583 std::optional<MD5::MD5Result> Checksum,
584 std::optional<StringRef> Source,
585 uint16_t DwarfVersion, unsigned FileNumber) {
586 if (Directory == CompilationDir)
587 Directory = "";
588 if (FileName.empty()) {
589 FileName = "<stdin>";
590 Directory = "";
592 assert(!FileName.empty());
593 // Keep track of whether any or all files have an MD5 checksum.
594 // If any files have embedded source, they all must.
595 if (MCDwarfFiles.empty()) {
596 trackMD5Usage(Checksum.has_value());
597 HasSource = (Source != std::nullopt);
599 if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum))
600 return 0;
601 if (FileNumber == 0) {
602 // File numbers start with 1 and/or after any file numbers
603 // allocated by inline-assembler .file directives.
604 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
605 SmallString<256> Buffer;
606 auto IterBool = SourceIdMap.insert(
607 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
608 FileNumber));
609 if (!IterBool.second)
610 return IterBool.first->second;
612 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
613 if (FileNumber >= MCDwarfFiles.size())
614 MCDwarfFiles.resize(FileNumber + 1);
616 // Get the new MCDwarfFile slot for this FileNumber.
617 MCDwarfFile &File = MCDwarfFiles[FileNumber];
619 // It is an error to see the same number more than once.
620 if (!File.Name.empty())
621 return make_error<StringError>("file number already allocated",
622 inconvertibleErrorCode());
624 // If any files have embedded source, they all must.
625 if (HasSource != (Source != std::nullopt))
626 return make_error<StringError>("inconsistent use of embedded source",
627 inconvertibleErrorCode());
629 if (Directory.empty()) {
630 // Separate the directory part from the basename of the FileName.
631 StringRef tFileName = sys::path::filename(FileName);
632 if (!tFileName.empty()) {
633 Directory = sys::path::parent_path(FileName);
634 if (!Directory.empty())
635 FileName = tFileName;
639 // Find or make an entry in the MCDwarfDirs vector for this Directory.
640 // Capture directory name.
641 unsigned DirIndex;
642 if (Directory.empty()) {
643 // For FileNames with no directories a DirIndex of 0 is used.
644 DirIndex = 0;
645 } else {
646 DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
647 if (DirIndex >= MCDwarfDirs.size())
648 MCDwarfDirs.push_back(std::string(Directory));
649 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
650 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
651 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
652 // are stored at MCDwarfFiles[FileNumber].Name .
653 DirIndex++;
656 File.Name = std::string(FileName);
657 File.DirIndex = DirIndex;
658 File.Checksum = Checksum;
659 trackMD5Usage(Checksum.has_value());
660 File.Source = Source;
661 if (Source)
662 HasSource = true;
664 // return the allocated FileNumber.
665 return FileNumber;
668 /// Utility function to emit the encoding to a streamer.
669 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
670 int64_t LineDelta, uint64_t AddrDelta) {
671 MCContext &Context = MCOS->getContext();
672 SmallString<256> Tmp;
673 MCDwarfLineAddr::encode(Context, Params, LineDelta, AddrDelta, Tmp);
674 MCOS->emitBytes(Tmp);
677 /// Given a special op, return the address skip amount (in units of
678 /// DWARF2_LINE_MIN_INSN_LENGTH).
679 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
680 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
683 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
684 void MCDwarfLineAddr::encode(MCContext &Context, MCDwarfLineTableParams Params,
685 int64_t LineDelta, uint64_t AddrDelta,
686 SmallVectorImpl<char> &Out) {
687 uint8_t Buf[16];
688 uint64_t Temp, Opcode;
689 bool NeedCopy = false;
691 // The maximum address skip amount that can be encoded with a special op.
692 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
694 // Scale the address delta by the minimum instruction length.
695 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
697 // A LineDelta of INT64_MAX is a signal that this is actually a
698 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
699 // end_sequence to emit the matrix entry.
700 if (LineDelta == INT64_MAX) {
701 if (AddrDelta == MaxSpecialAddrDelta)
702 Out.push_back(dwarf::DW_LNS_const_add_pc);
703 else if (AddrDelta) {
704 Out.push_back(dwarf::DW_LNS_advance_pc);
705 Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));
707 Out.push_back(dwarf::DW_LNS_extended_op);
708 Out.push_back(1);
709 Out.push_back(dwarf::DW_LNE_end_sequence);
710 return;
713 // Bias the line delta by the base.
714 Temp = LineDelta - Params.DWARF2LineBase;
716 // If the line increment is out of range of a special opcode, we must encode
717 // it with DW_LNS_advance_line.
718 if (Temp >= Params.DWARF2LineRange ||
719 Temp + Params.DWARF2LineOpcodeBase > 255) {
720 Out.push_back(dwarf::DW_LNS_advance_line);
721 Out.append(Buf, Buf + encodeSLEB128(LineDelta, Buf));
723 LineDelta = 0;
724 Temp = 0 - Params.DWARF2LineBase;
725 NeedCopy = true;
728 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
729 if (LineDelta == 0 && AddrDelta == 0) {
730 Out.push_back(dwarf::DW_LNS_copy);
731 return;
734 // Bias the opcode by the special opcode base.
735 Temp += Params.DWARF2LineOpcodeBase;
737 // Avoid overflow when addr_delta is large.
738 if (AddrDelta < 256 + MaxSpecialAddrDelta) {
739 // Try using a special opcode.
740 Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
741 if (Opcode <= 255) {
742 Out.push_back(Opcode);
743 return;
746 // Try using DW_LNS_const_add_pc followed by special op.
747 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
748 if (Opcode <= 255) {
749 Out.push_back(dwarf::DW_LNS_const_add_pc);
750 Out.push_back(Opcode);
751 return;
755 // Otherwise use DW_LNS_advance_pc.
756 Out.push_back(dwarf::DW_LNS_advance_pc);
757 Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));
759 if (NeedCopy)
760 Out.push_back(dwarf::DW_LNS_copy);
761 else {
762 assert(Temp <= 255 && "Buggy special opcode encoding.");
763 Out.push_back(Temp);
767 // Utility function to write a tuple for .debug_abbrev.
768 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
769 MCOS->emitULEB128IntValue(Name);
770 MCOS->emitULEB128IntValue(Form);
773 // When generating dwarf for assembly source files this emits
774 // the data for .debug_abbrev section which contains three DIEs.
775 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
776 MCContext &context = MCOS->getContext();
777 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
779 // DW_TAG_compile_unit DIE abbrev (1).
780 MCOS->emitULEB128IntValue(1);
781 MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
782 MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
783 dwarf::Form SecOffsetForm =
784 context.getDwarfVersion() >= 4
785 ? dwarf::DW_FORM_sec_offset
786 : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
787 : dwarf::DW_FORM_data4);
788 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
789 if (context.getGenDwarfSectionSyms().size() > 1 &&
790 context.getDwarfVersion() >= 3) {
791 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
792 } else {
793 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
794 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
796 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
797 if (!context.getCompilationDir().empty())
798 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
799 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
800 if (!DwarfDebugFlags.empty())
801 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
802 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
803 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
804 EmitAbbrev(MCOS, 0, 0);
806 // DW_TAG_label DIE abbrev (2).
807 MCOS->emitULEB128IntValue(2);
808 MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
809 MCOS->emitInt8(dwarf::DW_CHILDREN_no);
810 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
811 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
812 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
813 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
814 EmitAbbrev(MCOS, 0, 0);
816 // Terminate the abbreviations for this compilation unit.
817 MCOS->emitInt8(0);
820 // When generating dwarf for assembly source files this emits the data for
821 // .debug_aranges section. This section contains a header and a table of pairs
822 // of PointerSize'ed values for the address and size of section(s) with line
823 // table entries.
824 static void EmitGenDwarfAranges(MCStreamer *MCOS,
825 const MCSymbol *InfoSectionSymbol) {
826 MCContext &context = MCOS->getContext();
828 auto &Sections = context.getGenDwarfSectionSyms();
830 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
832 unsigned UnitLengthBytes =
833 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
834 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
836 // This will be the length of the .debug_aranges section, first account for
837 // the size of each item in the header (see below where we emit these items).
838 int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
840 // Figure the padding after the header before the table of address and size
841 // pairs who's values are PointerSize'ed.
842 const MCAsmInfo *asmInfo = context.getAsmInfo();
843 int AddrSize = asmInfo->getCodePointerSize();
844 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
845 if (Pad == 2 * AddrSize)
846 Pad = 0;
847 Length += Pad;
849 // Add the size of the pair of PointerSize'ed values for the address and size
850 // of each section we have in the table.
851 Length += 2 * AddrSize * Sections.size();
852 // And the pair of terminating zeros.
853 Length += 2 * AddrSize;
855 // Emit the header for this section.
856 if (context.getDwarfFormat() == dwarf::DWARF64)
857 // The DWARF64 mark.
858 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
859 // The 4 (8 for DWARF64) byte length not including the length of the unit
860 // length field itself.
861 MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
862 // The 2 byte version, which is 2.
863 MCOS->emitInt16(2);
864 // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
865 // from the start of the .debug_info.
866 if (InfoSectionSymbol)
867 MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
868 asmInfo->needsDwarfSectionOffsetDirective());
869 else
870 MCOS->emitIntValue(0, OffsetSize);
871 // The 1 byte size of an address.
872 MCOS->emitInt8(AddrSize);
873 // The 1 byte size of a segment descriptor, we use a value of zero.
874 MCOS->emitInt8(0);
875 // Align the header with the padding if needed, before we put out the table.
876 for(int i = 0; i < Pad; i++)
877 MCOS->emitInt8(0);
879 // Now emit the table of pairs of PointerSize'ed values for the section
880 // addresses and sizes.
881 for (MCSection *Sec : Sections) {
882 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
883 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
884 assert(StartSymbol && "StartSymbol must not be NULL");
885 assert(EndSymbol && "EndSymbol must not be NULL");
887 const MCExpr *Addr = MCSymbolRefExpr::create(
888 StartSymbol, MCSymbolRefExpr::VK_None, context);
889 const MCExpr *Size =
890 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
891 MCOS->emitValue(Addr, AddrSize);
892 emitAbsValue(*MCOS, Size, AddrSize);
895 // And finally the pair of terminating zeros.
896 MCOS->emitIntValue(0, AddrSize);
897 MCOS->emitIntValue(0, AddrSize);
900 // When generating dwarf for assembly source files this emits the data for
901 // .debug_info section which contains three parts. The header, the compile_unit
902 // DIE and a list of label DIEs.
903 static void EmitGenDwarfInfo(MCStreamer *MCOS,
904 const MCSymbol *AbbrevSectionSymbol,
905 const MCSymbol *LineSectionSymbol,
906 const MCSymbol *RangesSymbol) {
907 MCContext &context = MCOS->getContext();
909 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
911 // Create a symbol at the start and end of this section used in here for the
912 // expression to calculate the length in the header.
913 MCSymbol *InfoStart = context.createTempSymbol();
914 MCOS->emitLabel(InfoStart);
915 MCSymbol *InfoEnd = context.createTempSymbol();
917 // First part: the header.
919 unsigned UnitLengthBytes =
920 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
921 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
923 if (context.getDwarfFormat() == dwarf::DWARF64)
924 // Emit DWARF64 mark.
925 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
927 // The 4 (8 for DWARF64) byte total length of the information for this
928 // compilation unit, not including the unit length field itself.
929 const MCExpr *Length =
930 makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
931 emitAbsValue(*MCOS, Length, OffsetSize);
933 // The 2 byte DWARF version.
934 MCOS->emitInt16(context.getDwarfVersion());
936 // The DWARF v5 header has unit type, address size, abbrev offset.
937 // Earlier versions have abbrev offset, address size.
938 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
939 int AddrSize = AsmInfo.getCodePointerSize();
940 if (context.getDwarfVersion() >= 5) {
941 MCOS->emitInt8(dwarf::DW_UT_compile);
942 MCOS->emitInt8(AddrSize);
944 // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
945 // the .debug_abbrev.
946 if (AbbrevSectionSymbol)
947 MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
948 AsmInfo.needsDwarfSectionOffsetDirective());
949 else
950 // Since the abbrevs are at the start of the section, the offset is zero.
951 MCOS->emitIntValue(0, OffsetSize);
952 if (context.getDwarfVersion() <= 4)
953 MCOS->emitInt8(AddrSize);
955 // Second part: the compile_unit DIE.
957 // The DW_TAG_compile_unit DIE abbrev (1).
958 MCOS->emitULEB128IntValue(1);
960 // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
961 // .debug_line section.
962 if (LineSectionSymbol)
963 MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
964 AsmInfo.needsDwarfSectionOffsetDirective());
965 else
966 // The line table is at the start of the section, so the offset is zero.
967 MCOS->emitIntValue(0, OffsetSize);
969 if (RangesSymbol) {
970 // There are multiple sections containing code, so we must use
971 // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
972 // start of the .debug_ranges/.debug_rnglists.
973 MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
974 } else {
975 // If we only have one non-empty code section, we can use the simpler
976 // AT_low_pc and AT_high_pc attributes.
978 // Find the first (and only) non-empty text section
979 auto &Sections = context.getGenDwarfSectionSyms();
980 const auto TextSection = Sections.begin();
981 assert(TextSection != Sections.end() && "No text section found");
983 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
984 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
985 assert(StartSymbol && "StartSymbol must not be NULL");
986 assert(EndSymbol && "EndSymbol must not be NULL");
988 // AT_low_pc, the first address of the default .text section.
989 const MCExpr *Start = MCSymbolRefExpr::create(
990 StartSymbol, MCSymbolRefExpr::VK_None, context);
991 MCOS->emitValue(Start, AddrSize);
993 // AT_high_pc, the last address of the default .text section.
994 const MCExpr *End = MCSymbolRefExpr::create(
995 EndSymbol, MCSymbolRefExpr::VK_None, context);
996 MCOS->emitValue(End, AddrSize);
999 // AT_name, the name of the source file. Reconstruct from the first directory
1000 // and file table entries.
1001 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
1002 if (MCDwarfDirs.size() > 0) {
1003 MCOS->emitBytes(MCDwarfDirs[0]);
1004 MCOS->emitBytes(sys::path::get_separator());
1006 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
1007 // MCDwarfFiles might be empty if we have an empty source file.
1008 // If it's not empty, [0] is unused and [1] is the first actual file.
1009 assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
1010 const MCDwarfFile &RootFile =
1011 MCDwarfFiles.empty()
1012 ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
1013 : MCDwarfFiles[1];
1014 MCOS->emitBytes(RootFile.Name);
1015 MCOS->emitInt8(0); // NULL byte to terminate the string.
1017 // AT_comp_dir, the working directory the assembly was done in.
1018 if (!context.getCompilationDir().empty()) {
1019 MCOS->emitBytes(context.getCompilationDir());
1020 MCOS->emitInt8(0); // NULL byte to terminate the string.
1023 // AT_APPLE_flags, the command line arguments of the assembler tool.
1024 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
1025 if (!DwarfDebugFlags.empty()){
1026 MCOS->emitBytes(DwarfDebugFlags);
1027 MCOS->emitInt8(0); // NULL byte to terminate the string.
1030 // AT_producer, the version of the assembler tool.
1031 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
1032 if (!DwarfDebugProducer.empty())
1033 MCOS->emitBytes(DwarfDebugProducer);
1034 else
1035 MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
1036 MCOS->emitInt8(0); // NULL byte to terminate the string.
1038 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
1039 // draft has no standard code for assembler.
1040 MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
1042 // Third part: the list of label DIEs.
1044 // Loop on saved info for dwarf labels and create the DIEs for them.
1045 const std::vector<MCGenDwarfLabelEntry> &Entries =
1046 MCOS->getContext().getMCGenDwarfLabelEntries();
1047 for (const auto &Entry : Entries) {
1048 // The DW_TAG_label DIE abbrev (2).
1049 MCOS->emitULEB128IntValue(2);
1051 // AT_name, of the label without any leading underbar.
1052 MCOS->emitBytes(Entry.getName());
1053 MCOS->emitInt8(0); // NULL byte to terminate the string.
1055 // AT_decl_file, index into the file table.
1056 MCOS->emitInt32(Entry.getFileNumber());
1058 // AT_decl_line, source line number.
1059 MCOS->emitInt32(Entry.getLineNumber());
1061 // AT_low_pc, start address of the label.
1062 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
1063 MCSymbolRefExpr::VK_None, context);
1064 MCOS->emitValue(AT_low_pc, AddrSize);
1067 // Add the NULL DIE terminating the Compile Unit DIE's.
1068 MCOS->emitInt8(0);
1070 // Now set the value of the symbol at the end of the info section.
1071 MCOS->emitLabel(InfoEnd);
1074 // When generating dwarf for assembly source files this emits the data for
1075 // .debug_ranges section. We only emit one range list, which spans all of the
1076 // executable sections of this file.
1077 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
1078 MCContext &context = MCOS->getContext();
1079 auto &Sections = context.getGenDwarfSectionSyms();
1081 const MCAsmInfo *AsmInfo = context.getAsmInfo();
1082 int AddrSize = AsmInfo->getCodePointerSize();
1083 MCSymbol *RangesSymbol;
1085 if (MCOS->getContext().getDwarfVersion() >= 5) {
1086 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
1087 MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
1088 MCOS->AddComment("Offset entry count");
1089 MCOS->emitInt32(0);
1090 RangesSymbol = context.createTempSymbol("debug_rnglist0_start");
1091 MCOS->emitLabel(RangesSymbol);
1092 for (MCSection *Sec : Sections) {
1093 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1094 const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1095 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1096 StartSymbol, MCSymbolRefExpr::VK_None, context);
1097 const MCExpr *SectionSize =
1098 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1099 MCOS->emitInt8(dwarf::DW_RLE_start_length);
1100 MCOS->emitValue(SectionStartAddr, AddrSize);
1101 MCOS->emitULEB128Value(SectionSize);
1103 MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
1104 MCOS->emitLabel(EndSymbol);
1105 } else {
1106 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRangesSection());
1107 RangesSymbol = context.createTempSymbol("debug_ranges_start");
1108 MCOS->emitLabel(RangesSymbol);
1109 for (MCSection *Sec : Sections) {
1110 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1111 const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1113 // Emit a base address selection entry for the section start.
1114 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1115 StartSymbol, MCSymbolRefExpr::VK_None, context);
1116 MCOS->emitFill(AddrSize, 0xFF);
1117 MCOS->emitValue(SectionStartAddr, AddrSize);
1119 // Emit a range list entry spanning this section.
1120 const MCExpr *SectionSize =
1121 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1122 MCOS->emitIntValue(0, AddrSize);
1123 emitAbsValue(*MCOS, SectionSize, AddrSize);
1126 // Emit end of list entry
1127 MCOS->emitIntValue(0, AddrSize);
1128 MCOS->emitIntValue(0, AddrSize);
1131 return RangesSymbol;
1135 // When generating dwarf for assembly source files this emits the Dwarf
1136 // sections.
1138 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
1139 MCContext &context = MCOS->getContext();
1141 // Create the dwarf sections in this order (.debug_line already created).
1142 const MCAsmInfo *AsmInfo = context.getAsmInfo();
1143 bool CreateDwarfSectionSymbols =
1144 AsmInfo->doesDwarfUseRelocationsAcrossSections();
1145 MCSymbol *LineSectionSymbol = nullptr;
1146 if (CreateDwarfSectionSymbols)
1147 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
1148 MCSymbol *AbbrevSectionSymbol = nullptr;
1149 MCSymbol *InfoSectionSymbol = nullptr;
1150 MCSymbol *RangesSymbol = nullptr;
1152 // Create end symbols for each section, and remove empty sections
1153 MCOS->getContext().finalizeDwarfSections(*MCOS);
1155 // If there are no sections to generate debug info for, we don't need
1156 // to do anything
1157 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
1158 return;
1160 // We only use the .debug_ranges section if we have multiple code sections,
1161 // and we are emitting a DWARF version which supports it.
1162 const bool UseRangesSection =
1163 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
1164 MCOS->getContext().getDwarfVersion() >= 3;
1165 CreateDwarfSectionSymbols |= UseRangesSection;
1167 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());
1168 if (CreateDwarfSectionSymbols) {
1169 InfoSectionSymbol = context.createTempSymbol();
1170 MCOS->emitLabel(InfoSectionSymbol);
1172 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
1173 if (CreateDwarfSectionSymbols) {
1174 AbbrevSectionSymbol = context.createTempSymbol();
1175 MCOS->emitLabel(AbbrevSectionSymbol);
1178 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());
1180 // Output the data for .debug_aranges section.
1181 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
1183 if (UseRangesSection) {
1184 RangesSymbol = emitGenDwarfRanges(MCOS);
1185 assert(RangesSymbol);
1188 // Output the data for .debug_abbrev section.
1189 EmitGenDwarfAbbrev(MCOS);
1191 // Output the data for .debug_info section.
1192 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
1196 // When generating dwarf for assembly source files this is called when symbol
1197 // for a label is created. If this symbol is not a temporary and is in the
1198 // section that dwarf is being generated for, save the needed info to create
1199 // a dwarf label.
1201 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
1202 SourceMgr &SrcMgr, SMLoc &Loc) {
1203 // We won't create dwarf labels for temporary symbols.
1204 if (Symbol->isTemporary())
1205 return;
1206 MCContext &context = MCOS->getContext();
1207 // We won't create dwarf labels for symbols in sections that we are not
1208 // generating debug info for.
1209 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
1210 return;
1212 // The dwarf label's name does not have the symbol name's leading
1213 // underbar if any.
1214 StringRef Name = Symbol->getName();
1215 if (Name.startswith("_"))
1216 Name = Name.substr(1, Name.size()-1);
1218 // Get the dwarf file number to be used for the dwarf label.
1219 unsigned FileNumber = context.getGenDwarfFileNumber();
1221 // Finding the line number is the expensive part which is why we just don't
1222 // pass it in as for some symbols we won't create a dwarf label.
1223 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
1224 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
1226 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
1227 // values so that they don't have things like an ARM thumb bit from the
1228 // original symbol. So when used they won't get a low bit set after
1229 // relocation.
1230 MCSymbol *Label = context.createTempSymbol();
1231 MCOS->emitLabel(Label);
1233 // Create and entry for the info and add it to the other entries.
1234 MCOS->getContext().addMCGenDwarfLabelEntry(
1235 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
1238 static int getDataAlignmentFactor(MCStreamer &streamer) {
1239 MCContext &context = streamer.getContext();
1240 const MCAsmInfo *asmInfo = context.getAsmInfo();
1241 int size = asmInfo->getCalleeSaveStackSlotSize();
1242 if (asmInfo->isStackGrowthDirectionUp())
1243 return size;
1244 else
1245 return -size;
1248 static unsigned getSizeForEncoding(MCStreamer &streamer,
1249 unsigned symbolEncoding) {
1250 MCContext &context = streamer.getContext();
1251 unsigned format = symbolEncoding & 0x0f;
1252 switch (format) {
1253 default: llvm_unreachable("Unknown Encoding");
1254 case dwarf::DW_EH_PE_absptr:
1255 case dwarf::DW_EH_PE_signed:
1256 return context.getAsmInfo()->getCodePointerSize();
1257 case dwarf::DW_EH_PE_udata2:
1258 case dwarf::DW_EH_PE_sdata2:
1259 return 2;
1260 case dwarf::DW_EH_PE_udata4:
1261 case dwarf::DW_EH_PE_sdata4:
1262 return 4;
1263 case dwarf::DW_EH_PE_udata8:
1264 case dwarf::DW_EH_PE_sdata8:
1265 return 8;
1269 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
1270 unsigned symbolEncoding, bool isEH) {
1271 MCContext &context = streamer.getContext();
1272 const MCAsmInfo *asmInfo = context.getAsmInfo();
1273 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
1274 symbolEncoding,
1275 streamer);
1276 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1277 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
1278 emitAbsValue(streamer, v, size);
1279 else
1280 streamer.emitValue(v, size);
1283 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1284 unsigned symbolEncoding) {
1285 MCContext &context = streamer.getContext();
1286 const MCAsmInfo *asmInfo = context.getAsmInfo();
1287 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1288 symbolEncoding,
1289 streamer);
1290 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1291 streamer.emitValue(v, size);
1294 namespace {
1296 class FrameEmitterImpl {
1297 int CFAOffset = 0;
1298 int InitialCFAOffset = 0;
1299 bool IsEH;
1300 MCObjectStreamer &Streamer;
1302 public:
1303 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
1304 : IsEH(IsEH), Streamer(Streamer) {}
1306 /// Emit the unwind information in a compact way.
1307 void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
1309 const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
1310 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
1311 bool LastInSection, const MCSymbol &SectionStart);
1312 void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1313 MCSymbol *BaseLabel);
1314 void emitCFIInstruction(const MCCFIInstruction &Instr);
1317 } // end anonymous namespace
1319 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1320 Streamer.emitInt8(Encoding);
1323 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
1324 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1325 auto *MRI = Streamer.getContext().getRegisterInfo();
1327 switch (Instr.getOperation()) {
1328 case MCCFIInstruction::OpRegister: {
1329 unsigned Reg1 = Instr.getRegister();
1330 unsigned Reg2 = Instr.getRegister2();
1331 if (!IsEH) {
1332 Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
1333 Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
1335 Streamer.emitInt8(dwarf::DW_CFA_register);
1336 Streamer.emitULEB128IntValue(Reg1);
1337 Streamer.emitULEB128IntValue(Reg2);
1338 return;
1340 case MCCFIInstruction::OpWindowSave:
1341 Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
1342 return;
1344 case MCCFIInstruction::OpNegateRAState:
1345 Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
1346 return;
1348 case MCCFIInstruction::OpUndefined: {
1349 unsigned Reg = Instr.getRegister();
1350 Streamer.emitInt8(dwarf::DW_CFA_undefined);
1351 Streamer.emitULEB128IntValue(Reg);
1352 return;
1354 case MCCFIInstruction::OpAdjustCfaOffset:
1355 case MCCFIInstruction::OpDefCfaOffset: {
1356 const bool IsRelative =
1357 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1359 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
1361 if (IsRelative)
1362 CFAOffset += Instr.getOffset();
1363 else
1364 CFAOffset = Instr.getOffset();
1366 Streamer.emitULEB128IntValue(CFAOffset);
1368 return;
1370 case MCCFIInstruction::OpDefCfa: {
1371 unsigned Reg = Instr.getRegister();
1372 if (!IsEH)
1373 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1374 Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
1375 Streamer.emitULEB128IntValue(Reg);
1376 CFAOffset = Instr.getOffset();
1377 Streamer.emitULEB128IntValue(CFAOffset);
1379 return;
1381 case MCCFIInstruction::OpDefCfaRegister: {
1382 unsigned Reg = Instr.getRegister();
1383 if (!IsEH)
1384 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1385 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
1386 Streamer.emitULEB128IntValue(Reg);
1388 return;
1390 // TODO: Implement `_sf` variants if/when they need to be emitted.
1391 case MCCFIInstruction::OpLLVMDefAspaceCfa: {
1392 unsigned Reg = Instr.getRegister();
1393 if (!IsEH)
1394 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1395 Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1);
1396 Streamer.emitULEB128IntValue(Reg);
1397 CFAOffset = Instr.getOffset();
1398 Streamer.emitULEB128IntValue(CFAOffset);
1399 Streamer.emitULEB128IntValue(Instr.getAddressSpace());
1401 return;
1403 case MCCFIInstruction::OpOffset:
1404 case MCCFIInstruction::OpRelOffset: {
1405 const bool IsRelative =
1406 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1408 unsigned Reg = Instr.getRegister();
1409 if (!IsEH)
1410 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1412 int Offset = Instr.getOffset();
1413 if (IsRelative)
1414 Offset -= CFAOffset;
1415 Offset = Offset / dataAlignmentFactor;
1417 if (Offset < 0) {
1418 Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
1419 Streamer.emitULEB128IntValue(Reg);
1420 Streamer.emitSLEB128IntValue(Offset);
1421 } else if (Reg < 64) {
1422 Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
1423 Streamer.emitULEB128IntValue(Offset);
1424 } else {
1425 Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
1426 Streamer.emitULEB128IntValue(Reg);
1427 Streamer.emitULEB128IntValue(Offset);
1429 return;
1431 case MCCFIInstruction::OpRememberState:
1432 Streamer.emitInt8(dwarf::DW_CFA_remember_state);
1433 return;
1434 case MCCFIInstruction::OpRestoreState:
1435 Streamer.emitInt8(dwarf::DW_CFA_restore_state);
1436 return;
1437 case MCCFIInstruction::OpSameValue: {
1438 unsigned Reg = Instr.getRegister();
1439 Streamer.emitInt8(dwarf::DW_CFA_same_value);
1440 Streamer.emitULEB128IntValue(Reg);
1441 return;
1443 case MCCFIInstruction::OpRestore: {
1444 unsigned Reg = Instr.getRegister();
1445 if (!IsEH)
1446 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1447 if (Reg < 64) {
1448 Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
1449 } else {
1450 Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
1451 Streamer.emitULEB128IntValue(Reg);
1453 return;
1455 case MCCFIInstruction::OpGnuArgsSize:
1456 Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
1457 Streamer.emitULEB128IntValue(Instr.getOffset());
1458 return;
1460 case MCCFIInstruction::OpEscape:
1461 Streamer.emitBytes(Instr.getValues());
1462 return;
1464 llvm_unreachable("Unhandled case in switch");
1467 /// Emit frame instructions to describe the layout of the frame.
1468 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1469 MCSymbol *BaseLabel) {
1470 for (const MCCFIInstruction &Instr : Instrs) {
1471 MCSymbol *Label = Instr.getLabel();
1472 // Throw out move if the label is invalid.
1473 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1475 // Advance row if new location.
1476 if (BaseLabel && Label) {
1477 MCSymbol *ThisSym = Label;
1478 if (ThisSym != BaseLabel) {
1479 Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1480 BaseLabel = ThisSym;
1484 emitCFIInstruction(Instr);
1488 /// Emit the unwind information in a compact way.
1489 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
1490 MCContext &Context = Streamer.getContext();
1491 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1493 // range-start range-length compact-unwind-enc personality-func lsda
1494 // _foo LfooEnd-_foo 0x00000023 0 0
1495 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1497 // .section __LD,__compact_unwind,regular,debug
1499 // # compact unwind for _foo
1500 // .quad _foo
1501 // .set L1,LfooEnd-_foo
1502 // .long L1
1503 // .long 0x01010001
1504 // .quad 0
1505 // .quad 0
1507 // # compact unwind for _bar
1508 // .quad _bar
1509 // .set L2,LbarEnd-_bar
1510 // .long L2
1511 // .long 0x01020011
1512 // .quad __gxx_personality
1513 // .quad except_tab1
1515 uint32_t Encoding = Frame.CompactUnwindEncoding;
1516 if (!Encoding) return;
1517 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1519 // The encoding needs to know we have an LSDA.
1520 if (!DwarfEHFrameOnly && Frame.Lsda)
1521 Encoding |= 0x40000000;
1523 // Range Start
1524 unsigned FDEEncoding = MOFI->getFDEEncoding();
1525 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1526 Streamer.emitSymbolValue(Frame.Begin, Size);
1528 // Range Length
1529 const MCExpr *Range =
1530 makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
1531 emitAbsValue(Streamer, Range, 4);
1533 // Compact Encoding
1534 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1535 Streamer.emitIntValue(Encoding, Size);
1537 // Personality Function
1538 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1539 if (!DwarfEHFrameOnly && Frame.Personality)
1540 Streamer.emitSymbolValue(Frame.Personality, Size);
1541 else
1542 Streamer.emitIntValue(0, Size); // No personality fn
1544 // LSDA
1545 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1546 if (!DwarfEHFrameOnly && Frame.Lsda)
1547 Streamer.emitSymbolValue(Frame.Lsda, Size);
1548 else
1549 Streamer.emitIntValue(0, Size); // No LSDA
1552 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1553 if (IsEH)
1554 return 1;
1555 switch (DwarfVersion) {
1556 case 2:
1557 return 1;
1558 case 3:
1559 return 3;
1560 case 4:
1561 case 5:
1562 return 4;
1564 llvm_unreachable("Unknown version");
1567 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
1568 MCContext &context = Streamer.getContext();
1569 const MCRegisterInfo *MRI = context.getRegisterInfo();
1570 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1572 MCSymbol *sectionStart = context.createTempSymbol();
1573 Streamer.emitLabel(sectionStart);
1575 MCSymbol *sectionEnd = context.createTempSymbol();
1577 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1578 unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
1579 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1580 bool IsDwarf64 = Format == dwarf::DWARF64;
1582 if (IsDwarf64)
1583 // DWARF64 mark
1584 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1586 // Length
1587 const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
1588 *sectionEnd, UnitLengthBytes);
1589 emitAbsValue(Streamer, Length, OffsetSize);
1591 // CIE ID
1592 uint64_t CIE_ID =
1593 IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
1594 Streamer.emitIntValue(CIE_ID, OffsetSize);
1596 // Version
1597 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1598 Streamer.emitInt8(CIEVersion);
1600 if (IsEH) {
1601 SmallString<8> Augmentation;
1602 Augmentation += "z";
1603 if (Frame.Personality)
1604 Augmentation += "P";
1605 if (Frame.Lsda)
1606 Augmentation += "L";
1607 Augmentation += "R";
1608 if (Frame.IsSignalFrame)
1609 Augmentation += "S";
1610 if (Frame.IsBKeyFrame)
1611 Augmentation += "B";
1612 if (Frame.IsMTETaggedFrame)
1613 Augmentation += "G";
1614 Streamer.emitBytes(Augmentation);
1616 Streamer.emitInt8(0);
1618 if (CIEVersion >= 4) {
1619 // Address Size
1620 Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
1622 // Segment Descriptor Size
1623 Streamer.emitInt8(0);
1626 // Code Alignment Factor
1627 Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1629 // Data Alignment Factor
1630 Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
1632 // Return Address Register
1633 unsigned RAReg = Frame.RAReg;
1634 if (RAReg == static_cast<unsigned>(INT_MAX))
1635 RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
1637 if (CIEVersion == 1) {
1638 assert(RAReg <= 255 &&
1639 "DWARF 2 encodes return_address_register in one byte");
1640 Streamer.emitInt8(RAReg);
1641 } else {
1642 Streamer.emitULEB128IntValue(RAReg);
1645 // Augmentation Data Length (optional)
1646 unsigned augmentationLength = 0;
1647 if (IsEH) {
1648 if (Frame.Personality) {
1649 // Personality Encoding
1650 augmentationLength += 1;
1651 // Personality
1652 augmentationLength +=
1653 getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
1655 if (Frame.Lsda)
1656 augmentationLength += 1;
1657 // Encoding of the FDE pointers
1658 augmentationLength += 1;
1660 Streamer.emitULEB128IntValue(augmentationLength);
1662 // Augmentation Data (optional)
1663 if (Frame.Personality) {
1664 // Personality Encoding
1665 emitEncodingByte(Streamer, Frame.PersonalityEncoding);
1666 // Personality
1667 EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
1670 if (Frame.Lsda)
1671 emitEncodingByte(Streamer, Frame.LsdaEncoding);
1673 // Encoding of the FDE pointers
1674 emitEncodingByte(Streamer, MOFI->getFDEEncoding());
1677 // Initial Instructions
1679 const MCAsmInfo *MAI = context.getAsmInfo();
1680 if (!Frame.IsSimple) {
1681 const std::vector<MCCFIInstruction> &Instructions =
1682 MAI->getInitialFrameState();
1683 emitCFIInstructions(Instructions, nullptr);
1686 InitialCFAOffset = CFAOffset;
1688 // Padding
1689 Streamer.emitValueToAlignment(Align(IsEH ? 4 : MAI->getCodePointerSize()));
1691 Streamer.emitLabel(sectionEnd);
1692 return *sectionStart;
1695 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
1696 const MCDwarfFrameInfo &frame,
1697 bool LastInSection,
1698 const MCSymbol &SectionStart) {
1699 MCContext &context = Streamer.getContext();
1700 MCSymbol *fdeStart = context.createTempSymbol();
1701 MCSymbol *fdeEnd = context.createTempSymbol();
1702 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1704 CFAOffset = InitialCFAOffset;
1706 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1707 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1709 if (Format == dwarf::DWARF64)
1710 // DWARF64 mark
1711 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1713 // Length
1714 const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
1715 emitAbsValue(Streamer, Length, OffsetSize);
1717 Streamer.emitLabel(fdeStart);
1719 // CIE Pointer
1720 const MCAsmInfo *asmInfo = context.getAsmInfo();
1721 if (IsEH) {
1722 const MCExpr *offset =
1723 makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
1724 emitAbsValue(Streamer, offset, OffsetSize);
1725 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1726 const MCExpr *offset =
1727 makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
1728 emitAbsValue(Streamer, offset, OffsetSize);
1729 } else {
1730 Streamer.emitSymbolValue(&cieStart, OffsetSize,
1731 asmInfo->needsDwarfSectionOffsetDirective());
1734 // PC Begin
1735 unsigned PCEncoding =
1736 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1737 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
1738 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
1740 // PC Range
1741 const MCExpr *Range =
1742 makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
1743 emitAbsValue(Streamer, Range, PCSize);
1745 if (IsEH) {
1746 // Augmentation Data Length
1747 unsigned augmentationLength = 0;
1749 if (frame.Lsda)
1750 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
1752 Streamer.emitULEB128IntValue(augmentationLength);
1754 // Augmentation Data
1755 if (frame.Lsda)
1756 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
1759 // Call Frame Instructions
1760 emitCFIInstructions(frame.Instructions, frame.Begin);
1762 // Padding
1763 // The size of a .eh_frame section has to be a multiple of the alignment
1764 // since a null CIE is interpreted as the end. Old systems overaligned
1765 // .eh_frame, so we do too and account for it in the last FDE.
1766 unsigned Alignment = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
1767 Streamer.emitValueToAlignment(Align(Alignment));
1769 Streamer.emitLabel(fdeEnd);
1772 namespace {
1774 struct CIEKey {
1775 static const CIEKey getEmptyKey() {
1776 return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX),
1777 false, false);
1780 static const CIEKey getTombstoneKey() {
1781 return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX),
1782 false, false);
1785 CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
1786 unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple,
1787 unsigned RAReg, bool IsBKeyFrame, bool IsMTETaggedFrame)
1788 : Personality(Personality), PersonalityEncoding(PersonalityEncoding),
1789 LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame),
1790 IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame),
1791 IsMTETaggedFrame(IsMTETaggedFrame) {}
1793 explicit CIEKey(const MCDwarfFrameInfo &Frame)
1794 : Personality(Frame.Personality),
1795 PersonalityEncoding(Frame.PersonalityEncoding),
1796 LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
1797 IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
1798 IsBKeyFrame(Frame.IsBKeyFrame),
1799 IsMTETaggedFrame(Frame.IsMTETaggedFrame) {}
1801 StringRef PersonalityName() const {
1802 if (!Personality)
1803 return StringRef();
1804 return Personality->getName();
1807 bool operator<(const CIEKey &Other) const {
1808 return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
1809 IsSignalFrame, IsSimple, RAReg, IsBKeyFrame,
1810 IsMTETaggedFrame) <
1811 std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
1812 Other.LsdaEncoding, Other.IsSignalFrame,
1813 Other.IsSimple, Other.RAReg, Other.IsBKeyFrame,
1814 Other.IsMTETaggedFrame);
1817 const MCSymbol *Personality;
1818 unsigned PersonalityEncoding;
1819 unsigned LsdaEncoding;
1820 bool IsSignalFrame;
1821 bool IsSimple;
1822 unsigned RAReg;
1823 bool IsBKeyFrame;
1824 bool IsMTETaggedFrame;
1827 } // end anonymous namespace
1829 namespace llvm {
1831 template <> struct DenseMapInfo<CIEKey> {
1832 static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); }
1833 static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); }
1835 static unsigned getHashValue(const CIEKey &Key) {
1836 return static_cast<unsigned>(
1837 hash_combine(Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding,
1838 Key.IsSignalFrame, Key.IsSimple, Key.RAReg,
1839 Key.IsBKeyFrame, Key.IsMTETaggedFrame));
1842 static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) {
1843 return LHS.Personality == RHS.Personality &&
1844 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1845 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1846 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1847 LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg &&
1848 LHS.IsBKeyFrame == RHS.IsBKeyFrame &&
1849 LHS.IsMTETaggedFrame == RHS.IsMTETaggedFrame;
1853 } // end namespace llvm
1855 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1856 bool IsEH) {
1857 MCContext &Context = Streamer.getContext();
1858 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1859 const MCAsmInfo *AsmInfo = Context.getAsmInfo();
1860 FrameEmitterImpl Emitter(IsEH, Streamer);
1861 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1863 // Emit the compact unwind info if available.
1864 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1865 if (IsEH && MOFI->getCompactUnwindSection()) {
1866 Streamer.generateCompactUnwindEncodings(MAB);
1867 bool SectionEmitted = false;
1868 for (const MCDwarfFrameInfo &Frame : FrameArray) {
1869 if (Frame.CompactUnwindEncoding == 0) continue;
1870 if (!SectionEmitted) {
1871 Streamer.switchSection(MOFI->getCompactUnwindSection());
1872 Streamer.emitValueToAlignment(Align(AsmInfo->getCodePointerSize()));
1873 SectionEmitted = true;
1875 NeedsEHFrameSection |=
1876 Frame.CompactUnwindEncoding ==
1877 MOFI->getCompactUnwindDwarfEHFrameOnly();
1878 Emitter.EmitCompactUnwind(Frame);
1882 // Compact unwind information can be emitted in the eh_frame section or the
1883 // debug_frame section. Skip emitting FDEs and CIEs when the compact unwind
1884 // doesn't need an eh_frame section and the emission location is the eh_frame
1885 // section.
1886 if (!NeedsEHFrameSection && IsEH) return;
1888 MCSection &Section =
1889 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1890 : *MOFI->getDwarfFrameSection();
1892 Streamer.switchSection(&Section);
1893 MCSymbol *SectionStart = Context.createTempSymbol();
1894 Streamer.emitLabel(SectionStart);
1896 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1898 const MCSymbol *DummyDebugKey = nullptr;
1899 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
1900 // Sort the FDEs by their corresponding CIE before we emit them.
1901 // This isn't technically necessary according to the DWARF standard,
1902 // but the Android libunwindstack rejects eh_frame sections where
1903 // an FDE refers to a CIE other than the closest previous CIE.
1904 std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
1905 llvm::stable_sort(FrameArrayX,
1906 [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
1907 return CIEKey(X) < CIEKey(Y);
1909 for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
1910 const MCDwarfFrameInfo &Frame = *I;
1911 ++I;
1912 if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
1913 MOFI->getCompactUnwindDwarfEHFrameOnly() && IsEH)
1914 // CIEs and FDEs can be emitted in either the eh_frame section or the
1915 // debug_frame section, on some platforms (e.g. AArch64) the target object
1916 // file supports emitting a compact_unwind section without an associated
1917 // eh_frame section. If the eh_frame section is not needed, and the
1918 // location where the CIEs and FDEs are to be emitted is the eh_frame
1919 // section, do not emit anything.
1920 continue;
1922 CIEKey Key(Frame);
1923 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1924 if (!CIEStart)
1925 CIEStart = &Emitter.EmitCIE(Frame);
1927 Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart);
1931 void MCDwarfFrameEmitter::encodeAdvanceLoc(MCContext &Context,
1932 uint64_t AddrDelta,
1933 SmallVectorImpl<char> &Out) {
1934 // Scale the address delta by the minimum instruction length.
1935 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1936 if (AddrDelta == 0)
1937 return;
1939 support::endianness E =
1940 Context.getAsmInfo()->isLittleEndian() ? support::little : support::big;
1942 if (isUIntN(6, AddrDelta)) {
1943 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1944 Out.push_back(Opcode);
1945 } else if (isUInt<8>(AddrDelta)) {
1946 Out.push_back(dwarf::DW_CFA_advance_loc1);
1947 Out.push_back(AddrDelta);
1948 } else if (isUInt<16>(AddrDelta)) {
1949 Out.push_back(dwarf::DW_CFA_advance_loc2);
1950 support::endian::write<uint16_t>(Out, AddrDelta, E);
1951 } else {
1952 assert(isUInt<32>(AddrDelta));
1953 Out.push_back(dwarf::DW_CFA_advance_loc4);
1954 support::endian::write<uint32_t>(Out, AddrDelta, E);