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

source code of llvm/lib/MC/MCDwarf.cpp