1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCDwarf.h"
11 #include "llvm/ADT/Hashing.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/Config/config.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCObjectFileInfo.h"
20 #include "llvm/MC/MCObjectStreamer.h"
21 #include "llvm/MC/MCRegisterInfo.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/LEB128.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/raw_ostream.h"
32 // Given a special op, return the address skip amount (in units of
33 // DWARF2_LINE_MIN_INSN_LENGTH.
34 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
36 // The maximum address skip amount that can be encoded with a special op.
37 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
39 // First special line opcode - leave room for the standard opcodes.
40 // Note: If you want to change this, you'll have to update the
41 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
42 #define DWARF2_LINE_OPCODE_BASE 13
44 // Minimum line offset in a special line info. opcode. This value
45 // was chosen to give a reasonable range of values.
46 #define DWARF2_LINE_BASE -5
48 // Range of line offsets in a special line info. opcode.
49 #define DWARF2_LINE_RANGE 14
51 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
52 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
53 if (MinInsnLength == 1)
55 if (AddrDelta % MinInsnLength != 0) {
56 // TODO: report this error, but really only once.
59 return AddrDelta / MinInsnLength;
63 // This is called when an instruction is assembled into the specified section
64 // and if there is information from the last .loc directive that has yet to have
65 // a line entry made for it is made.
67 void MCLineEntry::Make(MCObjectStreamer *MCOS, const MCSection *Section) {
68 if (!MCOS->getContext().getDwarfLocSeen())
71 // Create a symbol at in the current section for use in the line entry.
72 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
73 // Set the value of the symbol to use for the MCLineEntry.
74 MCOS->EmitLabel(LineSym);
76 // Get the current .loc info saved in the context.
77 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
79 // Create a (local) line entry with the symbol and the current .loc info.
80 MCLineEntry LineEntry(LineSym, DwarfLoc);
82 // clear DwarfLocSeen saying the current .loc info is now used.
83 MCOS->getContext().ClearDwarfLocSeen();
85 // Add the line entry to this section's entries.
87 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
89 .addLineEntry(LineEntry, Section);
93 // This helper routine returns an expression of End - Start + IntVal .
95 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
96 const MCSymbol &Start,
99 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
101 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
103 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
105 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
107 MCConstantExpr::Create(IntVal, MCOS.getContext());
109 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
114 // This emits the Dwarf line table for the specified section from the entries
115 // in the LineSection.
118 EmitDwarfLineTable(MCObjectStreamer *MCOS, const MCSection *Section,
119 const MCLineSection::MCLineEntryCollection &LineEntries) {
120 unsigned FileNum = 1;
121 unsigned LastLine = 1;
123 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
125 unsigned Discriminator = 0;
126 MCSymbol *LastLabel = nullptr;
128 // Loop through each MCLineEntry and encode the dwarf line number table.
129 for (auto it = LineEntries.begin(),
130 ie = LineEntries.end();
133 if (FileNum != it->getFileNum()) {
134 FileNum = it->getFileNum();
135 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
136 MCOS->EmitULEB128IntValue(FileNum);
138 if (Column != it->getColumn()) {
139 Column = it->getColumn();
140 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
141 MCOS->EmitULEB128IntValue(Column);
143 if (Discriminator != it->getDiscriminator()) {
144 Discriminator = it->getDiscriminator();
145 unsigned Size = getULEB128Size(Discriminator);
146 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
147 MCOS->EmitULEB128IntValue(Size + 1);
148 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
149 MCOS->EmitULEB128IntValue(Discriminator);
151 if (Isa != it->getIsa()) {
153 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
154 MCOS->EmitULEB128IntValue(Isa);
156 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
157 Flags = it->getFlags();
158 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
160 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
161 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
162 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
163 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
164 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
165 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
167 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
168 MCSymbol *Label = it->getLabel();
170 // At this point we want to emit/create the sequence to encode the delta in
171 // line numbers and the increment of the address from the previous Label
172 // and the current Label.
173 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
174 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
175 asmInfo->getPointerSize());
177 LastLine = it->getLine();
181 // Emit a DW_LNE_end_sequence for the end of the section.
182 // Using the pointer Section create a temporary label at the end of the
183 // section and use that and the LastLabel to compute the address delta
184 // and use INT64_MAX as the line delta which is the signal that this is
185 // actually a DW_LNE_end_sequence.
187 // Switch to the section to be able to create a symbol at its end.
188 // TODO: keep track of the last subsection so that this symbol appears in the
190 MCOS->SwitchSection(Section);
192 MCContext &Ctx = MCOS->getContext();
193 // Create a symbol at the end of the section.
194 MCSymbol *SectionEnd = Ctx.CreateTempSymbol();
195 // Set the value of the symbol, as we are at the end of the section.
196 MCOS->EmitLabel(SectionEnd);
198 // Switch back the dwarf line section.
199 MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
201 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
202 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
203 AsmInfo->getPointerSize());
207 // This emits the Dwarf file and the line tables.
209 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS) {
210 MCContext &context = MCOS->getContext();
212 auto &LineTables = context.getMCDwarfLineTables();
214 // Bail out early so we don't switch to the debug_line section needlessly and
215 // in doing so create an unnecessary (if empty) section.
216 if (LineTables.empty())
219 // Switch to the section where the table will be emitted into.
220 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
222 // Handle the rest of the Compile Units.
223 for (const auto &CUIDTablePair : LineTables)
224 CUIDTablePair.second.EmitCU(MCOS);
227 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS) const {
228 MCOS.EmitLabel(Header.Emit(&MCOS, None).second);
231 std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
232 static const char StandardOpcodeLengths[] = {
233 0, // length of DW_LNS_copy
234 1, // length of DW_LNS_advance_pc
235 1, // length of DW_LNS_advance_line
236 1, // length of DW_LNS_set_file
237 1, // length of DW_LNS_set_column
238 0, // length of DW_LNS_negate_stmt
239 0, // length of DW_LNS_set_basic_block
240 0, // length of DW_LNS_const_add_pc
241 1, // length of DW_LNS_fixed_advance_pc
242 0, // length of DW_LNS_set_prologue_end
243 0, // length of DW_LNS_set_epilogue_begin
246 assert(array_lengthof(StandardOpcodeLengths) ==
247 (DWARF2_LINE_OPCODE_BASE - 1));
248 return Emit(MCOS, StandardOpcodeLengths);
251 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
252 MCContext &Context = OS.getContext();
253 assert(!isa<MCSymbolRefExpr>(Expr));
254 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
257 MCSymbol *ABS = Context.CreateTempSymbol();
258 OS.EmitAssignment(ABS, Expr);
259 return MCSymbolRefExpr::Create(ABS, Context);
262 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
263 const MCExpr *ABS = forceExpAbs(OS, Value);
264 OS.EmitValue(ABS, Size);
267 std::pair<MCSymbol *, MCSymbol *>
268 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
269 ArrayRef<char> StandardOpcodeLengths) const {
271 MCContext &context = MCOS->getContext();
273 // Create a symbol at the beginning of the line table.
274 MCSymbol *LineStartSym = Label;
276 LineStartSym = context.CreateTempSymbol();
277 // Set the value of the symbol, as we are at the start of the line table.
278 MCOS->EmitLabel(LineStartSym);
280 // Create a symbol for the end of the section (to be set when we get there).
281 MCSymbol *LineEndSym = context.CreateTempSymbol();
283 // The first 4 bytes is the total length of the information for this
284 // compilation unit (not including these 4 bytes for the length).
286 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
288 // Next 2 bytes is the Version, which is Dwarf 2.
289 MCOS->EmitIntValue(2, 2);
291 // Create a symbol for the end of the prologue (to be set when we get there).
292 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
294 // Length of the prologue, is the next 4 bytes. Which is the start of the
295 // section to the end of the prologue. Not including the 4 bytes for the
296 // total length, the 2 bytes for the version, and these 4 bytes for the
297 // length of the prologue.
300 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4);
302 // Parameters of the state machine, are next.
303 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
304 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
305 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
306 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
307 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
309 // Standard opcode lengths
310 for (char Length : StandardOpcodeLengths)
311 MCOS->EmitIntValue(Length, 1);
313 // Put out the directory and file tables.
315 // First the directory table.
316 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
317 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
318 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
320 MCOS->EmitIntValue(0, 1); // Terminate the directory list
322 // Second the file table.
323 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
324 assert(!MCDwarfFiles[i].Name.empty());
325 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
326 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
328 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
329 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
330 MCOS->EmitIntValue(0, 1); // filesize (always 0)
332 MCOS->EmitIntValue(0, 1); // Terminate the file list
334 // This is the end of the prologue, so set the value of the symbol at the
335 // end of the prologue (that was used in a previous expression).
336 MCOS->EmitLabel(ProEndSym);
338 return std::make_pair(LineStartSym, LineEndSym);
341 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS) const {
342 MCSymbol *LineEndSym = Header.Emit(MCOS).second;
344 // Put out the line tables.
345 for (const auto &LineSec : MCLineSections.getMCLineEntries())
346 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
348 // This is the end of the section, so set the value of the symbol at the end
349 // of this section (that was used in a previous expression).
350 MCOS->EmitLabel(LineEndSym);
353 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
354 unsigned FileNumber) {
355 return Header.getFile(Directory, FileName, FileNumber);
358 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
360 unsigned FileNumber) {
361 if (Directory == CompilationDir)
363 if (FileName.empty()) {
364 FileName = "<stdin>";
367 assert(!FileName.empty());
368 if (FileNumber == 0) {
369 FileNumber = SourceIdMap.size() + 1;
370 assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
371 "Don't mix autonumbered and explicit numbered line table usage");
372 auto IterBool = SourceIdMap.insert(
373 std::make_pair((Directory + Twine('\0') + FileName).str(), FileNumber));
374 if (!IterBool.second)
375 return IterBool.first->second;
377 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
378 MCDwarfFiles.resize(FileNumber + 1);
380 // Get the new MCDwarfFile slot for this FileNumber.
381 MCDwarfFile &File = MCDwarfFiles[FileNumber];
383 // It is an error to use see the same number more than once.
384 if (!File.Name.empty())
387 if (Directory.empty()) {
388 // Separate the directory part from the basename of the FileName.
389 StringRef tFileName = sys::path::filename(FileName);
390 if (!tFileName.empty()) {
391 Directory = sys::path::parent_path(FileName);
392 if (!Directory.empty())
393 FileName = tFileName;
397 // Find or make an entry in the MCDwarfDirs vector for this Directory.
398 // Capture directory name.
400 if (Directory.empty()) {
401 // For FileNames with no directories a DirIndex of 0 is used.
405 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
406 if (Directory == MCDwarfDirs[DirIndex])
409 if (DirIndex >= MCDwarfDirs.size())
410 MCDwarfDirs.push_back(Directory);
411 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
412 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
413 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
414 // are stored at MCDwarfFiles[FileNumber].Name .
418 File.Name = FileName;
419 File.DirIndex = DirIndex;
421 // return the allocated FileNumber.
425 /// Utility function to emit the encoding to a streamer.
426 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
427 uint64_t AddrDelta) {
428 MCContext &Context = MCOS->getContext();
429 SmallString<256> Tmp;
430 raw_svector_ostream OS(Tmp);
431 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
432 MCOS->EmitBytes(OS.str());
435 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
436 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
437 uint64_t AddrDelta, raw_ostream &OS) {
438 uint64_t Temp, Opcode;
439 bool NeedCopy = false;
441 // Scale the address delta by the minimum instruction length.
442 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
444 // A LineDelta of INT64_MAX is a signal that this is actually a
445 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
446 // end_sequence to emit the matrix entry.
447 if (LineDelta == INT64_MAX) {
448 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
449 OS << char(dwarf::DW_LNS_const_add_pc);
450 else if (AddrDelta) {
451 OS << char(dwarf::DW_LNS_advance_pc);
452 encodeULEB128(AddrDelta, OS);
454 OS << char(dwarf::DW_LNS_extended_op);
456 OS << char(dwarf::DW_LNE_end_sequence);
460 // Bias the line delta by the base.
461 Temp = LineDelta - DWARF2_LINE_BASE;
463 // If the line increment is out of range of a special opcode, we must encode
464 // it with DW_LNS_advance_line.
465 if (Temp >= DWARF2_LINE_RANGE) {
466 OS << char(dwarf::DW_LNS_advance_line);
467 encodeSLEB128(LineDelta, OS);
470 Temp = 0 - DWARF2_LINE_BASE;
474 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
475 if (LineDelta == 0 && AddrDelta == 0) {
476 OS << char(dwarf::DW_LNS_copy);
480 // Bias the opcode by the special opcode base.
481 Temp += DWARF2_LINE_OPCODE_BASE;
483 // Avoid overflow when addr_delta is large.
484 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
485 // Try using a special opcode.
486 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
492 // Try using DW_LNS_const_add_pc followed by special op.
493 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
495 OS << char(dwarf::DW_LNS_const_add_pc);
501 // Otherwise use DW_LNS_advance_pc.
502 OS << char(dwarf::DW_LNS_advance_pc);
503 encodeULEB128(AddrDelta, OS);
506 OS << char(dwarf::DW_LNS_copy);
511 // Utility function to write a tuple for .debug_abbrev.
512 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
513 MCOS->EmitULEB128IntValue(Name);
514 MCOS->EmitULEB128IntValue(Form);
517 // When generating dwarf for assembly source files this emits
518 // the data for .debug_abbrev section which contains three DIEs.
519 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
520 MCContext &context = MCOS->getContext();
521 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
523 // DW_TAG_compile_unit DIE abbrev (1).
524 MCOS->EmitULEB128IntValue(1);
525 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
526 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
527 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
528 if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
529 MCOS->getContext().getDwarfVersion() >= 3) {
530 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
532 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
533 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
535 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
536 if (!context.getCompilationDir().empty())
537 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
538 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
539 if (!DwarfDebugFlags.empty())
540 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
541 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
542 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
543 EmitAbbrev(MCOS, 0, 0);
545 // DW_TAG_label DIE abbrev (2).
546 MCOS->EmitULEB128IntValue(2);
547 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
548 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
549 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
550 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
551 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
552 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
553 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
554 EmitAbbrev(MCOS, 0, 0);
556 // DW_TAG_unspecified_parameters DIE abbrev (3).
557 MCOS->EmitULEB128IntValue(3);
558 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
559 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
560 EmitAbbrev(MCOS, 0, 0);
562 // Terminate the abbreviations for this compilation unit.
563 MCOS->EmitIntValue(0, 1);
566 // When generating dwarf for assembly source files this emits the data for
567 // .debug_aranges section. This section contains a header and a table of pairs
568 // of PointerSize'ed values for the address and size of section(s) with line
570 static void EmitGenDwarfAranges(MCStreamer *MCOS,
571 const MCSymbol *InfoSectionSymbol) {
572 MCContext &context = MCOS->getContext();
574 auto &Sections = context.getGenDwarfSectionSyms();
576 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
578 // This will be the length of the .debug_aranges section, first account for
579 // the size of each item in the header (see below where we emit these items).
580 int Length = 4 + 2 + 4 + 1 + 1;
582 // Figure the padding after the header before the table of address and size
583 // pairs who's values are PointerSize'ed.
584 const MCAsmInfo *asmInfo = context.getAsmInfo();
585 int AddrSize = asmInfo->getPointerSize();
586 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
587 if (Pad == 2 * AddrSize)
591 // Add the size of the pair of PointerSize'ed values for the address and size
592 // of each section we have in the table.
593 Length += 2 * AddrSize * Sections.size();
594 // And the pair of terminating zeros.
595 Length += 2 * AddrSize;
598 // Emit the header for this section.
599 // The 4 byte length not including the 4 byte value for the length.
600 MCOS->EmitIntValue(Length - 4, 4);
601 // The 2 byte version, which is 2.
602 MCOS->EmitIntValue(2, 2);
603 // The 4 byte offset to the compile unit in the .debug_info from the start
604 // of the .debug_info.
605 if (InfoSectionSymbol)
606 MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
607 asmInfo->needsDwarfSectionOffsetDirective());
609 MCOS->EmitIntValue(0, 4);
610 // The 1 byte size of an address.
611 MCOS->EmitIntValue(AddrSize, 1);
612 // The 1 byte size of a segment descriptor, we use a value of zero.
613 MCOS->EmitIntValue(0, 1);
614 // Align the header with the padding if needed, before we put out the table.
615 for(int i = 0; i < Pad; i++)
616 MCOS->EmitIntValue(0, 1);
618 // Now emit the table of pairs of PointerSize'ed values for the section
619 // addresses and sizes.
620 for (const auto &sec : Sections) {
621 MCSymbol *StartSymbol = sec.second.first;
622 MCSymbol *EndSymbol = sec.second.second;
623 assert(StartSymbol && "StartSymbol must not be NULL");
624 assert(EndSymbol && "EndSymbol must not be NULL");
626 const MCExpr *Addr = MCSymbolRefExpr::Create(
627 StartSymbol, MCSymbolRefExpr::VK_None, context);
628 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
629 *StartSymbol, *EndSymbol, 0);
630 MCOS->EmitValue(Addr, AddrSize);
631 emitAbsValue(*MCOS, Size, AddrSize);
634 // And finally the pair of terminating zeros.
635 MCOS->EmitIntValue(0, AddrSize);
636 MCOS->EmitIntValue(0, AddrSize);
639 // When generating dwarf for assembly source files this emits the data for
640 // .debug_info section which contains three parts. The header, the compile_unit
641 // DIE and a list of label DIEs.
642 static void EmitGenDwarfInfo(MCStreamer *MCOS,
643 const MCSymbol *AbbrevSectionSymbol,
644 const MCSymbol *LineSectionSymbol,
645 const MCSymbol *RangesSectionSymbol) {
646 MCContext &context = MCOS->getContext();
648 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
650 // Create a symbol at the start and end of this section used in here for the
651 // expression to calculate the length in the header.
652 MCSymbol *InfoStart = context.CreateTempSymbol();
653 MCOS->EmitLabel(InfoStart);
654 MCSymbol *InfoEnd = context.CreateTempSymbol();
656 // First part: the header.
658 // The 4 byte total length of the information for this compilation unit, not
659 // including these 4 bytes.
660 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
661 emitAbsValue(*MCOS, Length, 4);
663 // The 2 byte DWARF version.
664 MCOS->EmitIntValue(context.getDwarfVersion(), 2);
666 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
667 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
668 // it is at the start of that section so this is zero.
669 if (AbbrevSectionSymbol == nullptr)
670 MCOS->EmitIntValue(0, 4);
672 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
673 AsmInfo.needsDwarfSectionOffsetDirective());
675 const MCAsmInfo *asmInfo = context.getAsmInfo();
676 int AddrSize = asmInfo->getPointerSize();
677 // The 1 byte size of an address.
678 MCOS->EmitIntValue(AddrSize, 1);
680 // Second part: the compile_unit DIE.
682 // The DW_TAG_compile_unit DIE abbrev (1).
683 MCOS->EmitULEB128IntValue(1);
685 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
686 // which is at the start of that section so this is zero.
687 if (LineSectionSymbol)
688 MCOS->EmitSymbolValue(LineSectionSymbol, 4,
689 AsmInfo.needsDwarfSectionOffsetDirective());
691 MCOS->EmitIntValue(0, 4);
693 if (RangesSectionSymbol) {
694 // There are multiple sections containing code, so we must use the
695 // .debug_ranges sections.
697 // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
698 // to the address range list for this compilation unit.
699 MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
701 // If we only have one non-empty code section, we can use the simpler
702 // AT_low_pc and AT_high_pc attributes.
704 // Find the first (and only) non-empty text section
705 auto &Sections = context.getGenDwarfSectionSyms();
706 const auto TextSection = Sections.begin();
707 assert(TextSection != Sections.end() && "No text section found");
709 MCSymbol *StartSymbol = TextSection->second.first;
710 MCSymbol *EndSymbol = TextSection->second.second;
711 assert(StartSymbol && "StartSymbol must not be NULL");
712 assert(EndSymbol && "EndSymbol must not be NULL");
714 // AT_low_pc, the first address of the default .text section.
715 const MCExpr *Start = MCSymbolRefExpr::Create(
716 StartSymbol, MCSymbolRefExpr::VK_None, context);
717 MCOS->EmitValue(Start, AddrSize);
719 // AT_high_pc, the last address of the default .text section.
720 const MCExpr *End = MCSymbolRefExpr::Create(
721 EndSymbol, MCSymbolRefExpr::VK_None, context);
722 MCOS->EmitValue(End, AddrSize);
725 // AT_name, the name of the source file. Reconstruct from the first directory
726 // and file table entries.
727 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
728 if (MCDwarfDirs.size() > 0) {
729 MCOS->EmitBytes(MCDwarfDirs[0]);
730 MCOS->EmitBytes(sys::path::get_separator());
732 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
733 MCOS->getContext().getMCDwarfFiles();
734 MCOS->EmitBytes(MCDwarfFiles[1].Name);
735 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
737 // AT_comp_dir, the working directory the assembly was done in.
738 if (!context.getCompilationDir().empty()) {
739 MCOS->EmitBytes(context.getCompilationDir());
740 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
743 // AT_APPLE_flags, the command line arguments of the assembler tool.
744 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
745 if (!DwarfDebugFlags.empty()){
746 MCOS->EmitBytes(DwarfDebugFlags);
747 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
750 // AT_producer, the version of the assembler tool.
751 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
752 if (!DwarfDebugProducer.empty())
753 MCOS->EmitBytes(DwarfDebugProducer);
755 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
756 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
758 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
759 // draft has no standard code for assembler.
760 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
762 // Third part: the list of label DIEs.
764 // Loop on saved info for dwarf labels and create the DIEs for them.
765 const std::vector<MCGenDwarfLabelEntry> &Entries =
766 MCOS->getContext().getMCGenDwarfLabelEntries();
767 for (const auto &Entry : Entries) {
768 // The DW_TAG_label DIE abbrev (2).
769 MCOS->EmitULEB128IntValue(2);
771 // AT_name, of the label without any leading underbar.
772 MCOS->EmitBytes(Entry.getName());
773 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
775 // AT_decl_file, index into the file table.
776 MCOS->EmitIntValue(Entry.getFileNumber(), 4);
778 // AT_decl_line, source line number.
779 MCOS->EmitIntValue(Entry.getLineNumber(), 4);
781 // AT_low_pc, start address of the label.
782 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry.getLabel(),
783 MCSymbolRefExpr::VK_None, context);
784 MCOS->EmitValue(AT_low_pc, AddrSize);
786 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
787 MCOS->EmitIntValue(0, 1);
789 // The DW_TAG_unspecified_parameters DIE abbrev (3).
790 MCOS->EmitULEB128IntValue(3);
792 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
793 MCOS->EmitIntValue(0, 1);
796 // Add the NULL DIE terminating the Compile Unit DIE's.
797 MCOS->EmitIntValue(0, 1);
799 // Now set the value of the symbol at the end of the info section.
800 MCOS->EmitLabel(InfoEnd);
803 // When generating dwarf for assembly source files this emits the data for
804 // .debug_ranges section. We only emit one range list, which spans all of the
805 // executable sections of this file.
806 static void EmitGenDwarfRanges(MCStreamer *MCOS) {
807 MCContext &context = MCOS->getContext();
808 auto &Sections = context.getGenDwarfSectionSyms();
810 const MCAsmInfo *AsmInfo = context.getAsmInfo();
811 int AddrSize = AsmInfo->getPointerSize();
813 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
815 for (const auto sec : Sections) {
817 MCSymbol *StartSymbol = sec.second.first;
818 MCSymbol *EndSymbol = sec.second.second;
819 assert(StartSymbol && "StartSymbol must not be NULL");
820 assert(EndSymbol && "EndSymbol must not be NULL");
822 // Emit a base address selection entry for the start of this section
823 const MCExpr *SectionStartAddr = MCSymbolRefExpr::Create(
824 StartSymbol, MCSymbolRefExpr::VK_None, context);
825 MCOS->EmitFill(AddrSize, 0xFF);
826 MCOS->EmitValue(SectionStartAddr, AddrSize);
828 // Emit a range list entry spanning this section
829 const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
830 *StartSymbol, *EndSymbol, 0);
831 MCOS->EmitIntValue(0, AddrSize);
832 emitAbsValue(*MCOS, SectionSize, AddrSize);
835 // Emit end of list entry
836 MCOS->EmitIntValue(0, AddrSize);
837 MCOS->EmitIntValue(0, AddrSize);
841 // When generating dwarf for assembly source files this emits the Dwarf
844 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
845 MCContext &context = MCOS->getContext();
847 // Create the dwarf sections in this order (.debug_line already created).
848 const MCAsmInfo *AsmInfo = context.getAsmInfo();
849 bool CreateDwarfSectionSymbols =
850 AsmInfo->doesDwarfUseRelocationsAcrossSections();
851 MCSymbol *LineSectionSymbol = nullptr;
852 if (CreateDwarfSectionSymbols)
853 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
854 MCSymbol *AbbrevSectionSymbol = nullptr;
855 MCSymbol *InfoSectionSymbol = nullptr;
856 MCSymbol *RangesSectionSymbol = NULL;
858 // Create end symbols for each section, and remove empty sections
859 MCOS->getContext().finalizeDwarfSections(*MCOS);
861 // If there are no sections to generate debug info for, we don't need
863 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
866 // We only use the .debug_ranges section if we have multiple code sections,
867 // and we are emitting a DWARF version which supports it.
868 const bool UseRangesSection =
869 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
870 MCOS->getContext().getDwarfVersion() >= 3;
871 CreateDwarfSectionSymbols |= UseRangesSection;
873 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
874 if (CreateDwarfSectionSymbols) {
875 InfoSectionSymbol = context.CreateTempSymbol();
876 MCOS->EmitLabel(InfoSectionSymbol);
878 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
879 if (CreateDwarfSectionSymbols) {
880 AbbrevSectionSymbol = context.CreateTempSymbol();
881 MCOS->EmitLabel(AbbrevSectionSymbol);
883 if (UseRangesSection) {
884 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
885 if (CreateDwarfSectionSymbols) {
886 RangesSectionSymbol = context.CreateTempSymbol();
887 MCOS->EmitLabel(RangesSectionSymbol);
891 assert((RangesSectionSymbol != NULL) || !UseRangesSection);
893 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
895 // Output the data for .debug_aranges section.
896 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
898 if (UseRangesSection)
899 EmitGenDwarfRanges(MCOS);
901 // Output the data for .debug_abbrev section.
902 EmitGenDwarfAbbrev(MCOS);
904 // Output the data for .debug_info section.
905 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
906 RangesSectionSymbol);
910 // When generating dwarf for assembly source files this is called when symbol
911 // for a label is created. If this symbol is not a temporary and is in the
912 // section that dwarf is being generated for, save the needed info to create
915 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
916 SourceMgr &SrcMgr, SMLoc &Loc) {
917 // We won't create dwarf labels for temporary symbols.
918 if (Symbol->isTemporary())
920 MCContext &context = MCOS->getContext();
921 // We won't create dwarf labels for symbols in sections that we are not
922 // generating debug info for.
923 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
926 // The dwarf label's name does not have the symbol name's leading
928 StringRef Name = Symbol->getName();
929 if (Name.startswith("_"))
930 Name = Name.substr(1, Name.size()-1);
932 // Get the dwarf file number to be used for the dwarf label.
933 unsigned FileNumber = context.getGenDwarfFileNumber();
935 // Finding the line number is the expensive part which is why we just don't
936 // pass it in as for some symbols we won't create a dwarf label.
937 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
938 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
940 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
941 // values so that they don't have things like an ARM thumb bit from the
942 // original symbol. So when used they won't get a low bit set after
944 MCSymbol *Label = context.CreateTempSymbol();
945 MCOS->EmitLabel(Label);
947 // Create and entry for the info and add it to the other entries.
948 MCOS->getContext().addMCGenDwarfLabelEntry(
949 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
952 static int getDataAlignmentFactor(MCStreamer &streamer) {
953 MCContext &context = streamer.getContext();
954 const MCAsmInfo *asmInfo = context.getAsmInfo();
955 int size = asmInfo->getCalleeSaveStackSlotSize();
956 if (asmInfo->isStackGrowthDirectionUp())
962 static unsigned getSizeForEncoding(MCStreamer &streamer,
963 unsigned symbolEncoding) {
964 MCContext &context = streamer.getContext();
965 unsigned format = symbolEncoding & 0x0f;
967 default: llvm_unreachable("Unknown Encoding");
968 case dwarf::DW_EH_PE_absptr:
969 case dwarf::DW_EH_PE_signed:
970 return context.getAsmInfo()->getPointerSize();
971 case dwarf::DW_EH_PE_udata2:
972 case dwarf::DW_EH_PE_sdata2:
974 case dwarf::DW_EH_PE_udata4:
975 case dwarf::DW_EH_PE_sdata4:
977 case dwarf::DW_EH_PE_udata8:
978 case dwarf::DW_EH_PE_sdata8:
983 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
984 unsigned symbolEncoding, bool isEH) {
985 MCContext &context = streamer.getContext();
986 const MCAsmInfo *asmInfo = context.getAsmInfo();
987 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
990 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
991 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
992 emitAbsValue(streamer, v, size);
994 streamer.EmitValue(v, size);
997 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
998 unsigned symbolEncoding) {
999 MCContext &context = streamer.getContext();
1000 const MCAsmInfo *asmInfo = context.getAsmInfo();
1001 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1004 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1005 streamer.EmitValue(v, size);
1009 class FrameEmitterImpl {
1012 const MCSymbol *SectionStart;
1014 FrameEmitterImpl(bool isEH)
1015 : CFAOffset(0), IsEH(isEH), SectionStart(nullptr) {}
1017 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
1019 /// Emit the unwind information in a compact way.
1020 void EmitCompactUnwind(MCObjectStreamer &streamer,
1021 const MCDwarfFrameInfo &frame);
1023 const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
1024 const MCSymbol *personality,
1025 unsigned personalityEncoding,
1026 const MCSymbol *lsda,
1028 unsigned lsdaEncoding,
1030 MCSymbol *EmitFDE(MCObjectStreamer &streamer,
1031 const MCSymbol &cieStart,
1032 const MCDwarfFrameInfo &frame);
1033 void EmitCFIInstructions(MCObjectStreamer &streamer,
1034 ArrayRef<MCCFIInstruction> Instrs,
1035 MCSymbol *BaseLabel);
1036 void EmitCFIInstruction(MCObjectStreamer &Streamer,
1037 const MCCFIInstruction &Instr);
1040 } // end anonymous namespace
1042 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1043 Streamer.EmitIntValue(Encoding, 1);
1046 void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
1047 const MCCFIInstruction &Instr) {
1048 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1049 auto *MRI = Streamer.getContext().getRegisterInfo();
1051 switch (Instr.getOperation()) {
1052 case MCCFIInstruction::OpRegister: {
1053 unsigned Reg1 = Instr.getRegister();
1054 unsigned Reg2 = Instr.getRegister2();
1056 Reg1 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg1, true), false);
1057 Reg2 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg2, true), false);
1059 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1060 Streamer.EmitULEB128IntValue(Reg1);
1061 Streamer.EmitULEB128IntValue(Reg2);
1064 case MCCFIInstruction::OpWindowSave: {
1065 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1068 case MCCFIInstruction::OpUndefined: {
1069 unsigned Reg = Instr.getRegister();
1070 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1071 Streamer.EmitULEB128IntValue(Reg);
1074 case MCCFIInstruction::OpAdjustCfaOffset:
1075 case MCCFIInstruction::OpDefCfaOffset: {
1076 const bool IsRelative =
1077 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1079 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1082 CFAOffset += Instr.getOffset();
1084 CFAOffset = -Instr.getOffset();
1086 Streamer.EmitULEB128IntValue(CFAOffset);
1090 case MCCFIInstruction::OpDefCfa: {
1091 unsigned Reg = Instr.getRegister();
1093 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1094 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1095 Streamer.EmitULEB128IntValue(Reg);
1096 CFAOffset = -Instr.getOffset();
1097 Streamer.EmitULEB128IntValue(CFAOffset);
1102 case MCCFIInstruction::OpDefCfaRegister: {
1103 unsigned Reg = Instr.getRegister();
1105 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1106 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1107 Streamer.EmitULEB128IntValue(Reg);
1112 case MCCFIInstruction::OpOffset:
1113 case MCCFIInstruction::OpRelOffset: {
1114 const bool IsRelative =
1115 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1117 unsigned Reg = Instr.getRegister();
1119 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1121 int Offset = Instr.getOffset();
1123 Offset -= CFAOffset;
1124 Offset = Offset / dataAlignmentFactor;
1127 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1128 Streamer.EmitULEB128IntValue(Reg);
1129 Streamer.EmitSLEB128IntValue(Offset);
1130 } else if (Reg < 64) {
1131 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1132 Streamer.EmitULEB128IntValue(Offset);
1134 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1135 Streamer.EmitULEB128IntValue(Reg);
1136 Streamer.EmitULEB128IntValue(Offset);
1140 case MCCFIInstruction::OpRememberState:
1141 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1143 case MCCFIInstruction::OpRestoreState:
1144 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1146 case MCCFIInstruction::OpSameValue: {
1147 unsigned Reg = Instr.getRegister();
1148 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1149 Streamer.EmitULEB128IntValue(Reg);
1152 case MCCFIInstruction::OpRestore: {
1153 unsigned Reg = Instr.getRegister();
1155 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1156 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1159 case MCCFIInstruction::OpEscape:
1160 Streamer.EmitBytes(Instr.getValues());
1163 llvm_unreachable("Unhandled case in switch");
1166 /// Emit frame instructions to describe the layout of the frame.
1167 void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
1168 ArrayRef<MCCFIInstruction> Instrs,
1169 MCSymbol *BaseLabel) {
1170 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1171 const MCCFIInstruction &Instr = Instrs[i];
1172 MCSymbol *Label = Instr.getLabel();
1173 // Throw out move if the label is invalid.
1174 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1176 // Advance row if new location.
1177 if (BaseLabel && Label) {
1178 MCSymbol *ThisSym = Label;
1179 if (ThisSym != BaseLabel) {
1180 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1181 BaseLabel = ThisSym;
1185 EmitCFIInstruction(streamer, Instr);
1189 /// Emit the unwind information in a compact way.
1190 void FrameEmitterImpl::EmitCompactUnwind(MCObjectStreamer &Streamer,
1191 const MCDwarfFrameInfo &Frame) {
1192 MCContext &Context = Streamer.getContext();
1193 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1195 // range-start range-length compact-unwind-enc personality-func lsda
1196 // _foo LfooEnd-_foo 0x00000023 0 0
1197 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1199 // .section __LD,__compact_unwind,regular,debug
1201 // # compact unwind for _foo
1203 // .set L1,LfooEnd-_foo
1209 // # compact unwind for _bar
1211 // .set L2,LbarEnd-_bar
1214 // .quad __gxx_personality
1215 // .quad except_tab1
1217 uint32_t Encoding = Frame.CompactUnwindEncoding;
1218 if (!Encoding) return;
1219 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1221 // The encoding needs to know we have an LSDA.
1222 if (!DwarfEHFrameOnly && Frame.Lsda)
1223 Encoding |= 0x40000000;
1226 unsigned FDEEncoding = MOFI->getFDEEncoding();
1227 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1228 Streamer.EmitSymbolValue(Frame.Begin, Size);
1231 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1233 emitAbsValue(Streamer, Range, 4);
1236 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1237 Streamer.EmitIntValue(Encoding, Size);
1239 // Personality Function
1240 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1241 if (!DwarfEHFrameOnly && Frame.Personality)
1242 Streamer.EmitSymbolValue(Frame.Personality, Size);
1244 Streamer.EmitIntValue(0, Size); // No personality fn
1247 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1248 if (!DwarfEHFrameOnly && Frame.Lsda)
1249 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1251 Streamer.EmitIntValue(0, Size); // No LSDA
1254 const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
1255 const MCSymbol *personality,
1256 unsigned personalityEncoding,
1257 const MCSymbol *lsda,
1259 unsigned lsdaEncoding,
1261 MCContext &context = streamer.getContext();
1262 const MCRegisterInfo *MRI = context.getRegisterInfo();
1263 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1265 MCSymbol *sectionStart = context.CreateTempSymbol();
1266 streamer.EmitLabel(sectionStart);
1268 MCSymbol *sectionEnd = context.CreateTempSymbol();
1271 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1273 emitAbsValue(streamer, Length, 4);
1276 unsigned CIE_ID = IsEH ? 0 : -1;
1277 streamer.EmitIntValue(CIE_ID, 4);
1280 // For DWARF2, we use CIE version 1
1281 // For DWARF3+, we use CIE version 3
1282 uint8_t CIEVersion = context.getDwarfVersion() <= 2 ? 1 : 3;
1283 streamer.EmitIntValue(CIEVersion, 1);
1285 // Augmentation String
1286 SmallString<8> Augmentation;
1288 Augmentation += "z";
1290 Augmentation += "P";
1292 Augmentation += "L";
1293 Augmentation += "R";
1295 Augmentation += "S";
1296 streamer.EmitBytes(Augmentation);
1298 streamer.EmitIntValue(0, 1);
1300 // Code Alignment Factor
1301 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1303 // Data Alignment Factor
1304 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1306 // Return Address Register
1307 if (CIEVersion == 1) {
1308 assert(MRI->getRARegister() <= 255 &&
1309 "DWARF 2 encodes return_address_register in one byte");
1310 streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), IsEH), 1);
1312 streamer.EmitULEB128IntValue(
1313 MRI->getDwarfRegNum(MRI->getRARegister(), IsEH));
1316 // Augmentation Data Length (optional)
1318 unsigned augmentationLength = 0;
1321 // Personality Encoding
1322 augmentationLength += 1;
1324 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1327 augmentationLength += 1;
1328 // Encoding of the FDE pointers
1329 augmentationLength += 1;
1331 streamer.EmitULEB128IntValue(augmentationLength);
1333 // Augmentation Data (optional)
1335 // Personality Encoding
1336 emitEncodingByte(streamer, personalityEncoding);
1338 EmitPersonality(streamer, *personality, personalityEncoding);
1342 emitEncodingByte(streamer, lsdaEncoding);
1344 // Encoding of the FDE pointers
1345 emitEncodingByte(streamer, MOFI->getFDEEncoding());
1348 // Initial Instructions
1350 const MCAsmInfo *MAI = context.getAsmInfo();
1352 const std::vector<MCCFIInstruction> &Instructions =
1353 MAI->getInitialFrameState();
1354 EmitCFIInstructions(streamer, Instructions, nullptr);
1358 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1360 streamer.EmitLabel(sectionEnd);
1361 return *sectionStart;
1364 MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
1365 const MCSymbol &cieStart,
1366 const MCDwarfFrameInfo &frame) {
1367 MCContext &context = streamer.getContext();
1368 MCSymbol *fdeStart = context.CreateTempSymbol();
1369 MCSymbol *fdeEnd = context.CreateTempSymbol();
1370 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1373 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1374 emitAbsValue(streamer, Length, 4);
1376 streamer.EmitLabel(fdeStart);
1379 const MCAsmInfo *asmInfo = context.getAsmInfo();
1381 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1383 emitAbsValue(streamer, offset, 4);
1384 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1385 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1387 emitAbsValue(streamer, offset, 4);
1389 streamer.EmitSymbolValue(&cieStart, 4);
1393 unsigned PCEncoding =
1394 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1395 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1396 emitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH);
1399 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1401 emitAbsValue(streamer, Range, PCSize);
1404 // Augmentation Data Length
1405 unsigned augmentationLength = 0;
1408 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1410 streamer.EmitULEB128IntValue(augmentationLength);
1412 // Augmentation Data
1414 emitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true);
1417 // Call Frame Instructions
1418 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1421 streamer.EmitValueToAlignment(PCSize);
1428 static const CIEKey getEmptyKey() {
1429 return CIEKey(nullptr, 0, -1, false, false);
1431 static const CIEKey getTombstoneKey() {
1432 return CIEKey(nullptr, -1, 0, false, false);
1435 CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
1436 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
1437 : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1438 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1439 IsSimple(IsSimple_) {}
1440 const MCSymbol *Personality;
1441 unsigned PersonalityEncoding;
1442 unsigned LsdaEncoding;
1450 struct DenseMapInfo<CIEKey> {
1451 static CIEKey getEmptyKey() {
1452 return CIEKey::getEmptyKey();
1454 static CIEKey getTombstoneKey() {
1455 return CIEKey::getTombstoneKey();
1457 static unsigned getHashValue(const CIEKey &Key) {
1458 return static_cast<unsigned>(hash_combine(Key.Personality,
1459 Key.PersonalityEncoding,
1464 static bool isEqual(const CIEKey &LHS,
1465 const CIEKey &RHS) {
1466 return LHS.Personality == RHS.Personality &&
1467 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1468 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1469 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1470 LHS.IsSimple == RHS.IsSimple;
1475 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1477 Streamer.generateCompactUnwindEncodings(MAB);
1479 MCContext &Context = Streamer.getContext();
1480 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1481 FrameEmitterImpl Emitter(IsEH);
1482 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1484 // Emit the compact unwind info if available.
1485 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1486 if (IsEH && MOFI->getCompactUnwindSection()) {
1487 bool SectionEmitted = false;
1488 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1489 const MCDwarfFrameInfo &Frame = FrameArray[i];
1490 if (Frame.CompactUnwindEncoding == 0) continue;
1491 if (!SectionEmitted) {
1492 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1493 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1494 SectionEmitted = true;
1496 NeedsEHFrameSection |=
1497 Frame.CompactUnwindEncoding ==
1498 MOFI->getCompactUnwindDwarfEHFrameOnly();
1499 Emitter.EmitCompactUnwind(Streamer, Frame);
1503 if (!NeedsEHFrameSection) return;
1505 const MCSection &Section =
1506 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1507 *MOFI->getDwarfFrameSection();
1509 Streamer.SwitchSection(&Section);
1510 MCSymbol *SectionStart = Context.CreateTempSymbol();
1511 Streamer.EmitLabel(SectionStart);
1512 Emitter.setSectionStart(SectionStart);
1514 MCSymbol *FDEEnd = nullptr;
1515 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1517 const MCSymbol *DummyDebugKey = nullptr;
1518 NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1519 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1520 const MCDwarfFrameInfo &Frame = FrameArray[i];
1522 // Emit the label from the previous iteration
1524 Streamer.EmitLabel(FDEEnd);
1528 if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
1529 MOFI->getCompactUnwindDwarfEHFrameOnly())
1530 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1531 // of by the compact unwind encoding.
1534 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1535 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1536 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1538 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1539 Frame.PersonalityEncoding, Frame.Lsda,
1540 Frame.IsSignalFrame,
1544 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1547 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1549 Streamer.EmitLabel(FDEEnd);
1552 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1553 uint64_t AddrDelta) {
1554 MCContext &Context = Streamer.getContext();
1555 SmallString<256> Tmp;
1556 raw_svector_ostream OS(Tmp);
1557 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1558 Streamer.EmitBytes(OS.str());
1561 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1564 // Scale the address delta by the minimum instruction length.
1565 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1567 if (AddrDelta == 0) {
1568 } else if (isUIntN(6, AddrDelta)) {
1569 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1571 } else if (isUInt<8>(AddrDelta)) {
1572 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1573 OS << uint8_t(AddrDelta);
1574 } else if (isUInt<16>(AddrDelta)) {
1575 // FIXME: check what is the correct behavior on a big endian machine.
1576 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1577 OS << uint8_t( AddrDelta & 0xff);
1578 OS << uint8_t((AddrDelta >> 8) & 0xff);
1580 // FIXME: check what is the correct behavior on a big endian machine.
1581 assert(isUInt<32>(AddrDelta));
1582 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1583 OS << uint8_t( AddrDelta & 0xff);
1584 OS << uint8_t((AddrDelta >> 8) & 0xff);
1585 OS << uint8_t((AddrDelta >> 16) & 0xff);
1586 OS << uint8_t((AddrDelta >> 24) & 0xff);