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//===----------------------------------------------------------------------===//
8
9#include "llvm/MC/MCDwarf.h"
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
16#include "llvm/BinaryFormat/Dwarf.h"
17#include "llvm/Config/config.h"
18#include "llvm/MC/MCAsmInfo.h"
19#include "llvm/MC/MCContext.h"
20#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCObjectFileInfo.h"
22#include "llvm/MC/MCObjectStreamer.h"
23#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCSection.h"
25#include "llvm/MC/MCStreamer.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/Support/Casting.h"
28#include "llvm/Support/EndianStream.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/LEB128.h"
31#include "llvm/Support/MathExtras.h"
32#include "llvm/Support/Path.h"
33#include "llvm/Support/SourceMgr.h"
34#include "llvm/Support/raw_ostream.h"
35#include <cassert>
36#include <cstdint>
37#include <optional>
38#include <string>
39#include <utility>
40#include <vector>
41
42using namespace llvm;
43
44MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
45 MCSymbol *Start = S.getContext().createTempSymbol(Name: "debug_list_header_start");
46 MCSymbol *End = S.getContext().createTempSymbol(Name: "debug_list_header_end");
47 auto DwarfFormat = S.getContext().getDwarfFormat();
48 if (DwarfFormat == dwarf::DWARF64) {
49 S.AddComment(T: "DWARF64 mark");
50 S.emitInt32(Value: dwarf::DW_LENGTH_DWARF64);
51 }
52 S.AddComment(T: "Length");
53 S.emitAbsoluteSymbolDiff(Hi: End, Lo: Start,
54 Size: dwarf::getDwarfOffsetByteSize(Format: DwarfFormat));
55 S.emitLabel(Symbol: Start);
56 S.AddComment(T: "Version");
57 S.emitInt16(Value: S.getContext().getDwarfVersion());
58 S.AddComment(T: "Address size");
59 S.emitInt8(Value: S.getContext().getAsmInfo().getCodePointerSize());
60 S.AddComment(T: "Segment selector size");
61 S.emitInt8(Value: 0);
62 return End;
63}
64
65static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
66 unsigned MinInsnLength = Context.getAsmInfo().getMinInstAlignment();
67 if (MinInsnLength == 1)
68 return AddrDelta;
69 if (AddrDelta % MinInsnLength != 0) {
70 // TODO: report this error, but really only once.
71 ;
72 }
73 return AddrDelta / MinInsnLength;
74}
75
76MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) {
77 UseRelocs = Ctx.getAsmInfo().doesDwarfUseRelocationsAcrossSections();
78 if (UseRelocs) {
79 MCSection *DwarfLineStrSection =
80 Ctx.getObjectFileInfo()->getDwarfLineStrSection();
81 assert(DwarfLineStrSection && "DwarfLineStrSection must not be NULL");
82 LineStrLabel = DwarfLineStrSection->getBeginSymbol();
83 }
84}
85
86//
87// This is called when an instruction is assembled into the specified section
88// and if there is information from the last .loc directive that has yet to have
89// a line entry made for it is made.
90//
91void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) {
92 if (!MCOS->getContext().getDwarfLocSeen())
93 return;
94
95 // Create a symbol at in the current section for use in the line entry.
96 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
97 // Set the value of the symbol to use for the MCDwarfLineEntry.
98 MCOS->emitLabel(Symbol: LineSym);
99
100 // Get the current .loc info saved in the context.
101 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
102
103 // Create a (local) line entry with the symbol and the current .loc info.
104 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
105
106 // clear DwarfLocSeen saying the current .loc info is now used.
107 MCOS->getContext().clearDwarfLocSeen();
108
109 // Add the line entry to this section's entries.
110 MCOS->getContext()
111 .getMCDwarfLineTable(CUID: MCOS->getContext().getDwarfCompileUnitID())
112 .getMCLineSections()
113 .addLineEntry(LineEntry, Sec: Section);
114}
115
116//
117// This helper routine returns an expression of End - Start - IntVal .
118//
119static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
120 const MCSymbol &Start,
121 const MCSymbol &End,
122 int IntVal) {
123 const MCExpr *Res = MCSymbolRefExpr::create(Symbol: &End, Ctx);
124 const MCExpr *RHS = MCSymbolRefExpr::create(Symbol: &Start, Ctx);
125 const MCExpr *Res1 = MCBinaryExpr::create(Op: MCBinaryExpr::Sub, LHS: Res, RHS, Ctx);
126 const MCExpr *Res2 = MCConstantExpr::create(Value: IntVal, Ctx);
127 const MCExpr *Res3 = MCBinaryExpr::create(Op: MCBinaryExpr::Sub, LHS: Res1, RHS: Res2, Ctx);
128 return Res3;
129}
130
131void MCLineSection::addEndEntry(MCSymbol *EndLabel) {
132 auto *Sec = &EndLabel->getSection();
133 // The line table may be empty, which we should skip adding an end entry.
134 // There are three cases:
135 // (1) MCAsmStreamer - emitDwarfLocDirective emits a location directive in
136 // place instead of adding a line entry.
137 // (2) MCObjectStreamer - if a function has incomplete debug info where
138 // instructions don't have DILocations, the line entries are missing.
139 // (3) It's also possible that there are no prior line entries if the section
140 // itself is empty before this end label.
141 auto I = MCLineDivisions.find(Key: Sec);
142 if (I == MCLineDivisions.end()) // If section not found, do nothing.
143 return;
144
145 auto &Entries = I->second;
146 // If no entries in this section's list, nothing to base the end entry on.
147 if (Entries.empty())
148 return;
149
150 // Create the end entry based on the last existing entry.
151 MCDwarfLineEntry EndEntry = Entries.back();
152
153 // An end entry is just for marking the end of a sequence of code locations.
154 // It should not carry forward a LineStreamLabel from a previous special entry
155 // if Entries.back() happened to be such an entry. So here we clear
156 // LineStreamLabel.
157 EndEntry.LineStreamLabel = nullptr;
158 EndEntry.setEndLabel(EndLabel);
159 Entries.push_back(x: EndEntry);
160}
161
162//
163// This emits the Dwarf line table for the specified section from the entries
164// in the LineSection.
165//
166void MCDwarfLineTable::emitOne(
167 MCStreamer *MCOS, MCSection *Section,
168 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
169
170 unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator;
171 bool IsAtStartSeq;
172 MCSymbol *PrevLabel;
173 auto init = [&]() {
174 FileNum = 1;
175 LastLine = 1;
176 Column = 0;
177 Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
178 Isa = 0;
179 Discriminator = 0;
180 PrevLabel = nullptr;
181 IsAtStartSeq = true;
182 };
183 init();
184
185 // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
186 bool EndEntryEmitted = false;
187 for (auto It = LineEntries.begin(); It != LineEntries.end(); ++It) {
188 auto LineEntry = *It;
189 MCSymbol *CurrLabel = LineEntry.getLabel();
190 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
191
192 if (LineEntry.LineStreamLabel) {
193 if (!IsAtStartSeq) {
194 auto *Label = CurrLabel;
195 auto NextIt = It + 1;
196 // LineEntry with a null Label is probably a fake LineEntry we added
197 // when `-emit-func-debug-line-table-offsets` in order to terminate the
198 // sequence. Look for the next Label if possible, otherwise we will set
199 // the PC to the end of the section.
200 if (!Label && NextIt != LineEntries.end()) {
201 Label = NextIt->getLabel();
202 }
203 MCOS->emitDwarfLineEndEntry(Section, LastLabel: PrevLabel,
204 /*EndLabel =*/Label);
205 init();
206 }
207 MCOS->emitLabel(Symbol: LineEntry.LineStreamLabel, Loc: LineEntry.StreamLabelDefLoc);
208 continue;
209 }
210
211 if (LineEntry.IsEndEntry) {
212 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel: PrevLabel, Label: CurrLabel,
213 PointerSize: asmInfo.getCodePointerSize());
214 init();
215 EndEntryEmitted = true;
216 continue;
217 }
218
219 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
220
221 if (FileNum != LineEntry.getFileNum()) {
222 FileNum = LineEntry.getFileNum();
223 MCOS->emitInt8(Value: dwarf::DW_LNS_set_file);
224 MCOS->emitULEB128IntValue(Value: FileNum);
225 }
226 if (Column != LineEntry.getColumn()) {
227 Column = LineEntry.getColumn();
228 MCOS->emitInt8(Value: dwarf::DW_LNS_set_column);
229 MCOS->emitULEB128IntValue(Value: Column);
230 }
231 if (Discriminator != LineEntry.getDiscriminator() &&
232 MCOS->getContext().getDwarfVersion() >= 4) {
233 Discriminator = LineEntry.getDiscriminator();
234 unsigned Size = getULEB128Size(Value: Discriminator);
235 MCOS->emitInt8(Value: dwarf::DW_LNS_extended_op);
236 MCOS->emitULEB128IntValue(Value: Size + 1);
237 MCOS->emitInt8(Value: dwarf::DW_LNE_set_discriminator);
238 MCOS->emitULEB128IntValue(Value: Discriminator);
239 }
240 if (Isa != LineEntry.getIsa()) {
241 Isa = LineEntry.getIsa();
242 MCOS->emitInt8(Value: dwarf::DW_LNS_set_isa);
243 MCOS->emitULEB128IntValue(Value: Isa);
244 }
245 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
246 Flags = LineEntry.getFlags();
247 MCOS->emitInt8(Value: dwarf::DW_LNS_negate_stmt);
248 }
249 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
250 MCOS->emitInt8(Value: dwarf::DW_LNS_set_basic_block);
251 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
252 MCOS->emitInt8(Value: dwarf::DW_LNS_set_prologue_end);
253 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
254 MCOS->emitInt8(Value: dwarf::DW_LNS_set_epilogue_begin);
255
256 // At this point we want to emit/create the sequence to encode the delta in
257 // line numbers and the increment of the address from the previous Label
258 // and the current Label.
259 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel: PrevLabel, Label: CurrLabel,
260 PointerSize: asmInfo.getCodePointerSize());
261
262 Discriminator = 0;
263 LastLine = LineEntry.getLine();
264 PrevLabel = CurrLabel;
265 IsAtStartSeq = false;
266 }
267
268 // Generate DWARF line end entry.
269 // We do not need this for DwarfDebug that explicitly terminates the line
270 // table using ranges whenever CU or section changes. However, the MC path
271 // does not track ranges nor terminate the line table. In that case,
272 // conservatively use the section end symbol to end the line table.
273 if (!EndEntryEmitted && !IsAtStartSeq)
274 MCOS->emitDwarfLineEndEntry(Section, LastLabel: PrevLabel);
275}
276
277void MCDwarfLineTable::endCurrentSeqAndEmitLineStreamLabel(MCStreamer *MCOS,
278 SMLoc DefLoc,
279 StringRef Name) {
280 auto &ctx = MCOS->getContext();
281 auto *LineStreamLabel = ctx.getOrCreateSymbol(Name);
282 auto *LineSym = ctx.createTempSymbol();
283 MCOS->emitLabel(Symbol: LineSym);
284 const MCDwarfLoc &DwarfLoc = ctx.getCurrentDwarfLoc();
285
286 // Create a 'fake' line entry by having LineStreamLabel be non-null. This
287 // won't actually emit any line information, it will reset the line table
288 // sequence and emit a label at the start of the new line table sequence.
289 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc, LineStreamLabel, DefLoc);
290 getMCLineSections().addLineEntry(LineEntry, Sec: MCOS->getCurrentSectionOnly());
291}
292
293//
294// This emits the Dwarf file and the line tables.
295//
296void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) {
297 MCContext &context = MCOS->getContext();
298
299 auto &LineTables = context.getMCDwarfLineTables();
300
301 // Bail out early so we don't switch to the debug_line section needlessly and
302 // in doing so create an unnecessary (if empty) section.
303 if (LineTables.empty())
304 return;
305
306 // In a v5 non-split line table, put the strings in a separate section.
307 std::optional<MCDwarfLineStr> LineStr;
308 if (context.getDwarfVersion() >= 5)
309 LineStr.emplace(args&: context);
310
311 // Switch to the section where the table will be emitted into.
312 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfLineSection());
313
314 // Handle the rest of the Compile Units.
315 for (const auto &CUIDTablePair : LineTables) {
316 CUIDTablePair.second.emitCU(MCOS, Params, LineStr);
317 }
318
319 if (LineStr)
320 LineStr->emitSection(MCOS);
321}
322
323void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
324 MCSection *Section) const {
325 if (!HasSplitLineTable)
326 return;
327 std::optional<MCDwarfLineStr> NoLineStr(std::nullopt);
328 MCOS.switchSection(Section);
329 MCOS.emitLabel(Symbol: Header.Emit(MCOS: &MCOS, Params, SpecialOpcodeLengths: {}, LineStr&: NoLineStr).second);
330}
331
332std::pair<MCSymbol *, MCSymbol *>
333MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
334 std::optional<MCDwarfLineStr> &LineStr) const {
335 static const char StandardOpcodeLengths[] = {
336 0, // length of DW_LNS_copy
337 1, // length of DW_LNS_advance_pc
338 1, // length of DW_LNS_advance_line
339 1, // length of DW_LNS_set_file
340 1, // length of DW_LNS_set_column
341 0, // length of DW_LNS_negate_stmt
342 0, // length of DW_LNS_set_basic_block
343 0, // length of DW_LNS_const_add_pc
344 1, // length of DW_LNS_fixed_advance_pc
345 0, // length of DW_LNS_set_prologue_end
346 0, // length of DW_LNS_set_epilogue_begin
347 1 // DW_LNS_set_isa
348 };
349 assert(std::size(StandardOpcodeLengths) >=
350 (Params.DWARF2LineOpcodeBase - 1U));
351 return Emit(MCOS, Params,
352 SpecialOpcodeLengths: ArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
353 LineStr);
354}
355
356static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
357 MCContext &Context = OS.getContext();
358 assert(!isa<MCSymbolRefExpr>(Expr));
359 if (!Context.getAsmInfo().doesSetDirectiveSuppressReloc())
360 return Expr;
361
362 // On Mach-O, try to avoid a relocation by using a set directive.
363 MCSymbol *ABS = Context.createTempSymbol();
364 OS.emitAssignment(Symbol: ABS, Value: Expr);
365 return MCSymbolRefExpr::create(Symbol: ABS, Ctx&: Context);
366}
367
368static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
369 const MCExpr *ABS = forceExpAbs(OS, Expr: Value);
370 OS.emitValue(Value: ABS, Size);
371}
372
373void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
374 // Switch to the .debug_line_str section.
375 MCOS->switchSection(
376 Section: MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
377 SmallString<0> Data = getFinalizedData();
378 MCOS->emitBinaryData(Data: Data.str());
379}
380
381SmallString<0> MCDwarfLineStr::getFinalizedData() {
382 // Emit the strings without perturbing the offsets we used.
383 if (!LineStrings.isFinalized())
384 LineStrings.finalizeInOrder();
385 SmallString<0> Data;
386 Data.resize(N: LineStrings.getSize());
387 LineStrings.write(Buf: (uint8_t *)Data.data());
388 return Data;
389}
390
391size_t MCDwarfLineStr::addString(StringRef Path) {
392 return LineStrings.add(S: Path);
393}
394
395void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
396 int RefSize =
397 dwarf::getDwarfOffsetByteSize(Format: MCOS->getContext().getDwarfFormat());
398 size_t Offset = addString(Path);
399 if (UseRelocs)
400 MCOS->emitDwarfSectionOffset(Sym: LineStrLabel, Offset, Size: RefSize);
401 else
402 MCOS->emitIntValue(Value: Offset, Size: RefSize);
403}
404
405void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
406 // First the directory table.
407 for (auto &Dir : MCDwarfDirs) {
408 MCOS->emitBytes(Data: Dir); // The DirectoryName, and...
409 MCOS->emitBytes(Data: StringRef("\0", 1)); // its null terminator.
410 }
411 MCOS->emitInt8(Value: 0); // Terminate the directory list.
412
413 // Second the file table.
414 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
415 assert(!MCDwarfFiles[i].Name.empty());
416 MCOS->emitBytes(Data: MCDwarfFiles[i].Name); // FileName and...
417 MCOS->emitBytes(Data: StringRef("\0", 1)); // its null terminator.
418 MCOS->emitULEB128IntValue(Value: MCDwarfFiles[i].DirIndex); // Directory number.
419 MCOS->emitInt8(Value: 0); // Last modification timestamp (always 0).
420 MCOS->emitInt8(Value: 0); // File size (always 0).
421 }
422 MCOS->emitInt8(Value: 0); // Terminate the file list.
423}
424
425static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
426 bool EmitMD5, bool HasAnySource,
427 std::optional<MCDwarfLineStr> &LineStr) {
428 assert(!DwarfFile.Name.empty());
429 if (LineStr)
430 LineStr->emitRef(MCOS, Path: DwarfFile.Name);
431 else {
432 MCOS->emitBytes(Data: DwarfFile.Name); // FileName and...
433 MCOS->emitBytes(Data: StringRef("\0", 1)); // its null terminator.
434 }
435 MCOS->emitULEB128IntValue(Value: DwarfFile.DirIndex); // Directory number.
436 if (EmitMD5) {
437 const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
438 MCOS->emitBinaryData(
439 Data: StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size()));
440 }
441 if (HasAnySource) {
442 // From https://dwarfstd.org/issues/180201.1.html
443 // * The value is an empty null-terminated string if no source is available
444 StringRef Source = DwarfFile.Source.value_or(u: StringRef());
445 // * If the source is available but is an empty file then the value is a
446 // null-terminated single "\n".
447 if (DwarfFile.Source && DwarfFile.Source->empty())
448 Source = "\n";
449 if (LineStr)
450 LineStr->emitRef(MCOS, Path: Source);
451 else {
452 MCOS->emitBytes(Data: Source); // Source and...
453 MCOS->emitBytes(Data: StringRef("\0", 1)); // its null terminator.
454 }
455 }
456}
457
458void MCDwarfLineTableHeader::emitV5FileDirTables(
459 MCStreamer *MCOS, std::optional<MCDwarfLineStr> &LineStr) const {
460 // The directory format, which is just a list of the directory paths. In a
461 // non-split object, these are references to .debug_line_str; in a split
462 // object, they are inline strings.
463 MCOS->emitInt8(Value: 1);
464 MCOS->emitULEB128IntValue(Value: dwarf::DW_LNCT_path);
465 MCOS->emitULEB128IntValue(Value: LineStr ? dwarf::DW_FORM_line_strp
466 : dwarf::DW_FORM_string);
467 MCOS->emitULEB128IntValue(Value: MCDwarfDirs.size() + 1);
468 // Try not to emit an empty compilation directory.
469 SmallString<256> Dir;
470 StringRef CompDir = MCOS->getContext().getCompilationDir();
471 if (!CompilationDir.empty()) {
472 Dir = CompilationDir;
473 MCOS->getContext().remapDebugPath(Path&: Dir);
474 CompDir = Dir.str();
475 if (LineStr)
476 CompDir = LineStr->getSaver().save(S: CompDir);
477 }
478 if (LineStr) {
479 // Record path strings, emit references here.
480 LineStr->emitRef(MCOS, Path: CompDir);
481 for (const auto &Dir : MCDwarfDirs)
482 LineStr->emitRef(MCOS, Path: Dir);
483 } else {
484 // The list of directory paths. Compilation directory comes first.
485 MCOS->emitBytes(Data: CompDir);
486 MCOS->emitBytes(Data: StringRef("\0", 1));
487 for (const auto &Dir : MCDwarfDirs) {
488 MCOS->emitBytes(Data: Dir); // The DirectoryName, and...
489 MCOS->emitBytes(Data: StringRef("\0", 1)); // its null terminator.
490 }
491 }
492
493 // The file format, which is the inline null-terminated filename and a
494 // directory index. We don't track file size/timestamp so don't emit them
495 // in the v5 table. Emit MD5 checksums and source if we have them.
496 uint64_t Entries = 2;
497 if (HasAllMD5)
498 Entries += 1;
499 if (HasAnySource)
500 Entries += 1;
501 MCOS->emitInt8(Value: Entries);
502 MCOS->emitULEB128IntValue(Value: dwarf::DW_LNCT_path);
503 MCOS->emitULEB128IntValue(Value: LineStr ? dwarf::DW_FORM_line_strp
504 : dwarf::DW_FORM_string);
505 MCOS->emitULEB128IntValue(Value: dwarf::DW_LNCT_directory_index);
506 MCOS->emitULEB128IntValue(Value: dwarf::DW_FORM_udata);
507 if (HasAllMD5) {
508 MCOS->emitULEB128IntValue(Value: dwarf::DW_LNCT_MD5);
509 MCOS->emitULEB128IntValue(Value: dwarf::DW_FORM_data16);
510 }
511 if (HasAnySource) {
512 MCOS->emitULEB128IntValue(Value: dwarf::DW_LNCT_LLVM_source);
513 MCOS->emitULEB128IntValue(Value: LineStr ? dwarf::DW_FORM_line_strp
514 : dwarf::DW_FORM_string);
515 }
516 // Then the counted list of files. The root file is file #0, then emit the
517 // files as provide by .file directives.
518 // MCDwarfFiles has an unused element [0] so use size() not size()+1.
519 // But sometimes MCDwarfFiles is empty, in which case we still emit one file.
520 MCOS->emitULEB128IntValue(Value: MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
521 // To accommodate assembler source written for DWARF v4 but trying to emit
522 // v5: If we didn't see a root file explicitly, replicate file #1.
523 assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
524 "No root file and no .file directives");
525 emitOneV5FileEntry(MCOS, DwarfFile: RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
526 EmitMD5: HasAllMD5, HasAnySource, LineStr);
527 for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
528 emitOneV5FileEntry(MCOS, DwarfFile: MCDwarfFiles[i], EmitMD5: HasAllMD5, HasAnySource, LineStr);
529}
530
531std::pair<MCSymbol *, MCSymbol *>
532MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
533 ArrayRef<char> StandardOpcodeLengths,
534 std::optional<MCDwarfLineStr> &LineStr) const {
535 MCContext &context = MCOS->getContext();
536
537 // Create a symbol at the beginning of the line table.
538 MCSymbol *LineStartSym = Label;
539 if (!LineStartSym)
540 LineStartSym = context.createTempSymbol();
541
542 // Set the value of the symbol, as we are at the start of the line table.
543 MCOS->emitDwarfLineStartLabel(StartSym: LineStartSym);
544
545 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format: context.getDwarfFormat());
546
547 MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength(Prefix: "debug_line", Comment: "unit length");
548
549 // Next 2 bytes is the Version.
550 unsigned LineTableVersion = context.getDwarfVersion();
551 MCOS->emitInt16(Value: LineTableVersion);
552
553 // In v5, we get address info next.
554 if (LineTableVersion >= 5) {
555 MCOS->emitInt8(Value: context.getAsmInfo().getCodePointerSize());
556 MCOS->emitInt8(Value: 0); // Segment selector; same as EmitGenDwarfAranges.
557 }
558
559 // Create symbols for the start/end of the prologue.
560 MCSymbol *ProStartSym = context.createTempSymbol(Name: "prologue_start");
561 MCSymbol *ProEndSym = context.createTempSymbol(Name: "prologue_end");
562
563 // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is
564 // actually the length from after the length word, to the end of the prologue.
565 MCOS->emitAbsoluteSymbolDiff(Hi: ProEndSym, Lo: ProStartSym, Size: OffsetSize);
566
567 MCOS->emitLabel(Symbol: ProStartSym);
568
569 // Parameters of the state machine, are next.
570 MCOS->emitInt8(Value: context.getAsmInfo().getMinInstAlignment());
571 // maximum_operations_per_instruction
572 // For non-VLIW architectures this field is always 1.
573 // FIXME: VLIW architectures need to update this field accordingly.
574 if (LineTableVersion >= 4)
575 MCOS->emitInt8(Value: 1);
576 MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
577 MCOS->emitInt8(Value: Params.DWARF2LineBase);
578 MCOS->emitInt8(Value: Params.DWARF2LineRange);
579 MCOS->emitInt8(Value: StandardOpcodeLengths.size() + 1);
580
581 // Standard opcode lengths
582 for (char Length : StandardOpcodeLengths)
583 MCOS->emitInt8(Value: Length);
584
585 // Put out the directory and file tables. The formats vary depending on
586 // the version.
587 if (LineTableVersion >= 5)
588 emitV5FileDirTables(MCOS, LineStr);
589 else
590 emitV2FileDirTables(MCOS);
591
592 // This is the end of the prologue, so set the value of the symbol at the
593 // end of the prologue (that was used in a previous expression).
594 MCOS->emitLabel(Symbol: ProEndSym);
595
596 return std::make_pair(x&: LineStartSym, y&: LineEndSym);
597}
598
599void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
600 std::optional<MCDwarfLineStr> &LineStr) const {
601 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
602
603 // Put out the line tables.
604 for (const auto &LineSec : MCLineSections.getMCLineEntries())
605 emitOne(MCOS, Section: LineSec.first, LineEntries: LineSec.second);
606
607 // This is the end of the section, so set the value of the symbol at the end
608 // of this section (that was used in a previous expression).
609 MCOS->emitLabel(Symbol: LineEndSym);
610}
611
612Expected<unsigned>
613MCDwarfLineTable::tryGetFile(StringRef &Directory, StringRef &FileName,
614 std::optional<MD5::MD5Result> Checksum,
615 std::optional<StringRef> Source,
616 uint16_t DwarfVersion, unsigned FileNumber) {
617 return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
618 FileNumber);
619}
620
621static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
622 StringRef &FileName,
623 std::optional<MD5::MD5Result> Checksum) {
624 if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)
625 return false;
626 return RootFile.Checksum == Checksum;
627}
628
629Expected<unsigned>
630MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, StringRef &FileName,
631 std::optional<MD5::MD5Result> Checksum,
632 std::optional<StringRef> Source,
633 uint16_t DwarfVersion, unsigned FileNumber) {
634 if (Directory == CompilationDir)
635 Directory = "";
636 if (FileName.empty()) {
637 FileName = "<stdin>";
638 Directory = "";
639 }
640 assert(!FileName.empty());
641 // Keep track of whether any or all files have an MD5 checksum.
642 // If any files have embedded source, they all must.
643 if (MCDwarfFiles.empty()) {
644 trackMD5Usage(MD5Used: Checksum.has_value());
645 HasAnySource |= Source.has_value();
646 }
647 if (FileNumber == 0) {
648 if (DwarfVersion >= 5 &&
649 isRootFile(RootFile, Directory, FileName, Checksum))
650 return 0;
651 // File numbers start with 1 and/or after any file numbers
652 // allocated by inline-assembler .file directives.
653 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
654 SmallString<256> Buffer;
655 auto IterBool = SourceIdMap.insert(
656 KV: std::make_pair(x: (Directory + Twine('\0') + FileName).toStringRef(Out&: Buffer),
657 y&: FileNumber));
658 if (!IterBool.second)
659 return IterBool.first->second;
660 }
661 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
662 if (FileNumber >= MCDwarfFiles.size())
663 MCDwarfFiles.resize(N: FileNumber + 1);
664
665 // Get the new MCDwarfFile slot for this FileNumber.
666 MCDwarfFile &File = MCDwarfFiles[FileNumber];
667
668 // It is an error to see the same number more than once.
669 if (!File.Name.empty())
670 return make_error<StringError>(Args: "file number already allocated",
671 Args: inconvertibleErrorCode());
672
673 if (Directory.empty()) {
674 // Separate the directory part from the basename of the FileName.
675 StringRef tFileName = sys::path::filename(path: FileName);
676 if (!tFileName.empty()) {
677 Directory = sys::path::parent_path(path: FileName);
678 if (!Directory.empty())
679 FileName = tFileName;
680 }
681 }
682
683 // Find or make an entry in the MCDwarfDirs vector for this Directory.
684 // Capture directory name.
685 unsigned DirIndex;
686 if (Directory.empty()) {
687 // For FileNames with no directories a DirIndex of 0 is used.
688 DirIndex = 0;
689 } else {
690 DirIndex = llvm::find(Range&: MCDwarfDirs, Val: Directory) - MCDwarfDirs.begin();
691 if (DirIndex >= MCDwarfDirs.size())
692 MCDwarfDirs.push_back(Elt: std::string(Directory));
693 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
694 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
695 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
696 // are stored at MCDwarfFiles[FileNumber].Name .
697 DirIndex++;
698 }
699
700 File.Name = std::string(FileName);
701 File.DirIndex = DirIndex;
702 File.Checksum = Checksum;
703 trackMD5Usage(MD5Used: Checksum.has_value());
704 File.Source = Source;
705 if (Source.has_value())
706 HasAnySource = true;
707
708 // return the allocated FileNumber.
709 return FileNumber;
710}
711
712/// Utility function to emit the encoding to a streamer.
713void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
714 int64_t LineDelta, uint64_t AddrDelta) {
715 MCContext &Context = MCOS->getContext();
716 SmallString<256> Tmp;
717 MCDwarfLineAddr::encode(Context, Params, LineDelta, AddrDelta, OS&: Tmp);
718 MCOS->emitBytes(Data: Tmp);
719}
720
721/// Given a special op, return the address skip amount (in units of
722/// DWARF2_LINE_MIN_INSN_LENGTH).
723static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
724 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
725}
726
727/// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
728void MCDwarfLineAddr::encode(MCContext &Context, MCDwarfLineTableParams Params,
729 int64_t LineDelta, uint64_t AddrDelta,
730 SmallVectorImpl<char> &Out) {
731 uint64_t Temp, Opcode;
732 bool NeedCopy = false;
733
734 // The maximum address skip amount that can be encoded with a special op.
735 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, op: 255);
736
737 // Scale the address delta by the minimum instruction length.
738 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
739
740 // A LineDelta of INT64_MAX is a signal that this is actually a
741 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
742 // end_sequence to emit the matrix entry.
743 if (LineDelta == INT64_MAX) {
744 if (AddrDelta == MaxSpecialAddrDelta)
745 Out.push_back(Elt: dwarf::DW_LNS_const_add_pc);
746 else if (AddrDelta) {
747 Out.push_back(Elt: dwarf::DW_LNS_advance_pc);
748 appendLEB128<LEB128Sign::Unsigned>(Buffer&: Out, Value: AddrDelta);
749 }
750 Out.push_back(Elt: dwarf::DW_LNS_extended_op);
751 Out.push_back(Elt: 1);
752 Out.push_back(Elt: dwarf::DW_LNE_end_sequence);
753 return;
754 }
755
756 // Bias the line delta by the base.
757 Temp = LineDelta - Params.DWARF2LineBase;
758
759 // If the line increment is out of range of a special opcode, we must encode
760 // it with DW_LNS_advance_line.
761 if (Temp >= Params.DWARF2LineRange ||
762 Temp + Params.DWARF2LineOpcodeBase > 255) {
763 Out.push_back(Elt: dwarf::DW_LNS_advance_line);
764 appendLEB128<LEB128Sign::Signed>(Buffer&: Out, Value: LineDelta);
765
766 LineDelta = 0;
767 Temp = 0 - Params.DWARF2LineBase;
768 NeedCopy = true;
769 }
770
771 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
772 if (LineDelta == 0 && AddrDelta == 0) {
773 Out.push_back(Elt: dwarf::DW_LNS_copy);
774 return;
775 }
776
777 // Bias the opcode by the special opcode base.
778 Temp += Params.DWARF2LineOpcodeBase;
779
780 // Avoid overflow when addr_delta is large.
781 if (AddrDelta < 256 + MaxSpecialAddrDelta) {
782 // Try using a special opcode.
783 Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
784 if (Opcode <= 255) {
785 Out.push_back(Elt: Opcode);
786 return;
787 }
788
789 // Try using DW_LNS_const_add_pc followed by special op.
790 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
791 if (Opcode <= 255) {
792 Out.push_back(Elt: dwarf::DW_LNS_const_add_pc);
793 Out.push_back(Elt: Opcode);
794 return;
795 }
796 }
797
798 // Otherwise use DW_LNS_advance_pc.
799 Out.push_back(Elt: dwarf::DW_LNS_advance_pc);
800 appendLEB128<LEB128Sign::Unsigned>(Buffer&: Out, Value: AddrDelta);
801
802 if (NeedCopy)
803 Out.push_back(Elt: dwarf::DW_LNS_copy);
804 else {
805 assert(Temp <= 255 && "Buggy special opcode encoding.");
806 Out.push_back(Elt: Temp);
807 }
808}
809
810// Utility function to write a tuple for .debug_abbrev.
811static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
812 MCOS->emitULEB128IntValue(Value: Name);
813 MCOS->emitULEB128IntValue(Value: Form);
814}
815
816// When generating dwarf for assembly source files this emits
817// the data for .debug_abbrev section which contains three DIEs.
818static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
819 MCContext &context = MCOS->getContext();
820 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfAbbrevSection());
821
822 // DW_TAG_compile_unit DIE abbrev (1).
823 MCOS->emitULEB128IntValue(Value: 1);
824 MCOS->emitULEB128IntValue(Value: dwarf::DW_TAG_compile_unit);
825 MCOS->emitInt8(Value: dwarf::DW_CHILDREN_yes);
826 dwarf::Form SecOffsetForm =
827 context.getDwarfVersion() >= 4
828 ? dwarf::DW_FORM_sec_offset
829 : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
830 : dwarf::DW_FORM_data4);
831 EmitAbbrev(MCOS, Name: dwarf::DW_AT_stmt_list, Form: SecOffsetForm);
832 if (context.getGenDwarfSectionSyms().size() > 1 &&
833 context.getDwarfVersion() >= 3) {
834 EmitAbbrev(MCOS, Name: dwarf::DW_AT_ranges, Form: SecOffsetForm);
835 } else {
836 EmitAbbrev(MCOS, Name: dwarf::DW_AT_low_pc, Form: dwarf::DW_FORM_addr);
837 EmitAbbrev(MCOS, Name: dwarf::DW_AT_high_pc, Form: dwarf::DW_FORM_addr);
838 }
839 EmitAbbrev(MCOS, Name: dwarf::DW_AT_name, Form: dwarf::DW_FORM_string);
840 if (!context.getCompilationDir().empty())
841 EmitAbbrev(MCOS, Name: dwarf::DW_AT_comp_dir, Form: dwarf::DW_FORM_string);
842 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
843 if (!DwarfDebugFlags.empty())
844 EmitAbbrev(MCOS, Name: dwarf::DW_AT_APPLE_flags, Form: dwarf::DW_FORM_string);
845 EmitAbbrev(MCOS, Name: dwarf::DW_AT_producer, Form: dwarf::DW_FORM_string);
846
847 if (context.getDwarfVersion() >= 6)
848 EmitAbbrev(MCOS, Name: dwarf::DW_AT_language_name, Form: dwarf::DW_FORM_data2);
849 else
850 EmitAbbrev(MCOS, Name: dwarf::DW_AT_language, Form: dwarf::DW_FORM_data2);
851
852 EmitAbbrev(MCOS, Name: 0, Form: 0);
853
854 // DW_TAG_label DIE abbrev (2).
855 MCOS->emitULEB128IntValue(Value: 2);
856 MCOS->emitULEB128IntValue(Value: dwarf::DW_TAG_label);
857 MCOS->emitInt8(Value: dwarf::DW_CHILDREN_no);
858 EmitAbbrev(MCOS, Name: dwarf::DW_AT_name, Form: dwarf::DW_FORM_string);
859 EmitAbbrev(MCOS, Name: dwarf::DW_AT_decl_file, Form: dwarf::DW_FORM_data4);
860 EmitAbbrev(MCOS, Name: dwarf::DW_AT_decl_line, Form: dwarf::DW_FORM_data4);
861 EmitAbbrev(MCOS, Name: dwarf::DW_AT_low_pc, Form: dwarf::DW_FORM_addr);
862 EmitAbbrev(MCOS, Name: 0, Form: 0);
863
864 // Terminate the abbreviations for this compilation unit.
865 MCOS->emitInt8(Value: 0);
866}
867
868// When generating dwarf for assembly source files this emits the data for
869// .debug_aranges section. This section contains a header and a table of pairs
870// of PointerSize'ed values for the address and size of section(s) with line
871// table entries.
872static void EmitGenDwarfAranges(MCStreamer *MCOS,
873 const MCSymbol *InfoSectionSymbol) {
874 MCContext &context = MCOS->getContext();
875
876 auto &Sections = context.getGenDwarfSectionSyms();
877
878 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfARangesSection());
879
880 unsigned UnitLengthBytes =
881 dwarf::getUnitLengthFieldByteSize(Format: context.getDwarfFormat());
882 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format: context.getDwarfFormat());
883
884 // This will be the length of the .debug_aranges section, first account for
885 // the size of each item in the header (see below where we emit these items).
886 int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
887
888 // Figure the padding after the header before the table of address and size
889 // pairs who's values are PointerSize'ed.
890 const MCAsmInfo &asmInfo = context.getAsmInfo();
891 int AddrSize = asmInfo.getCodePointerSize();
892 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
893 if (Pad == 2 * AddrSize)
894 Pad = 0;
895 Length += Pad;
896
897 // Add the size of the pair of PointerSize'ed values for the address and size
898 // of each section we have in the table.
899 Length += 2 * AddrSize * Sections.size();
900 // And the pair of terminating zeros.
901 Length += 2 * AddrSize;
902
903 // Emit the header for this section.
904 if (context.getDwarfFormat() == dwarf::DWARF64)
905 // The DWARF64 mark.
906 MCOS->emitInt32(Value: dwarf::DW_LENGTH_DWARF64);
907 // The 4 (8 for DWARF64) byte length not including the length of the unit
908 // length field itself.
909 MCOS->emitIntValue(Value: Length - UnitLengthBytes, Size: OffsetSize);
910 // The 2 byte version, which is 2.
911 MCOS->emitInt16(Value: 2);
912 // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
913 // from the start of the .debug_info.
914 if (InfoSectionSymbol)
915 MCOS->emitDwarfSectionOffset(Sym: InfoSectionSymbol, /*Offset=*/0, Size: OffsetSize);
916 else
917 MCOS->emitIntValue(Value: 0, Size: OffsetSize);
918 // The 1 byte size of an address.
919 MCOS->emitInt8(Value: AddrSize);
920 // The 1 byte size of a segment descriptor, we use a value of zero.
921 MCOS->emitInt8(Value: 0);
922 // Align the header with the padding if needed, before we put out the table.
923 for(int i = 0; i < Pad; i++)
924 MCOS->emitInt8(Value: 0);
925
926 // Now emit the table of pairs of PointerSize'ed values for the section
927 // addresses and sizes.
928 for (MCSection *Sec : Sections) {
929 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
930 MCSymbol *EndSymbol = Sec->getEndSymbol(Ctx&: context);
931 assert(StartSymbol && "StartSymbol must not be NULL");
932 assert(EndSymbol && "EndSymbol must not be NULL");
933
934 const MCExpr *Addr = MCSymbolRefExpr::create(Symbol: StartSymbol, Ctx&: context);
935 const MCExpr *Size =
936 makeEndMinusStartExpr(Ctx&: context, Start: *StartSymbol, End: *EndSymbol, IntVal: 0);
937 MCOS->emitValue(Value: Addr, Size: AddrSize);
938 emitAbsValue(OS&: *MCOS, Value: Size, Size: AddrSize);
939 }
940
941 // And finally the pair of terminating zeros.
942 MCOS->emitIntValue(Value: 0, Size: AddrSize);
943 MCOS->emitIntValue(Value: 0, Size: AddrSize);
944}
945
946// When generating dwarf for assembly source files this emits the data for
947// .debug_info section which contains three parts. The header, the compile_unit
948// DIE and a list of label DIEs.
949static void EmitGenDwarfInfo(MCStreamer *MCOS,
950 const MCSymbol *AbbrevSectionSymbol,
951 const MCSymbol *LineSectionSymbol,
952 const MCSymbol *RangesSymbol) {
953 MCContext &context = MCOS->getContext();
954
955 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfInfoSection());
956
957 // Create a symbol at the start and end of this section used in here for the
958 // expression to calculate the length in the header.
959 MCSymbol *InfoStart = context.createTempSymbol();
960 MCOS->emitLabel(Symbol: InfoStart);
961 MCSymbol *InfoEnd = context.createTempSymbol();
962
963 // First part: the header.
964
965 unsigned UnitLengthBytes =
966 dwarf::getUnitLengthFieldByteSize(Format: context.getDwarfFormat());
967 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format: context.getDwarfFormat());
968
969 if (context.getDwarfFormat() == dwarf::DWARF64)
970 // Emit DWARF64 mark.
971 MCOS->emitInt32(Value: dwarf::DW_LENGTH_DWARF64);
972
973 // The 4 (8 for DWARF64) byte total length of the information for this
974 // compilation unit, not including the unit length field itself.
975 const MCExpr *Length =
976 makeEndMinusStartExpr(Ctx&: context, Start: *InfoStart, End: *InfoEnd, IntVal: UnitLengthBytes);
977 emitAbsValue(OS&: *MCOS, Value: Length, Size: OffsetSize);
978
979 // The 2 byte DWARF version.
980 MCOS->emitInt16(Value: context.getDwarfVersion());
981
982 // The DWARF v5 header has unit type, address size, abbrev offset.
983 // Earlier versions have abbrev offset, address size.
984 const MCAsmInfo &AsmInfo = context.getAsmInfo();
985 int AddrSize = AsmInfo.getCodePointerSize();
986 if (context.getDwarfVersion() >= 5) {
987 MCOS->emitInt8(Value: dwarf::DW_UT_compile);
988 MCOS->emitInt8(Value: AddrSize);
989 }
990 // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
991 // the .debug_abbrev.
992 if (AbbrevSectionSymbol)
993 MCOS->emitDwarfSectionOffset(Sym: AbbrevSectionSymbol, /*Offset=*/0, Size: OffsetSize);
994 else
995 // Since the abbrevs are at the start of the section, the offset is zero.
996 MCOS->emitIntValue(Value: 0, Size: OffsetSize);
997 if (context.getDwarfVersion() <= 4)
998 MCOS->emitInt8(Value: AddrSize);
999
1000 // Second part: the compile_unit DIE.
1001
1002 // The DW_TAG_compile_unit DIE abbrev (1).
1003 MCOS->emitULEB128IntValue(Value: 1);
1004
1005 // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
1006 // .debug_line section.
1007 if (LineSectionSymbol)
1008 MCOS->emitDwarfSectionOffset(Sym: LineSectionSymbol, /*Offset=*/0, Size: OffsetSize);
1009 else
1010 // The line table is at the start of the section, so the offset is zero.
1011 MCOS->emitIntValue(Value: 0, Size: OffsetSize);
1012
1013 if (RangesSymbol) {
1014 // There are multiple sections containing code, so we must use
1015 // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
1016 // start of the .debug_ranges/.debug_rnglists.
1017 MCOS->emitSymbolValue(Sym: RangesSymbol, Size: OffsetSize);
1018 } else {
1019 // If we only have one non-empty code section, we can use the simpler
1020 // AT_low_pc and AT_high_pc attributes.
1021
1022 // Find the first (and only) non-empty text section
1023 auto &Sections = context.getGenDwarfSectionSyms();
1024 const auto TextSection = Sections.begin();
1025 assert(TextSection != Sections.end() && "No text section found");
1026
1027 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
1028 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(Ctx&: context);
1029 assert(StartSymbol && "StartSymbol must not be NULL");
1030 assert(EndSymbol && "EndSymbol must not be NULL");
1031
1032 // AT_low_pc, the first address of the default .text section.
1033 const MCExpr *Start = MCSymbolRefExpr::create(Symbol: StartSymbol, Ctx&: context);
1034 MCOS->emitValue(Value: Start, Size: AddrSize);
1035
1036 // AT_high_pc, the last address of the default .text section.
1037 const MCExpr *End = MCSymbolRefExpr::create(Symbol: EndSymbol, Ctx&: context);
1038 MCOS->emitValue(Value: End, Size: AddrSize);
1039 }
1040
1041 // AT_name, the name of the source file. Reconstruct from the first directory
1042 // and file table entries.
1043 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
1044 if (MCDwarfDirs.size() > 0) {
1045 MCOS->emitBytes(Data: MCDwarfDirs[0]);
1046 MCOS->emitBytes(Data: sys::path::get_separator());
1047 }
1048 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
1049 // MCDwarfFiles might be empty if we have an empty source file.
1050 // If it's not empty, [0] is unused and [1] is the first actual file.
1051 assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
1052 const MCDwarfFile &RootFile =
1053 MCDwarfFiles.empty()
1054 ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
1055 : MCDwarfFiles[1];
1056 MCOS->emitBytes(Data: RootFile.Name);
1057 MCOS->emitInt8(Value: 0); // NULL byte to terminate the string.
1058
1059 // AT_comp_dir, the working directory the assembly was done in.
1060 if (!context.getCompilationDir().empty()) {
1061 MCOS->emitBytes(Data: context.getCompilationDir());
1062 MCOS->emitInt8(Value: 0); // NULL byte to terminate the string.
1063 }
1064
1065 // AT_APPLE_flags, the command line arguments of the assembler tool.
1066 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
1067 if (!DwarfDebugFlags.empty()){
1068 MCOS->emitBytes(Data: DwarfDebugFlags);
1069 MCOS->emitInt8(Value: 0); // NULL byte to terminate the string.
1070 }
1071
1072 // AT_producer, the version of the assembler tool.
1073 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
1074 if (!DwarfDebugProducer.empty())
1075 MCOS->emitBytes(Data: DwarfDebugProducer);
1076 else
1077 MCOS->emitBytes(Data: StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
1078 MCOS->emitInt8(Value: 0); // NULL byte to terminate the string.
1079
1080 if (context.getDwarfVersion() >= 6) {
1081 // AT_language_name, a 4 byte value.
1082 MCOS->emitInt16(Value: dwarf::DW_LNAME_Assembly);
1083 } else {
1084 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
1085 // draft has no standard code for assembler.
1086 // FIXME: dwarf4 has DW_LANG_Assembly which we could use instead.
1087 MCOS->emitInt16(Value: dwarf::DW_LANG_Mips_Assembler);
1088 }
1089
1090 // Third part: the list of label DIEs.
1091
1092 // Loop on saved info for dwarf labels and create the DIEs for them.
1093 const std::vector<MCGenDwarfLabelEntry> &Entries =
1094 MCOS->getContext().getMCGenDwarfLabelEntries();
1095 for (const auto &Entry : Entries) {
1096 // The DW_TAG_label DIE abbrev (2).
1097 MCOS->emitULEB128IntValue(Value: 2);
1098
1099 // AT_name, of the label without any leading underbar.
1100 MCOS->emitBytes(Data: Entry.getName());
1101 MCOS->emitInt8(Value: 0); // NULL byte to terminate the string.
1102
1103 // AT_decl_file, index into the file table.
1104 MCOS->emitInt32(Value: Entry.getFileNumber());
1105
1106 // AT_decl_line, source line number.
1107 MCOS->emitInt32(Value: Entry.getLineNumber());
1108
1109 // AT_low_pc, start address of the label.
1110 const auto *AT_low_pc = MCSymbolRefExpr::create(Symbol: Entry.getLabel(), Ctx&: context);
1111 MCOS->emitValue(Value: AT_low_pc, Size: AddrSize);
1112 }
1113
1114 // Add the NULL DIE terminating the Compile Unit DIE's.
1115 MCOS->emitInt8(Value: 0);
1116
1117 // Now set the value of the symbol at the end of the info section.
1118 MCOS->emitLabel(Symbol: InfoEnd);
1119}
1120
1121// When generating dwarf for assembly source files this emits the data for
1122// .debug_ranges section. We only emit one range list, which spans all of the
1123// executable sections of this file.
1124static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
1125 MCContext &context = MCOS->getContext();
1126 auto &Sections = context.getGenDwarfSectionSyms();
1127
1128 const MCAsmInfo &AsmInfo = context.getAsmInfo();
1129 int AddrSize = AsmInfo.getCodePointerSize();
1130 MCSymbol *RangesSymbol;
1131
1132 if (MCOS->getContext().getDwarfVersion() >= 5) {
1133 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfRnglistsSection());
1134 MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(S&: *MCOS);
1135 MCOS->AddComment(T: "Offset entry count");
1136 MCOS->emitInt32(Value: 0);
1137 RangesSymbol = context.createTempSymbol(Name: "debug_rnglist0_start");
1138 MCOS->emitLabel(Symbol: RangesSymbol);
1139 for (MCSection *Sec : Sections) {
1140 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1141 const MCSymbol *EndSymbol = Sec->getEndSymbol(Ctx&: context);
1142 const MCExpr *SectionStartAddr =
1143 MCSymbolRefExpr::create(Symbol: StartSymbol, Ctx&: context);
1144 const MCExpr *SectionSize =
1145 makeEndMinusStartExpr(Ctx&: context, Start: *StartSymbol, End: *EndSymbol, IntVal: 0);
1146 MCOS->emitInt8(Value: dwarf::DW_RLE_start_length);
1147 MCOS->emitValue(Value: SectionStartAddr, Size: AddrSize);
1148 MCOS->emitULEB128Value(Value: SectionSize);
1149 }
1150 MCOS->emitInt8(Value: dwarf::DW_RLE_end_of_list);
1151 MCOS->emitLabel(Symbol: EndSymbol);
1152 } else {
1153 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfRangesSection());
1154 RangesSymbol = context.createTempSymbol(Name: "debug_ranges_start");
1155 MCOS->emitLabel(Symbol: RangesSymbol);
1156 for (MCSection *Sec : Sections) {
1157 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1158 const MCSymbol *EndSymbol = Sec->getEndSymbol(Ctx&: context);
1159
1160 // Emit a base address selection entry for the section start.
1161 const MCExpr *SectionStartAddr =
1162 MCSymbolRefExpr::create(Symbol: StartSymbol, Ctx&: context);
1163 MCOS->emitFill(NumBytes: AddrSize, FillValue: 0xFF);
1164 MCOS->emitValue(Value: SectionStartAddr, Size: AddrSize);
1165
1166 // Emit a range list entry spanning this section.
1167 const MCExpr *SectionSize =
1168 makeEndMinusStartExpr(Ctx&: context, Start: *StartSymbol, End: *EndSymbol, IntVal: 0);
1169 MCOS->emitIntValue(Value: 0, Size: AddrSize);
1170 emitAbsValue(OS&: *MCOS, Value: SectionSize, Size: AddrSize);
1171 }
1172
1173 // Emit end of list entry
1174 MCOS->emitIntValue(Value: 0, Size: AddrSize);
1175 MCOS->emitIntValue(Value: 0, Size: AddrSize);
1176 }
1177
1178 return RangesSymbol;
1179}
1180
1181//
1182// When generating dwarf for assembly source files this emits the Dwarf
1183// sections.
1184//
1185void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
1186 MCContext &context = MCOS->getContext();
1187
1188 // Create the dwarf sections in this order (.debug_line already created).
1189 const MCAsmInfo &AsmInfo = context.getAsmInfo();
1190 bool CreateDwarfSectionSymbols =
1191 AsmInfo.doesDwarfUseRelocationsAcrossSections();
1192 MCSymbol *LineSectionSymbol = nullptr;
1193 if (CreateDwarfSectionSymbols)
1194 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(CUID: 0);
1195 MCSymbol *AbbrevSectionSymbol = nullptr;
1196 MCSymbol *InfoSectionSymbol = nullptr;
1197 MCSymbol *RangesSymbol = nullptr;
1198
1199 // Create end symbols for each section, and remove empty sections
1200 MCOS->getContext().finalizeDwarfSections(MCOS&: *MCOS);
1201
1202 // If there are no sections to generate debug info for, we don't need
1203 // to do anything
1204 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
1205 return;
1206
1207 // We only use the .debug_ranges section if we have multiple code sections,
1208 // and we are emitting a DWARF version which supports it.
1209 const bool UseRangesSection =
1210 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
1211 MCOS->getContext().getDwarfVersion() >= 3;
1212 CreateDwarfSectionSymbols |= UseRangesSection;
1213
1214 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfInfoSection());
1215 if (CreateDwarfSectionSymbols) {
1216 InfoSectionSymbol = context.createTempSymbol();
1217 MCOS->emitLabel(Symbol: InfoSectionSymbol);
1218 }
1219 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfAbbrevSection());
1220 if (CreateDwarfSectionSymbols) {
1221 AbbrevSectionSymbol = context.createTempSymbol();
1222 MCOS->emitLabel(Symbol: AbbrevSectionSymbol);
1223 }
1224
1225 MCOS->switchSection(Section: context.getObjectFileInfo()->getDwarfARangesSection());
1226
1227 // Output the data for .debug_aranges section.
1228 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
1229
1230 if (UseRangesSection) {
1231 RangesSymbol = emitGenDwarfRanges(MCOS);
1232 assert(RangesSymbol);
1233 }
1234
1235 // Output the data for .debug_abbrev section.
1236 EmitGenDwarfAbbrev(MCOS);
1237
1238 // Output the data for .debug_info section.
1239 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
1240}
1241
1242//
1243// When generating dwarf for assembly source files this is called when symbol
1244// for a label is created. If this symbol is not a temporary and is in the
1245// section that dwarf is being generated for, save the needed info to create
1246// a dwarf label.
1247//
1248void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
1249 SourceMgr &SrcMgr, SMLoc &Loc) {
1250 // We won't create dwarf labels for temporary symbols.
1251 if (Symbol->isTemporary())
1252 return;
1253 MCContext &context = MCOS->getContext();
1254 // We won't create dwarf labels for symbols in sections that we are not
1255 // generating debug info for.
1256 if (!context.getGenDwarfSectionSyms().count(key: MCOS->getCurrentSectionOnly()))
1257 return;
1258
1259 // The dwarf label's name does not have the symbol name's leading
1260 // underbar if any.
1261 StringRef Name = Symbol->getName();
1262 if (Name.starts_with(Prefix: "_"))
1263 Name = Name.substr(Start: 1, N: Name.size()-1);
1264
1265 // Get the dwarf file number to be used for the dwarf label.
1266 unsigned FileNumber = context.getGenDwarfFileNumber();
1267
1268 // Finding the line number is the expensive part which is why we just don't
1269 // pass it in as for some symbols we won't create a dwarf label.
1270 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
1271 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, BufferID: CurBuffer);
1272
1273 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
1274 // values so that they don't have things like an ARM thumb bit from the
1275 // original symbol. So when used they won't get a low bit set after
1276 // relocation.
1277 MCSymbol *Label = context.createTempSymbol();
1278 MCOS->emitLabel(Symbol: Label);
1279
1280 // Create and entry for the info and add it to the other entries.
1281 MCOS->getContext().addMCGenDwarfLabelEntry(
1282 E: MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
1283}
1284
1285void MCCFIInstruction::replaceRegister(unsigned FromReg, unsigned ToReg) {
1286 auto ReplaceReg = [=](unsigned &Reg) {
1287 if (Reg == FromReg)
1288 Reg = ToReg;
1289 };
1290 auto Visitor = makeVisitor(
1291 Callables: [=](CommonFields &F) {
1292 ReplaceReg(F.Register);
1293 ReplaceReg(F.Register2);
1294 },
1295 Callables: [](EscapeFields &) {}, Callables: [](LabelFields &) {},
1296 Callables: [=](RegisterPairFields &F) {
1297 ReplaceReg(F.Register);
1298 ReplaceReg(F.Reg1);
1299 ReplaceReg(F.Reg2);
1300 },
1301 Callables: [=](VectorRegistersFields &F) {
1302 ReplaceReg(F.Register);
1303 for (VectorRegisterWithLane &VRL : F.VectorRegisters)
1304 ReplaceReg(VRL.Register);
1305 },
1306 Callables: [=](VectorOffsetFields &F) {
1307 ReplaceReg(F.Register);
1308 ReplaceReg(F.MaskRegister);
1309 },
1310 Callables: [=](VectorRegisterMaskFields &F) {
1311 ReplaceReg(F.Register);
1312 ReplaceReg(F.SpillRegister);
1313 ReplaceReg(F.MaskRegister);
1314 },
1315 Callables: [](LLVMSetRAStateFields &) {
1316 llvm_unreachable(".cfi_set_ra_state does not have registers");
1317 });
1318 std::visit(visitor&: Visitor, variants&: ExtraFields);
1319}
1320
1321static int getDataAlignmentFactor(MCStreamer &streamer) {
1322 MCContext &context = streamer.getContext();
1323 const MCAsmInfo &asmInfo = context.getAsmInfo();
1324 int size = asmInfo.getCalleeSaveStackSlotSize();
1325 if (asmInfo.isStackGrowthDirectionUp())
1326 return size;
1327 else
1328 return -size;
1329}
1330
1331static unsigned getSizeForEncoding(MCStreamer &streamer,
1332 unsigned symbolEncoding) {
1333 MCContext &context = streamer.getContext();
1334 unsigned format = symbolEncoding & 0x0f;
1335 switch (format) {
1336 default: llvm_unreachable("Unknown Encoding");
1337 case dwarf::DW_EH_PE_absptr:
1338 case dwarf::DW_EH_PE_signed:
1339 return context.getAsmInfo().getCodePointerSize();
1340 case dwarf::DW_EH_PE_udata2:
1341 case dwarf::DW_EH_PE_sdata2:
1342 return 2;
1343 case dwarf::DW_EH_PE_udata4:
1344 case dwarf::DW_EH_PE_sdata4:
1345 return 4;
1346 case dwarf::DW_EH_PE_udata8:
1347 case dwarf::DW_EH_PE_sdata8:
1348 return 8;
1349 }
1350}
1351
1352static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
1353 unsigned symbolEncoding, bool isEH) {
1354 MCContext &context = streamer.getContext();
1355 const MCAsmInfo &asmInfo = context.getAsmInfo();
1356 const MCExpr *v =
1357 asmInfo.getExprForFDESymbol(Sym: &symbol, Encoding: symbolEncoding, Streamer&: streamer);
1358 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1359 if (asmInfo.doDwarfFDESymbolsUseAbsDiff() && isEH)
1360 emitAbsValue(OS&: streamer, Value: v, Size: size);
1361 else
1362 streamer.emitValue(Value: v, Size: size);
1363}
1364
1365static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1366 unsigned symbolEncoding) {
1367 MCContext &context = streamer.getContext();
1368 const MCAsmInfo &asmInfo = context.getAsmInfo();
1369 const MCExpr *v =
1370 asmInfo.getExprForPersonalitySymbol(Sym: &symbol, Encoding: symbolEncoding, Streamer&: streamer);
1371 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1372 streamer.emitValue(Value: v, Size: size);
1373}
1374
1375namespace {
1376
1377class FrameEmitterImpl {
1378 int64_t CFAOffset = 0;
1379 int64_t InitialCFAOffset = 0;
1380 SmallVector<int64_t, 0> SavedCFAOffsets;
1381 bool IsEH;
1382 MCObjectStreamer &Streamer;
1383
1384public:
1385 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
1386 : IsEH(IsEH), Streamer(Streamer) {}
1387
1388 /// Emit the unwind information in a compact way.
1389 void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
1390
1391 const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
1392 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
1393 bool LastInSection, const MCSymbol &SectionStart);
1394 void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1395 MCSymbol *BaseLabel);
1396 void emitCFIInstruction(const MCCFIInstruction &Instr);
1397};
1398
1399} // end anonymous namespace
1400
1401static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1402 Streamer.emitInt8(Value: Encoding);
1403}
1404
1405static void encodeDwarfRegisterLocation(int DwarfReg, raw_ostream &OS) {
1406 assert(DwarfReg >= 0);
1407 if (DwarfReg < 32) {
1408 OS << uint8_t(dwarf::DW_OP_reg0 + DwarfReg);
1409 } else {
1410 OS << uint8_t(dwarf::DW_OP_regx);
1411 encodeULEB128(Value: DwarfReg, OS);
1412 }
1413}
1414
1415void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
1416 int dataAlignmentFactor = getDataAlignmentFactor(streamer&: Streamer);
1417 auto *MRI = Streamer.getContext().getRegisterInfo();
1418
1419 switch (Instr.getOperation()) {
1420 case MCCFIInstruction::OpRegister: {
1421 unsigned Reg1 = Instr.getRegister();
1422 unsigned Reg2 = Instr.getRegister2();
1423 if (!IsEH) {
1424 Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg1);
1425 Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg2);
1426 }
1427 Streamer.emitInt8(Value: dwarf::DW_CFA_register);
1428 Streamer.emitULEB128IntValue(Value: Reg1);
1429 Streamer.emitULEB128IntValue(Value: Reg2);
1430 return;
1431 }
1432 case MCCFIInstruction::OpWindowSave:
1433 Streamer.emitInt8(Value: dwarf::DW_CFA_GNU_window_save);
1434 return;
1435
1436 case MCCFIInstruction::OpNegateRAState:
1437 Streamer.emitInt8(Value: dwarf::DW_CFA_AARCH64_negate_ra_state);
1438 return;
1439
1440 case MCCFIInstruction::OpNegateRAStateWithPC:
1441 Streamer.emitInt8(Value: dwarf::DW_CFA_AARCH64_negate_ra_state_with_pc);
1442 return;
1443
1444 case MCCFIInstruction::OpLLVMSetRAState: {
1445 Streamer.emitInt8(Value: dwarf::DW_CFA_AARCH64_set_ra_state);
1446 Streamer.emitULEB128IntValue(Value: Instr.getRASignState());
1447 if (MCSymbol *PACSym = Instr.getRASignSymbol()) {
1448 MCContext &Ctx = Streamer.getContext();
1449 const MCExpr *Diff = MCBinaryExpr::createSub(
1450 LHS: MCSymbolRefExpr::create(Symbol: PACSym, Ctx),
1451 RHS: MCSymbolRefExpr::create(Symbol: Instr.getLabel(), Ctx), Ctx);
1452 const MCExpr *Factored = MCBinaryExpr::createDiv(
1453 LHS: Diff,
1454 RHS: MCConstantExpr::create(Value: Ctx.getAsmInfo().getMinInstAlignment(), Ctx),
1455 Ctx);
1456 Streamer.emitSLEB128Value(Value: Factored);
1457 } else {
1458 Streamer.emitSLEB128IntValue(Value: Instr.getRASignOffset());
1459 }
1460 return;
1461 }
1462 case MCCFIInstruction::OpUndefined: {
1463 unsigned Reg = Instr.getRegister();
1464 Streamer.emitInt8(Value: dwarf::DW_CFA_undefined);
1465 Streamer.emitULEB128IntValue(Value: Reg);
1466 return;
1467 }
1468 case MCCFIInstruction::OpAdjustCfaOffset:
1469 case MCCFIInstruction::OpDefCfaOffset: {
1470 const bool IsRelative =
1471 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1472
1473 Streamer.emitInt8(Value: dwarf::DW_CFA_def_cfa_offset);
1474
1475 if (IsRelative)
1476 CFAOffset += Instr.getOffset();
1477 else
1478 CFAOffset = Instr.getOffset();
1479
1480 Streamer.emitULEB128IntValue(Value: CFAOffset);
1481
1482 return;
1483 }
1484 case MCCFIInstruction::OpDefCfa: {
1485 unsigned Reg = Instr.getRegister();
1486 if (!IsEH)
1487 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg);
1488 Streamer.emitInt8(Value: dwarf::DW_CFA_def_cfa);
1489 Streamer.emitULEB128IntValue(Value: Reg);
1490 CFAOffset = Instr.getOffset();
1491 Streamer.emitULEB128IntValue(Value: CFAOffset);
1492
1493 return;
1494 }
1495 case MCCFIInstruction::OpDefCfaRegister: {
1496 unsigned Reg = Instr.getRegister();
1497 if (!IsEH)
1498 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg);
1499 Streamer.emitInt8(Value: dwarf::DW_CFA_def_cfa_register);
1500 Streamer.emitULEB128IntValue(Value: Reg);
1501
1502 return;
1503 }
1504 // TODO: Implement `_sf` variants if/when they need to be emitted.
1505 case MCCFIInstruction::OpLLVMDefAspaceCfa: {
1506 unsigned Reg = Instr.getRegister();
1507 if (!IsEH)
1508 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg);
1509 Streamer.emitIntValue(Value: dwarf::DW_CFA_LLVM_def_aspace_cfa, Size: 1);
1510 Streamer.emitULEB128IntValue(Value: Reg);
1511 CFAOffset = Instr.getOffset();
1512 Streamer.emitULEB128IntValue(Value: CFAOffset);
1513 Streamer.emitULEB128IntValue(Value: Instr.getAddressSpace());
1514
1515 return;
1516 }
1517 case MCCFIInstruction::OpOffset:
1518 case MCCFIInstruction::OpRelOffset: {
1519 const bool IsRelative =
1520 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1521
1522 unsigned Reg = Instr.getRegister();
1523 if (!IsEH)
1524 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg);
1525
1526 int64_t Offset = Instr.getOffset();
1527 if (IsRelative)
1528 Offset -= CFAOffset;
1529 Offset = Offset / dataAlignmentFactor;
1530
1531 if (Offset < 0) {
1532 Streamer.emitInt8(Value: dwarf::DW_CFA_offset_extended_sf);
1533 Streamer.emitULEB128IntValue(Value: Reg);
1534 Streamer.emitSLEB128IntValue(Value: Offset);
1535 } else if (Reg < 64) {
1536 Streamer.emitInt8(Value: dwarf::DW_CFA_offset + Reg);
1537 Streamer.emitULEB128IntValue(Value: Offset);
1538 } else {
1539 Streamer.emitInt8(Value: dwarf::DW_CFA_offset_extended);
1540 Streamer.emitULEB128IntValue(Value: Reg);
1541 Streamer.emitULEB128IntValue(Value: Offset);
1542 }
1543 return;
1544 }
1545 case MCCFIInstruction::OpRememberState:
1546 Streamer.emitInt8(Value: dwarf::DW_CFA_remember_state);
1547 SavedCFAOffsets.push_back(Elt: CFAOffset);
1548 return;
1549 case MCCFIInstruction::OpRestoreState:
1550 Streamer.emitInt8(Value: dwarf::DW_CFA_restore_state);
1551 CFAOffset = SavedCFAOffsets.pop_back_val();
1552 return;
1553 case MCCFIInstruction::OpSameValue: {
1554 unsigned Reg = Instr.getRegister();
1555 Streamer.emitInt8(Value: dwarf::DW_CFA_same_value);
1556 Streamer.emitULEB128IntValue(Value: Reg);
1557 return;
1558 }
1559 case MCCFIInstruction::OpRestore: {
1560 unsigned Reg = Instr.getRegister();
1561 if (!IsEH)
1562 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg);
1563 if (Reg < 64) {
1564 Streamer.emitInt8(Value: dwarf::DW_CFA_restore | Reg);
1565 } else {
1566 Streamer.emitInt8(Value: dwarf::DW_CFA_restore_extended);
1567 Streamer.emitULEB128IntValue(Value: Reg);
1568 }
1569 return;
1570 }
1571 case MCCFIInstruction::OpGnuArgsSize:
1572 Streamer.emitInt8(Value: dwarf::DW_CFA_GNU_args_size);
1573 Streamer.emitULEB128IntValue(Value: Instr.getOffset());
1574 return;
1575
1576 case MCCFIInstruction::OpEscape:
1577 Streamer.emitBytes(Data: Instr.getValues());
1578 return;
1579
1580 case MCCFIInstruction::OpLabel:
1581 Streamer.emitLabel(Symbol: Instr.getCfiLabel(), Loc: Instr.getLoc());
1582 return;
1583 case MCCFIInstruction::OpValOffset: {
1584 unsigned Reg = Instr.getRegister();
1585 if (!IsEH)
1586 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(RegNum: Reg);
1587
1588 int64_t Offset = Instr.getOffset();
1589 Offset = Offset / dataAlignmentFactor;
1590
1591 if (Offset < 0) {
1592 Streamer.emitInt8(Value: dwarf::DW_CFA_val_offset_sf);
1593 Streamer.emitULEB128IntValue(Value: Reg);
1594 Streamer.emitSLEB128IntValue(Value: Offset);
1595 } else {
1596 Streamer.emitInt8(Value: dwarf::DW_CFA_val_offset);
1597 Streamer.emitULEB128IntValue(Value: Reg);
1598 Streamer.emitULEB128IntValue(Value: Offset);
1599 }
1600 return;
1601 }
1602 case MCCFIInstruction::OpLLVMRegisterPair: {
1603 // CFI for a register spilled to a pair of SGPRs is implemented as an
1604 // expression(E) rule where E is a composite location description with
1605 // multiple parts each referencing SGPR register location storage with a bit
1606 // offset of 0. In other words we generate the following DWARF:
1607 //
1608 // DW_CFA_expression: <Reg>,
1609 // (DW_OP_regx <SGPRPair[0]>) (DW_OP_piece <Size>)
1610 // (DW_OP_regx <SGPRPair[1]>) (DW_OP_piece <Size>)
1611 //
1612 // The memory location description for the current CFA is pushed on the
1613 // stack before E is evaluated, but we choose not to drop it as it would
1614 // require a longer expression E and DWARF defines the result of the
1615 // evaulation to be the location description on the top of the stack (i.e.
1616 // the implictly pushed one is just ignored.)
1617
1618 const auto &Fields =
1619 Instr.getExtraFields<MCCFIInstruction::RegisterPairFields>();
1620
1621 SmallString<10> Block;
1622 raw_svector_ostream OSBlock(Block);
1623 encodeDwarfRegisterLocation(DwarfReg: Fields.Reg1, OS&: OSBlock);
1624 if (Fields.Reg1SizeInBits % 8 == 0) {
1625 OSBlock << uint8_t(dwarf::DW_OP_piece);
1626 encodeULEB128(Value: Fields.Reg1SizeInBits / 8, OS&: OSBlock);
1627 } else {
1628 OSBlock << uint8_t(dwarf::DW_OP_bit_piece);
1629 encodeULEB128(Value: Fields.Reg1SizeInBits, OS&: OSBlock);
1630 encodeULEB128(Value: 0, OS&: OSBlock);
1631 }
1632 encodeDwarfRegisterLocation(DwarfReg: Fields.Reg2, OS&: OSBlock);
1633 if (Fields.Reg2SizeInBits % 8 == 0) {
1634 OSBlock << uint8_t(dwarf::DW_OP_piece);
1635 encodeULEB128(Value: Fields.Reg2SizeInBits / 8, OS&: OSBlock);
1636 } else {
1637 OSBlock << uint8_t(dwarf::DW_OP_bit_piece);
1638 encodeULEB128(Value: Fields.Reg2SizeInBits, OS&: OSBlock);
1639 encodeULEB128(Value: 0, OS&: OSBlock);
1640 }
1641
1642 Streamer.emitInt8(Value: dwarf::DW_CFA_expression);
1643 Streamer.emitULEB128IntValue(Value: Fields.Register);
1644 Streamer.emitULEB128IntValue(Value: Block.size());
1645 Streamer.emitBinaryData(Data: StringRef(&Block[0], Block.size()));
1646 return;
1647 }
1648 case MCCFIInstruction::OpLLVMVectorRegisters: {
1649 // CFI for an SGPR spilled to a multiple lanes of VGPRs is implemented as an
1650 // expression(E) rule where E is a composite location description with
1651 // multiple parts each referencing VGPR register location storage with a bit
1652 // offset of the lane index multiplied by the size of a lane. In other words
1653 // we generate the following DWARF:
1654 //
1655 // DW_CFA_expression: <SGPR>,
1656 // (DW_OP_regx <VGPR[0]>) (DW_OP_bit_piece <Size>, <Lane[0]>*<Size>)
1657 // (DW_OP_regx <VGPR[1]>) (DW_OP_bit_piece <Size>, <Lane[1]>*<Size>)
1658 // ...
1659 // (DW_OP_regx <VGPR[N]>) (DW_OP_bit_piece <Size>, <Lane[N]>*<Size>)
1660 //
1661 // However if we're only using a single lane then we can emit a slightly
1662 // more optimal form:
1663 //
1664 // DW_CFA_expression: <SGPR>,
1665 // (DW_OP_regx <VGPR[0]>) (DW_OP_LLVM_offset_uconst <Lane[0]>*<Size>)
1666 //
1667 // The memory location description for the current CFA is pushed on the
1668 // stack before E is evaluated, but we choose not to drop it as it would
1669 // require a longer expression E and DWARF defines the result of the
1670 // evaulation to be the location description on the top of the stack (i.e.
1671 // the implictly pushed one is just ignored.)
1672
1673 const auto &Fields =
1674 Instr.getExtraFields<MCCFIInstruction::VectorRegistersFields>();
1675 auto &VRs = Fields.VectorRegisters;
1676
1677 SmallString<20> Block;
1678 raw_svector_ostream OSBlock(Block);
1679
1680 if (VRs.size() == 1 && VRs[0].SizeInBits % 8 == 0) {
1681 encodeDwarfRegisterLocation(DwarfReg: VRs[0].Register, OS&: OSBlock);
1682 OSBlock << uint8_t(dwarf::DW_OP_LLVM_user)
1683 << uint8_t(dwarf::DW_OP_LLVM_offset_uconst);
1684 encodeULEB128(Value: static_cast<uint64_t>(VRs[0].SizeInBits / 8) * VRs[0].Lane,
1685 OS&: OSBlock);
1686 } else {
1687 for (const auto &VR : VRs) {
1688 // TODO: Detect when we can merge multiple adjacent pieces, or even
1689 // reduce this to a register location description (when all pieces are
1690 // adjacent).
1691 encodeDwarfRegisterLocation(DwarfReg: VR.Register, OS&: OSBlock);
1692 OSBlock << uint8_t(dwarf::DW_OP_bit_piece);
1693 encodeULEB128(Value: VR.SizeInBits, OS&: OSBlock);
1694 encodeULEB128(Value: static_cast<uint64_t>(VR.SizeInBits) * VR.Lane, OS&: OSBlock);
1695 }
1696 }
1697
1698 Streamer.emitInt8(Value: dwarf::DW_CFA_expression);
1699 Streamer.emitULEB128IntValue(Value: Fields.Register);
1700 Streamer.emitULEB128IntValue(Value: Block.size());
1701 Streamer.emitBinaryData(Data: StringRef(&Block[0], Block.size()));
1702 return;
1703 }
1704 case MCCFIInstruction::OpLLVMVectorOffset: {
1705 // CFI for a vector register spilled to memory is implemented as an
1706 // expression(E) rule where E is a location description.
1707 //
1708 // DW_CFA_expression: <VGPR>,
1709 // (DW_OP_regx <VGPR>)
1710 // (DW_OP_swap)
1711 // (DW_OP_LLVM_offset_uconst <Offset>)
1712 // (DW_OP_LLVM_call_frame_entry_reg <Mask>)
1713 // (DW_OP_deref_size <MaskSize>)
1714 // (DW_OP_LLVM_select_bit_piece <VGPRSize> <MaskSize>)
1715
1716 const auto &Fields =
1717 Instr.getExtraFields<MCCFIInstruction::VectorOffsetFields>();
1718
1719 SmallString<20> Block;
1720 raw_svector_ostream OSBlock(Block);
1721 encodeDwarfRegisterLocation(DwarfReg: Fields.Register, OS&: OSBlock);
1722 OSBlock << uint8_t(dwarf::DW_OP_swap);
1723 OSBlock << uint8_t(dwarf::DW_OP_LLVM_user)
1724 << uint8_t(dwarf::DW_OP_LLVM_offset_uconst);
1725 encodeULEB128(Value: Fields.Offset, OS&: OSBlock);
1726 OSBlock << uint8_t(dwarf::DW_OP_LLVM_user)
1727 << uint8_t(dwarf::DW_OP_LLVM_call_frame_entry_reg);
1728 encodeULEB128(Value: Fields.MaskRegister, OS&: OSBlock);
1729 OSBlock << uint8_t(dwarf::DW_OP_deref_size);
1730 OSBlock << uint8_t(Fields.MaskRegisterSizeInBits / 8);
1731 OSBlock << uint8_t(dwarf::DW_OP_LLVM_user)
1732 << uint8_t(dwarf::DW_OP_LLVM_select_bit_piece);
1733 encodeULEB128(Value: Fields.RegisterSizeInBits, OS&: OSBlock);
1734 encodeULEB128(Value: Fields.MaskRegisterSizeInBits, OS&: OSBlock);
1735
1736 Streamer.emitInt8(Value: dwarf::DW_CFA_expression);
1737 Streamer.emitULEB128IntValue(Value: Fields.Register);
1738 Streamer.emitULEB128IntValue(Value: Block.size());
1739 Streamer.emitBinaryData(Data: StringRef(&Block[0], Block.size()));
1740 return;
1741 }
1742 case MCCFIInstruction::OpLLVMVectorRegisterMask: {
1743 // CFI for a VGPR/AGPR partially spilled to another VGPR/AGPR dependent on
1744 // an EXEC mask is implemented as an expression(E) rule where E is a
1745 // location description.
1746 //
1747 // DW_CFA_expression: <GPR>,
1748 // (DW_OP_regx <GPR>)
1749 // (DW_OP_regx <Spill GPR>)
1750 // (DW_OP_LLVM_call_frame_entry_reg <Mask>)
1751 // (DW_OP_deref_size <MaskSize>)
1752 // (DW_OP_LLVM_select_bit_piece <GPR lane size> <MaskSize>)
1753
1754 const auto Fields =
1755 Instr.getExtraFields<MCCFIInstruction::VectorRegisterMaskFields>();
1756
1757 SmallString<20> Block;
1758 raw_svector_ostream OSBlock(Block);
1759 encodeDwarfRegisterLocation(DwarfReg: Fields.Register, OS&: OSBlock);
1760 encodeDwarfRegisterLocation(DwarfReg: Fields.SpillRegister, OS&: OSBlock);
1761 OSBlock << uint8_t(dwarf::DW_OP_LLVM_user)
1762 << uint8_t(dwarf::DW_OP_LLVM_call_frame_entry_reg);
1763 encodeULEB128(Value: Fields.MaskRegister, OS&: OSBlock);
1764 OSBlock << uint8_t(dwarf::DW_OP_deref_size)
1765 << uint8_t(Fields.MaskRegisterSizeInBits / 8);
1766 OSBlock << uint8_t(dwarf::DW_OP_LLVM_user)
1767 << uint8_t(dwarf::DW_OP_LLVM_select_bit_piece);
1768 encodeULEB128(Value: Fields.SpillRegisterLaneSizeInBits, OS&: OSBlock);
1769 encodeULEB128(Value: Fields.MaskRegisterSizeInBits, OS&: OSBlock);
1770
1771 Streamer.emitInt8(Value: dwarf::DW_CFA_expression);
1772 Streamer.emitULEB128IntValue(Value: Fields.Register);
1773 Streamer.emitULEB128IntValue(Value: Block.size());
1774 Streamer.emitBinaryData(Data: StringRef(&Block[0], Block.size()));
1775 return;
1776 }
1777 }
1778
1779 llvm_unreachable("Unhandled case in switch");
1780}
1781
1782/// Emit frame instructions to describe the layout of the frame.
1783void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1784 MCSymbol *BaseLabel) {
1785 for (const MCCFIInstruction &Instr : Instrs) {
1786 MCSymbol *Label = Instr.getLabel();
1787 // Throw out move if the label is invalid.
1788 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1789
1790 // Advance row if new location.
1791 if (BaseLabel && Label) {
1792 MCSymbol *ThisSym = Label;
1793 if (ThisSym != BaseLabel) {
1794 Streamer.emitDwarfAdvanceFrameAddr(LastLabel: BaseLabel, Label: ThisSym, Loc: Instr.getLoc());
1795 BaseLabel = ThisSym;
1796 }
1797 }
1798
1799 emitCFIInstruction(Instr);
1800 }
1801}
1802
1803/// Emit the unwind information in a compact way.
1804void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
1805 MCContext &Context = Streamer.getContext();
1806 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1807
1808 // range-start range-length compact-unwind-enc personality-func lsda
1809 // _foo LfooEnd-_foo 0x00000023 0 0
1810 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1811 //
1812 // .section __LD,__compact_unwind,regular,debug
1813 //
1814 // # compact unwind for _foo
1815 // .quad _foo
1816 // .set L1,LfooEnd-_foo
1817 // .long L1
1818 // .long 0x01010001
1819 // .quad 0
1820 // .quad 0
1821 //
1822 // # compact unwind for _bar
1823 // .quad _bar
1824 // .set L2,LbarEnd-_bar
1825 // .long L2
1826 // .long 0x01020011
1827 // .quad __gxx_personality
1828 // .quad except_tab1
1829
1830 uint32_t Encoding = Frame.CompactUnwindEncoding;
1831 if (!Encoding) return;
1832 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1833
1834 // The encoding needs to know we have an LSDA.
1835 if (!DwarfEHFrameOnly && Frame.Lsda)
1836 Encoding |= 0x40000000;
1837
1838 // Range Start
1839 unsigned FDEEncoding = MOFI->getFDEEncoding();
1840 unsigned Size = getSizeForEncoding(streamer&: Streamer, symbolEncoding: FDEEncoding);
1841 Streamer.emitSymbolValue(Sym: Frame.Begin, Size);
1842
1843 // Range Length
1844 const MCExpr *Range =
1845 makeEndMinusStartExpr(Ctx&: Context, Start: *Frame.Begin, End: *Frame.End, IntVal: 0);
1846 emitAbsValue(OS&: Streamer, Value: Range, Size: 4);
1847
1848 // Compact Encoding
1849 Size = getSizeForEncoding(streamer&: Streamer, symbolEncoding: dwarf::DW_EH_PE_udata4);
1850 Streamer.emitIntValue(Value: Encoding, Size);
1851
1852 // Personality Function
1853 Size = getSizeForEncoding(streamer&: Streamer, symbolEncoding: dwarf::DW_EH_PE_absptr);
1854 if (!DwarfEHFrameOnly && Frame.Personality)
1855 Streamer.emitSymbolValue(Sym: Frame.Personality, Size);
1856 else
1857 Streamer.emitIntValue(Value: 0, Size); // No personality fn
1858
1859 // LSDA
1860 Size = getSizeForEncoding(streamer&: Streamer, symbolEncoding: Frame.LsdaEncoding);
1861 if (!DwarfEHFrameOnly && Frame.Lsda)
1862 Streamer.emitSymbolValue(Sym: Frame.Lsda, Size);
1863 else
1864 Streamer.emitIntValue(Value: 0, Size); // No LSDA
1865}
1866
1867static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1868 if (IsEH)
1869 return 1;
1870 switch (DwarfVersion) {
1871 case 2:
1872 return 1;
1873 case 3:
1874 return 3;
1875 case 4:
1876 case 5:
1877 case 6:
1878 return 4;
1879 }
1880 llvm_unreachable("Unknown version");
1881}
1882
1883const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
1884 MCContext &context = Streamer.getContext();
1885 const MCRegisterInfo *MRI = context.getRegisterInfo();
1886 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1887
1888 MCSymbol *sectionStart = context.createTempSymbol();
1889 Streamer.emitLabel(Symbol: sectionStart);
1890
1891 MCSymbol *sectionEnd = context.createTempSymbol();
1892
1893 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1894 unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
1895 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1896 bool IsDwarf64 = Format == dwarf::DWARF64;
1897
1898 if (IsDwarf64)
1899 // DWARF64 mark
1900 Streamer.emitInt32(Value: dwarf::DW_LENGTH_DWARF64);
1901
1902 // Length
1903 const MCExpr *Length = makeEndMinusStartExpr(Ctx&: context, Start: *sectionStart,
1904 End: *sectionEnd, IntVal: UnitLengthBytes);
1905 emitAbsValue(OS&: Streamer, Value: Length, Size: OffsetSize);
1906
1907 // CIE ID
1908 uint64_t CIE_ID =
1909 IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
1910 Streamer.emitIntValue(Value: CIE_ID, Size: OffsetSize);
1911
1912 // Version
1913 uint8_t CIEVersion = getCIEVersion(IsEH, DwarfVersion: context.getDwarfVersion());
1914 Streamer.emitInt8(Value: CIEVersion);
1915
1916 if (IsEH) {
1917 SmallString<8> Augmentation;
1918 Augmentation += "z";
1919 if (Frame.Personality)
1920 Augmentation += "P";
1921 if (Frame.Lsda)
1922 Augmentation += "L";
1923 Augmentation += "R";
1924 if (Frame.IsSignalFrame)
1925 Augmentation += "S";
1926 if (Frame.IsBKeyFrame)
1927 Augmentation += "B";
1928 if (Frame.IsMTETaggedFrame)
1929 Augmentation += "G";
1930 if (Frame.IsNonHintPAuthFrame)
1931 Augmentation += "N";
1932 Streamer.emitBytes(Data: Augmentation);
1933 }
1934 Streamer.emitInt8(Value: 0);
1935
1936 if (CIEVersion >= 4) {
1937 // Address Size
1938 Streamer.emitInt8(Value: context.getAsmInfo().getCodePointerSize());
1939
1940 // Segment Descriptor Size
1941 Streamer.emitInt8(Value: 0);
1942 }
1943
1944 // Code Alignment Factor
1945 Streamer.emitULEB128IntValue(Value: context.getAsmInfo().getMinInstAlignment());
1946
1947 // Data Alignment Factor
1948 Streamer.emitSLEB128IntValue(Value: getDataAlignmentFactor(streamer&: Streamer));
1949
1950 // Return Address Register
1951 unsigned RAReg = Frame.RAReg;
1952 if (RAReg == static_cast<unsigned>(INT_MAX))
1953 RAReg = MRI->getDwarfRegNum(Reg: MRI->getRARegister(), isEH: IsEH);
1954
1955 if (CIEVersion == 1) {
1956 assert(RAReg <= 255 &&
1957 "DWARF 2 encodes return_address_register in one byte");
1958 Streamer.emitInt8(Value: RAReg);
1959 } else {
1960 Streamer.emitULEB128IntValue(Value: RAReg);
1961 }
1962
1963 // Augmentation Data Length (optional)
1964 unsigned augmentationLength = 0;
1965 if (IsEH) {
1966 if (Frame.Personality) {
1967 // Personality Encoding
1968 augmentationLength += 1;
1969 // Personality
1970 augmentationLength +=
1971 getSizeForEncoding(streamer&: Streamer, symbolEncoding: Frame.PersonalityEncoding);
1972 }
1973 if (Frame.Lsda)
1974 augmentationLength += 1;
1975 // Encoding of the FDE pointers
1976 augmentationLength += 1;
1977
1978 Streamer.emitULEB128IntValue(Value: augmentationLength);
1979
1980 // Augmentation Data (optional)
1981 if (Frame.Personality) {
1982 // Personality Encoding
1983 emitEncodingByte(Streamer, Encoding: Frame.PersonalityEncoding);
1984 // Personality
1985 EmitPersonality(streamer&: Streamer, symbol: *Frame.Personality, symbolEncoding: Frame.PersonalityEncoding);
1986 }
1987
1988 if (Frame.Lsda)
1989 emitEncodingByte(Streamer, Encoding: Frame.LsdaEncoding);
1990
1991 // Encoding of the FDE pointers
1992 emitEncodingByte(Streamer, Encoding: MOFI->getFDEEncoding());
1993 }
1994
1995 // Initial Instructions
1996
1997 const MCAsmInfo &MAI = context.getAsmInfo();
1998 if (!Frame.IsSimple) {
1999 const std::vector<MCCFIInstruction> &Instructions =
2000 MAI.getInitialFrameState();
2001 emitCFIInstructions(Instrs: Instructions, BaseLabel: nullptr);
2002 }
2003
2004 InitialCFAOffset = CFAOffset;
2005
2006 // Padding
2007 Streamer.emitValueToAlignment(Alignment: Align(IsEH ? 4 : MAI.getCodePointerSize()));
2008
2009 Streamer.emitLabel(Symbol: sectionEnd);
2010 return *sectionStart;
2011}
2012
2013void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
2014 const MCDwarfFrameInfo &frame,
2015 bool LastInSection,
2016 const MCSymbol &SectionStart) {
2017 MCContext &context = Streamer.getContext();
2018 MCSymbol *fdeStart = context.createTempSymbol();
2019 MCSymbol *fdeEnd = context.createTempSymbol();
2020 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
2021
2022 CFAOffset = InitialCFAOffset;
2023 SavedCFAOffsets.clear();
2024
2025 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
2026 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
2027
2028 if (Format == dwarf::DWARF64)
2029 // DWARF64 mark
2030 Streamer.emitInt32(Value: dwarf::DW_LENGTH_DWARF64);
2031
2032 // Length
2033 const MCExpr *Length = makeEndMinusStartExpr(Ctx&: context, Start: *fdeStart, End: *fdeEnd, IntVal: 0);
2034 emitAbsValue(OS&: Streamer, Value: Length, Size: OffsetSize);
2035
2036 Streamer.emitLabel(Symbol: fdeStart);
2037
2038 // CIE Pointer
2039 const MCAsmInfo &asmInfo = context.getAsmInfo();
2040 if (IsEH) {
2041 const MCExpr *offset =
2042 makeEndMinusStartExpr(Ctx&: context, Start: cieStart, End: *fdeStart, IntVal: 0);
2043 emitAbsValue(OS&: Streamer, Value: offset, Size: OffsetSize);
2044 } else if (!asmInfo.doesDwarfUseRelocationsAcrossSections()) {
2045 const MCExpr *offset =
2046 makeEndMinusStartExpr(Ctx&: context, Start: SectionStart, End: cieStart, IntVal: 0);
2047 emitAbsValue(OS&: Streamer, Value: offset, Size: OffsetSize);
2048 } else {
2049 Streamer.emitDwarfSectionOffset(Sym: &cieStart, /*Offset=*/0, Size: OffsetSize);
2050 }
2051
2052 // PC Begin
2053 unsigned PCEncoding =
2054 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
2055 unsigned PCSize = getSizeForEncoding(streamer&: Streamer, symbolEncoding: PCEncoding);
2056 emitFDESymbol(streamer&: Streamer, symbol: *frame.Begin, symbolEncoding: PCEncoding, isEH: IsEH);
2057
2058 // PC Range
2059 const MCExpr *Range =
2060 makeEndMinusStartExpr(Ctx&: context, Start: *frame.Begin, End: *frame.End, IntVal: 0);
2061 emitAbsValue(OS&: Streamer, Value: Range, Size: PCSize);
2062
2063 if (IsEH) {
2064 // Augmentation Data Length
2065 unsigned augmentationLength = 0;
2066
2067 if (frame.Lsda)
2068 augmentationLength += getSizeForEncoding(streamer&: Streamer, symbolEncoding: frame.LsdaEncoding);
2069
2070 Streamer.emitULEB128IntValue(Value: augmentationLength);
2071
2072 // Augmentation Data
2073 if (frame.Lsda)
2074 emitFDESymbol(streamer&: Streamer, symbol: *frame.Lsda, symbolEncoding: frame.LsdaEncoding, isEH: true);
2075 }
2076
2077 // Call Frame Instructions
2078 emitCFIInstructions(Instrs: frame.Instructions, BaseLabel: frame.Begin);
2079
2080 // Padding
2081 // The size of a .eh_frame section has to be a multiple of the alignment
2082 // since a null CIE is interpreted as the end. Old systems overaligned
2083 // .eh_frame, so we do too and account for it in the last FDE.
2084 unsigned Alignment = LastInSection ? asmInfo.getCodePointerSize() : PCSize;
2085 Streamer.emitValueToAlignment(Alignment: Align(Alignment));
2086
2087 Streamer.emitLabel(Symbol: fdeEnd);
2088}
2089
2090namespace {
2091
2092struct CIEKey {
2093 CIEKey() = default;
2094
2095 explicit CIEKey(const MCDwarfFrameInfo &Frame, bool IsEH)
2096 : Personality(Frame.Personality),
2097 PersonalityEncoding(Frame.PersonalityEncoding),
2098 LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
2099 IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
2100 IsBKeyFrame(Frame.IsBKeyFrame),
2101 IsMTETaggedFrame(Frame.IsMTETaggedFrame),
2102 IsNonHintPAuthFrame(Frame.IsNonHintPAuthFrame), IsEH(IsEH) {}
2103
2104 StringRef PersonalityName() const {
2105 if (!Personality)
2106 return StringRef();
2107 return Personality->getName();
2108 }
2109
2110 bool operator<(const CIEKey &Other) const {
2111 assert(IsEH == Other.IsEH);
2112 if (!IsEH)
2113 return std::make_tuple(args: RAReg, args: IsSimple) <
2114 std::make_tuple(args: Other.RAReg, args: Other.IsSimple);
2115
2116 return std::make_tuple(args: PersonalityName(), args: PersonalityEncoding, args: LsdaEncoding,
2117 args: IsSignalFrame, args: IsSimple, args: RAReg, args: IsBKeyFrame,
2118 args: IsMTETaggedFrame, args: IsNonHintPAuthFrame) <
2119 std::make_tuple(args: Other.PersonalityName(), args: Other.PersonalityEncoding,
2120 args: Other.LsdaEncoding, args: Other.IsSignalFrame,
2121 args: Other.IsSimple, args: Other.RAReg, args: Other.IsBKeyFrame,
2122 args: Other.IsMTETaggedFrame, args: Other.IsNonHintPAuthFrame);
2123 }
2124
2125 bool operator==(const CIEKey &Other) const {
2126 assert(IsEH == Other.IsEH);
2127 if (!IsEH)
2128 return RAReg == Other.RAReg && IsSimple == Other.IsSimple;
2129
2130 return Personality == Other.Personality &&
2131 PersonalityEncoding == Other.PersonalityEncoding &&
2132 LsdaEncoding == Other.LsdaEncoding &&
2133 IsSignalFrame == Other.IsSignalFrame && IsSimple == Other.IsSimple &&
2134 RAReg == Other.RAReg && IsBKeyFrame == Other.IsBKeyFrame &&
2135 IsMTETaggedFrame == Other.IsMTETaggedFrame &&
2136 IsNonHintPAuthFrame == Other.IsNonHintPAuthFrame;
2137 }
2138 bool operator!=(const CIEKey &Other) const { return !(*this == Other); }
2139
2140 const MCSymbol *Personality = nullptr;
2141 unsigned PersonalityEncoding = 0;
2142 unsigned LsdaEncoding = -1;
2143 bool IsSignalFrame = false;
2144 bool IsSimple = false;
2145 unsigned RAReg = UINT_MAX;
2146 bool IsBKeyFrame = false;
2147 bool IsMTETaggedFrame = false;
2148 bool IsNonHintPAuthFrame = false;
2149 bool IsEH = false;
2150};
2151
2152} // end anonymous namespace
2153
2154void MCDwarfFrameEmitter::emit(MCObjectStreamer &Streamer, bool IsEH) {
2155 MCContext &Context = Streamer.getContext();
2156 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
2157 const MCAsmInfo &AsmInfo = Context.getAsmInfo();
2158 FrameEmitterImpl Emitter(IsEH, Streamer);
2159 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
2160
2161 // Emit the compact unwind info if available.
2162 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
2163 if (IsEH && MOFI->getCompactUnwindSection()) {
2164 Streamer.generateCompactUnwindEncodings();
2165 bool SectionEmitted = false;
2166 for (const MCDwarfFrameInfo &Frame : FrameArray) {
2167 if (Frame.CompactUnwindEncoding == 0) continue;
2168 if (!SectionEmitted) {
2169 Streamer.switchSection(Section: MOFI->getCompactUnwindSection());
2170 Streamer.emitValueToAlignment(Alignment: Align(AsmInfo.getCodePointerSize()));
2171 SectionEmitted = true;
2172 }
2173 NeedsEHFrameSection |=
2174 Frame.CompactUnwindEncoding ==
2175 MOFI->getCompactUnwindDwarfEHFrameOnly();
2176 Emitter.EmitCompactUnwind(Frame);
2177 }
2178 }
2179
2180 // Compact unwind information can be emitted in the eh_frame section or the
2181 // debug_frame section. Skip emitting FDEs and CIEs when the compact unwind
2182 // doesn't need an eh_frame section and the emission location is the eh_frame
2183 // section.
2184 if (!NeedsEHFrameSection && IsEH) return;
2185
2186 MCSection &Section =
2187 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
2188 : *MOFI->getDwarfFrameSection();
2189
2190 Streamer.switchSection(Section: &Section);
2191 MCSymbol *SectionStart = Context.createTempSymbol();
2192 Streamer.emitLabel(Symbol: SectionStart);
2193
2194 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
2195 // Sort the FDEs by their corresponding CIE before we emit them.
2196 // This isn't technically necessary according to the DWARF standard,
2197 // but the Android libunwindstack rejects eh_frame sections where
2198 // an FDE refers to a CIE other than the closest previous CIE.
2199 std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
2200 llvm::stable_sort(Range&: FrameArrayX, C: [IsEH](const MCDwarfFrameInfo &X,
2201 const MCDwarfFrameInfo &Y) {
2202 return CIEKey(X, IsEH) < CIEKey(Y, IsEH);
2203 });
2204 CIEKey LastKey;
2205 const MCSymbol *LastCIEStart = nullptr;
2206 for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
2207 const MCDwarfFrameInfo &Frame = *I;
2208 ++I;
2209 if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
2210 MOFI->getCompactUnwindDwarfEHFrameOnly() && IsEH)
2211 // CIEs and FDEs can be emitted in either the eh_frame section or the
2212 // debug_frame section, on some platforms (e.g. AArch64) the target object
2213 // file supports emitting a compact_unwind section without an associated
2214 // eh_frame section. If the eh_frame section is not needed, and the
2215 // location where the CIEs and FDEs are to be emitted is the eh_frame
2216 // section, do not emit anything.
2217 continue;
2218
2219 CIEKey Key(Frame, IsEH);
2220 if (!LastCIEStart || Key != LastKey) {
2221 LastKey = Key;
2222 LastCIEStart = &Emitter.EmitCIE(Frame);
2223 }
2224
2225 Emitter.EmitFDE(cieStart: *LastCIEStart, frame: Frame, LastInSection: I == E, SectionStart: *SectionStart);
2226 }
2227}
2228
2229void MCDwarfFrameEmitter::encodeAdvanceLoc(MCContext &Context,
2230 uint64_t AddrDelta,
2231 SmallVectorImpl<char> &Out) {
2232 // Scale the address delta by the minimum instruction length.
2233 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
2234 if (AddrDelta == 0)
2235 return;
2236
2237 llvm::endianness E = Context.getAsmInfo().isLittleEndian()
2238 ? llvm::endianness::little
2239 : llvm::endianness::big;
2240
2241 if (isUIntN(N: 6, x: AddrDelta)) {
2242 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
2243 Out.push_back(Elt: Opcode);
2244 } else if (isUInt<8>(x: AddrDelta)) {
2245 Out.push_back(Elt: dwarf::DW_CFA_advance_loc1);
2246 Out.push_back(Elt: AddrDelta);
2247 } else if (isUInt<16>(x: AddrDelta)) {
2248 Out.push_back(Elt: dwarf::DW_CFA_advance_loc2);
2249 support::endian::write<uint16_t>(Out, V: AddrDelta, E);
2250 } else {
2251 assert(isUInt<32>(AddrDelta));
2252 Out.push_back(Elt: dwarf::DW_CFA_advance_loc4);
2253 support::endian::write<uint32_t>(Out, V: AddrDelta, E);
2254 }
2255}
2256