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