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 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
33 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
34 if (MinInsnLength == 1)
36 if (AddrDelta % MinInsnLength != 0) {
37 // TODO: report this error, but really only once.
40 return AddrDelta / MinInsnLength;
44 // This is called when an instruction is assembled into the specified section
45 // and if there is information from the last .loc directive that has yet to have
46 // a line entry made for it is made.
48 void MCLineEntry::Make(MCObjectStreamer *MCOS, MCSection *Section) {
49 if (!MCOS->getContext().getDwarfLocSeen())
52 // Create a symbol at in the current section for use in the line entry.
53 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
54 // Set the value of the symbol to use for the MCLineEntry.
55 MCOS->EmitLabel(LineSym);
57 // Get the current .loc info saved in the context.
58 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
60 // Create a (local) line entry with the symbol and the current .loc info.
61 MCLineEntry LineEntry(LineSym, DwarfLoc);
63 // clear DwarfLocSeen saying the current .loc info is now used.
64 MCOS->getContext().clearDwarfLocSeen();
66 // Add the line entry to this section's entries.
68 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
70 .addLineEntry(LineEntry, Section);
74 // This helper routine returns an expression of End - Start + IntVal .
76 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
77 const MCSymbol &Start,
80 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
82 MCSymbolRefExpr::create(&End, Variant, MCOS.getContext());
84 MCSymbolRefExpr::create(&Start, Variant, MCOS.getContext());
86 MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
88 MCConstantExpr::create(IntVal, MCOS.getContext());
90 MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
95 // This emits the Dwarf line table for the specified section from the entries
96 // in the LineSection.
99 EmitDwarfLineTable(MCObjectStreamer *MCOS, MCSection *Section,
100 const MCLineSection::MCLineEntryCollection &LineEntries) {
101 unsigned FileNum = 1;
102 unsigned LastLine = 1;
104 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
106 unsigned Discriminator = 0;
107 MCSymbol *LastLabel = nullptr;
109 // Loop through each MCLineEntry and encode the dwarf line number table.
110 for (auto it = LineEntries.begin(),
111 ie = LineEntries.end();
114 if (FileNum != it->getFileNum()) {
115 FileNum = it->getFileNum();
116 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
117 MCOS->EmitULEB128IntValue(FileNum);
119 if (Column != it->getColumn()) {
120 Column = it->getColumn();
121 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
122 MCOS->EmitULEB128IntValue(Column);
124 if (Discriminator != it->getDiscriminator()) {
125 Discriminator = it->getDiscriminator();
126 unsigned Size = getULEB128Size(Discriminator);
127 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
128 MCOS->EmitULEB128IntValue(Size + 1);
129 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
130 MCOS->EmitULEB128IntValue(Discriminator);
132 if (Isa != it->getIsa()) {
134 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
135 MCOS->EmitULEB128IntValue(Isa);
137 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
138 Flags = it->getFlags();
139 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
141 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
142 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
143 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
144 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
145 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
146 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
148 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
149 MCSymbol *Label = it->getLabel();
151 // At this point we want to emit/create the sequence to encode the delta in
152 // line numbers and the increment of the address from the previous Label
153 // and the current Label.
154 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
155 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
156 asmInfo->getPointerSize());
158 LastLine = it->getLine();
162 // Emit a DW_LNE_end_sequence for the end of the section.
163 // Use the section end label to compute the address delta and use INT64_MAX
164 // as the line delta which is the signal that this is actually a
165 // DW_LNE_end_sequence.
166 MCSymbol *SectionEnd = MCOS->endSection(Section);
168 // Switch back the dwarf line section, in case endSection had to switch the
170 MCContext &Ctx = MCOS->getContext();
171 MCOS->SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
173 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
174 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
175 AsmInfo->getPointerSize());
179 // This emits the Dwarf file and the line tables.
181 void MCDwarfLineTable::Emit(MCObjectStreamer *MCOS,
182 MCDwarfLineTableParams Params) {
183 MCContext &context = MCOS->getContext();
185 auto &LineTables = context.getMCDwarfLineTables();
187 // Bail out early so we don't switch to the debug_line section needlessly and
188 // in doing so create an unnecessary (if empty) section.
189 if (LineTables.empty())
192 // Switch to the section where the table will be emitted into.
193 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
195 // Handle the rest of the Compile Units.
196 for (const auto &CUIDTablePair : LineTables)
197 CUIDTablePair.second.EmitCU(MCOS, Params);
200 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS,
201 MCDwarfLineTableParams Params) const {
202 MCOS.EmitLabel(Header.Emit(&MCOS, Params, None).second);
205 std::pair<MCSymbol *, MCSymbol *>
206 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS,
207 MCDwarfLineTableParams Params) const {
208 static const char StandardOpcodeLengths[] = {
209 0, // length of DW_LNS_copy
210 1, // length of DW_LNS_advance_pc
211 1, // length of DW_LNS_advance_line
212 1, // length of DW_LNS_set_file
213 1, // length of DW_LNS_set_column
214 0, // length of DW_LNS_negate_stmt
215 0, // length of DW_LNS_set_basic_block
216 0, // length of DW_LNS_const_add_pc
217 1, // length of DW_LNS_fixed_advance_pc
218 0, // length of DW_LNS_set_prologue_end
219 0, // length of DW_LNS_set_epilogue_begin
222 assert(array_lengthof(StandardOpcodeLengths) >=
223 (Params.DWARF2LineOpcodeBase - 1));
224 return Emit(MCOS, Params, ArrayRef<char>(StandardOpcodeLengths,
225 Params.DWARF2LineOpcodeBase - 1));
228 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
229 MCContext &Context = OS.getContext();
230 assert(!isa<MCSymbolRefExpr>(Expr));
231 if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
234 MCSymbol *ABS = Context.createTempSymbol();
235 OS.EmitAssignment(ABS, Expr);
236 return MCSymbolRefExpr::create(ABS, Context);
239 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
240 const MCExpr *ABS = forceExpAbs(OS, Value);
241 OS.EmitValue(ABS, Size);
244 std::pair<MCSymbol *, MCSymbol *>
245 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
246 ArrayRef<char> StandardOpcodeLengths) const {
248 MCContext &context = MCOS->getContext();
250 // Create a symbol at the beginning of the line table.
251 MCSymbol *LineStartSym = Label;
253 LineStartSym = context.createTempSymbol();
254 // Set the value of the symbol, as we are at the start of the line table.
255 MCOS->EmitLabel(LineStartSym);
257 // Create a symbol for the end of the section (to be set when we get there).
258 MCSymbol *LineEndSym = context.createTempSymbol();
260 // The first 4 bytes is the total length of the information for this
261 // compilation unit (not including these 4 bytes for the length).
263 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym, 4), 4);
265 // Next 2 bytes is the Version, which is Dwarf 2.
266 MCOS->EmitIntValue(2, 2);
268 // Create a symbol for the end of the prologue (to be set when we get there).
269 MCSymbol *ProEndSym = context.createTempSymbol(); // Lprologue_end
271 // Length of the prologue, is the next 4 bytes. Which is the start of the
272 // section to the end of the prologue. Not including the 4 bytes for the
273 // total length, the 2 bytes for the version, and these 4 bytes for the
274 // length of the prologue.
277 MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, (4 + 2 + 4)), 4);
279 // Parameters of the state machine, are next.
280 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
281 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
282 MCOS->EmitIntValue(Params.DWARF2LineBase, 1);
283 MCOS->EmitIntValue(Params.DWARF2LineRange, 1);
284 MCOS->EmitIntValue(StandardOpcodeLengths.size() + 1, 1);
286 // Standard opcode lengths
287 for (char Length : StandardOpcodeLengths)
288 MCOS->EmitIntValue(Length, 1);
290 // Put out the directory and file tables.
292 // First the directory table.
293 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
294 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
295 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
297 MCOS->EmitIntValue(0, 1); // Terminate the directory list
299 // Second the file table.
300 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
301 assert(!MCDwarfFiles[i].Name.empty());
302 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
303 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
305 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
306 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
307 MCOS->EmitIntValue(0, 1); // filesize (always 0)
309 MCOS->EmitIntValue(0, 1); // Terminate the file list
311 // This is the end of the prologue, so set the value of the symbol at the
312 // end of the prologue (that was used in a previous expression).
313 MCOS->EmitLabel(ProEndSym);
315 return std::make_pair(LineStartSym, LineEndSym);
318 void MCDwarfLineTable::EmitCU(MCObjectStreamer *MCOS,
319 MCDwarfLineTableParams Params) const {
320 MCSymbol *LineEndSym = Header.Emit(MCOS, Params).second;
322 // Put out the line tables.
323 for (const auto &LineSec : MCLineSections.getMCLineEntries())
324 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
326 // This is the end of the section, so set the value of the symbol at the end
327 // of this section (that was used in a previous expression).
328 MCOS->EmitLabel(LineEndSym);
331 unsigned MCDwarfLineTable::getFile(StringRef &Directory, StringRef &FileName,
332 unsigned FileNumber) {
333 return Header.getFile(Directory, FileName, FileNumber);
336 unsigned MCDwarfLineTableHeader::getFile(StringRef &Directory,
338 unsigned FileNumber) {
339 if (Directory == CompilationDir)
341 if (FileName.empty()) {
342 FileName = "<stdin>";
345 assert(!FileName.empty());
346 if (FileNumber == 0) {
347 FileNumber = SourceIdMap.size() + 1;
348 assert((MCDwarfFiles.empty() || FileNumber == MCDwarfFiles.size()) &&
349 "Don't mix autonumbered and explicit numbered line table usage");
350 SmallString<256> Buffer;
351 auto IterBool = SourceIdMap.insert(
352 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
354 if (!IterBool.second)
355 return IterBool.first->second;
357 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
358 MCDwarfFiles.resize(FileNumber + 1);
360 // Get the new MCDwarfFile slot for this FileNumber.
361 MCDwarfFile &File = MCDwarfFiles[FileNumber];
363 // It is an error to use see the same number more than once.
364 if (!File.Name.empty())
367 if (Directory.empty()) {
368 // Separate the directory part from the basename of the FileName.
369 StringRef tFileName = sys::path::filename(FileName);
370 if (!tFileName.empty()) {
371 Directory = sys::path::parent_path(FileName);
372 if (!Directory.empty())
373 FileName = tFileName;
377 // Find or make an entry in the MCDwarfDirs vector for this Directory.
378 // Capture directory name.
380 if (Directory.empty()) {
381 // For FileNames with no directories a DirIndex of 0 is used.
385 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
386 if (Directory == MCDwarfDirs[DirIndex])
389 if (DirIndex >= MCDwarfDirs.size())
390 MCDwarfDirs.push_back(Directory);
391 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
392 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
393 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
394 // are stored at MCDwarfFiles[FileNumber].Name .
398 File.Name = FileName;
399 File.DirIndex = DirIndex;
401 // return the allocated FileNumber.
405 /// Utility function to emit the encoding to a streamer.
406 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
407 int64_t LineDelta, uint64_t AddrDelta) {
408 MCContext &Context = MCOS->getContext();
409 SmallString<256> Tmp;
410 raw_svector_ostream OS(Tmp);
411 MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS);
412 MCOS->EmitBytes(OS.str());
415 /// Given a special op, return the address skip amount (in units of
416 /// DWARF2_LINE_MIN_INSN_LENGTH).
417 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
418 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
421 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
422 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params,
423 int64_t LineDelta, uint64_t AddrDelta,
425 uint64_t Temp, Opcode;
426 bool NeedCopy = false;
428 // The maximum address skip amount that can be encoded with a special op.
429 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
431 // Scale the address delta by the minimum instruction length.
432 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
434 // A LineDelta of INT64_MAX is a signal that this is actually a
435 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
436 // end_sequence to emit the matrix entry.
437 if (LineDelta == INT64_MAX) {
438 if (AddrDelta == MaxSpecialAddrDelta)
439 OS << char(dwarf::DW_LNS_const_add_pc);
440 else if (AddrDelta) {
441 OS << char(dwarf::DW_LNS_advance_pc);
442 encodeULEB128(AddrDelta, OS);
444 OS << char(dwarf::DW_LNS_extended_op);
446 OS << char(dwarf::DW_LNE_end_sequence);
450 // Bias the line delta by the base.
451 Temp = LineDelta - Params.DWARF2LineBase;
453 // If the line increment is out of range of a special opcode, we must encode
454 // it with DW_LNS_advance_line.
455 if (Temp >= Params.DWARF2LineRange) {
456 OS << char(dwarf::DW_LNS_advance_line);
457 encodeSLEB128(LineDelta, OS);
460 Temp = 0 - Params.DWARF2LineBase;
464 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
465 if (LineDelta == 0 && AddrDelta == 0) {
466 OS << char(dwarf::DW_LNS_copy);
470 // Bias the opcode by the special opcode base.
471 Temp += Params.DWARF2LineOpcodeBase;
473 // Avoid overflow when addr_delta is large.
474 if (AddrDelta < 256 + MaxSpecialAddrDelta) {
475 // Try using a special opcode.
476 Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
482 // Try using DW_LNS_const_add_pc followed by special op.
483 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
485 OS << char(dwarf::DW_LNS_const_add_pc);
491 // Otherwise use DW_LNS_advance_pc.
492 OS << char(dwarf::DW_LNS_advance_pc);
493 encodeULEB128(AddrDelta, OS);
496 OS << char(dwarf::DW_LNS_copy);
501 // Utility function to write a tuple for .debug_abbrev.
502 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
503 MCOS->EmitULEB128IntValue(Name);
504 MCOS->EmitULEB128IntValue(Form);
507 // When generating dwarf for assembly source files this emits
508 // the data for .debug_abbrev section which contains three DIEs.
509 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
510 MCContext &context = MCOS->getContext();
511 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
513 // DW_TAG_compile_unit DIE abbrev (1).
514 MCOS->EmitULEB128IntValue(1);
515 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
516 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
517 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
518 if (MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
519 MCOS->getContext().getDwarfVersion() >= 3) {
520 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4);
522 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
523 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
525 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
526 if (!context.getCompilationDir().empty())
527 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
528 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
529 if (!DwarfDebugFlags.empty())
530 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
531 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
532 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
533 EmitAbbrev(MCOS, 0, 0);
535 // DW_TAG_label DIE abbrev (2).
536 MCOS->EmitULEB128IntValue(2);
537 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
538 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
539 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
540 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
541 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
542 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
543 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
544 EmitAbbrev(MCOS, 0, 0);
546 // DW_TAG_unspecified_parameters DIE abbrev (3).
547 MCOS->EmitULEB128IntValue(3);
548 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
549 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
550 EmitAbbrev(MCOS, 0, 0);
552 // Terminate the abbreviations for this compilation unit.
553 MCOS->EmitIntValue(0, 1);
556 // When generating dwarf for assembly source files this emits the data for
557 // .debug_aranges section. This section contains a header and a table of pairs
558 // of PointerSize'ed values for the address and size of section(s) with line
560 static void EmitGenDwarfAranges(MCStreamer *MCOS,
561 const MCSymbol *InfoSectionSymbol) {
562 MCContext &context = MCOS->getContext();
564 auto &Sections = context.getGenDwarfSectionSyms();
566 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
568 // This will be the length of the .debug_aranges section, first account for
569 // the size of each item in the header (see below where we emit these items).
570 int Length = 4 + 2 + 4 + 1 + 1;
572 // Figure the padding after the header before the table of address and size
573 // pairs who's values are PointerSize'ed.
574 const MCAsmInfo *asmInfo = context.getAsmInfo();
575 int AddrSize = asmInfo->getPointerSize();
576 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
577 if (Pad == 2 * AddrSize)
581 // Add the size of the pair of PointerSize'ed values for the address and size
582 // of each section we have in the table.
583 Length += 2 * AddrSize * Sections.size();
584 // And the pair of terminating zeros.
585 Length += 2 * AddrSize;
588 // Emit the header for this section.
589 // The 4 byte length not including the 4 byte value for the length.
590 MCOS->EmitIntValue(Length - 4, 4);
591 // The 2 byte version, which is 2.
592 MCOS->EmitIntValue(2, 2);
593 // The 4 byte offset to the compile unit in the .debug_info from the start
594 // of the .debug_info.
595 if (InfoSectionSymbol)
596 MCOS->EmitSymbolValue(InfoSectionSymbol, 4,
597 asmInfo->needsDwarfSectionOffsetDirective());
599 MCOS->EmitIntValue(0, 4);
600 // The 1 byte size of an address.
601 MCOS->EmitIntValue(AddrSize, 1);
602 // The 1 byte size of a segment descriptor, we use a value of zero.
603 MCOS->EmitIntValue(0, 1);
604 // Align the header with the padding if needed, before we put out the table.
605 for(int i = 0; i < Pad; i++)
606 MCOS->EmitIntValue(0, 1);
608 // Now emit the table of pairs of PointerSize'ed values for the section
609 // addresses and sizes.
610 for (MCSection *Sec : Sections) {
611 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
612 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
613 assert(StartSymbol && "StartSymbol must not be NULL");
614 assert(EndSymbol && "EndSymbol must not be NULL");
616 const MCExpr *Addr = MCSymbolRefExpr::create(
617 StartSymbol, MCSymbolRefExpr::VK_None, context);
618 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
619 *StartSymbol, *EndSymbol, 0);
620 MCOS->EmitValue(Addr, AddrSize);
621 emitAbsValue(*MCOS, Size, AddrSize);
624 // And finally the pair of terminating zeros.
625 MCOS->EmitIntValue(0, AddrSize);
626 MCOS->EmitIntValue(0, AddrSize);
629 // When generating dwarf for assembly source files this emits the data for
630 // .debug_info section which contains three parts. The header, the compile_unit
631 // DIE and a list of label DIEs.
632 static void EmitGenDwarfInfo(MCStreamer *MCOS,
633 const MCSymbol *AbbrevSectionSymbol,
634 const MCSymbol *LineSectionSymbol,
635 const MCSymbol *RangesSectionSymbol) {
636 MCContext &context = MCOS->getContext();
638 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
640 // Create a symbol at the start and end of this section used in here for the
641 // expression to calculate the length in the header.
642 MCSymbol *InfoStart = context.createTempSymbol();
643 MCOS->EmitLabel(InfoStart);
644 MCSymbol *InfoEnd = context.createTempSymbol();
646 // First part: the header.
648 // The 4 byte total length of the information for this compilation unit, not
649 // including these 4 bytes.
650 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
651 emitAbsValue(*MCOS, Length, 4);
653 // The 2 byte DWARF version.
654 MCOS->EmitIntValue(context.getDwarfVersion(), 2);
656 const MCAsmInfo &AsmInfo = *context.getAsmInfo();
657 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
658 // it is at the start of that section so this is zero.
659 if (AbbrevSectionSymbol == nullptr)
660 MCOS->EmitIntValue(0, 4);
662 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4,
663 AsmInfo.needsDwarfSectionOffsetDirective());
665 const MCAsmInfo *asmInfo = context.getAsmInfo();
666 int AddrSize = asmInfo->getPointerSize();
667 // The 1 byte size of an address.
668 MCOS->EmitIntValue(AddrSize, 1);
670 // Second part: the compile_unit DIE.
672 // The DW_TAG_compile_unit DIE abbrev (1).
673 MCOS->EmitULEB128IntValue(1);
675 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
676 // which is at the start of that section so this is zero.
677 if (LineSectionSymbol)
678 MCOS->EmitSymbolValue(LineSectionSymbol, 4,
679 AsmInfo.needsDwarfSectionOffsetDirective());
681 MCOS->EmitIntValue(0, 4);
683 if (RangesSectionSymbol) {
684 // There are multiple sections containing code, so we must use the
685 // .debug_ranges sections.
687 // AT_ranges, the 4 byte offset from the start of the .debug_ranges section
688 // to the address range list for this compilation unit.
689 MCOS->EmitSymbolValue(RangesSectionSymbol, 4);
691 // If we only have one non-empty code section, we can use the simpler
692 // AT_low_pc and AT_high_pc attributes.
694 // Find the first (and only) non-empty text section
695 auto &Sections = context.getGenDwarfSectionSyms();
696 const auto TextSection = Sections.begin();
697 assert(TextSection != Sections.end() && "No text section found");
699 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
700 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
701 assert(StartSymbol && "StartSymbol must not be NULL");
702 assert(EndSymbol && "EndSymbol must not be NULL");
704 // AT_low_pc, the first address of the default .text section.
705 const MCExpr *Start = MCSymbolRefExpr::create(
706 StartSymbol, MCSymbolRefExpr::VK_None, context);
707 MCOS->EmitValue(Start, AddrSize);
709 // AT_high_pc, the last address of the default .text section.
710 const MCExpr *End = MCSymbolRefExpr::create(
711 EndSymbol, MCSymbolRefExpr::VK_None, context);
712 MCOS->EmitValue(End, AddrSize);
715 // AT_name, the name of the source file. Reconstruct from the first directory
716 // and file table entries.
717 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
718 if (MCDwarfDirs.size() > 0) {
719 MCOS->EmitBytes(MCDwarfDirs[0]);
720 MCOS->EmitBytes(sys::path::get_separator());
722 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
723 MCOS->getContext().getMCDwarfFiles();
724 MCOS->EmitBytes(MCDwarfFiles[1].Name);
725 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
727 // AT_comp_dir, the working directory the assembly was done in.
728 if (!context.getCompilationDir().empty()) {
729 MCOS->EmitBytes(context.getCompilationDir());
730 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
733 // AT_APPLE_flags, the command line arguments of the assembler tool.
734 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
735 if (!DwarfDebugFlags.empty()){
736 MCOS->EmitBytes(DwarfDebugFlags);
737 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
740 // AT_producer, the version of the assembler tool.
741 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
742 if (!DwarfDebugProducer.empty())
743 MCOS->EmitBytes(DwarfDebugProducer);
745 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
746 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
748 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
749 // draft has no standard code for assembler.
750 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
752 // Third part: the list of label DIEs.
754 // Loop on saved info for dwarf labels and create the DIEs for them.
755 const std::vector<MCGenDwarfLabelEntry> &Entries =
756 MCOS->getContext().getMCGenDwarfLabelEntries();
757 for (const auto &Entry : Entries) {
758 // The DW_TAG_label DIE abbrev (2).
759 MCOS->EmitULEB128IntValue(2);
761 // AT_name, of the label without any leading underbar.
762 MCOS->EmitBytes(Entry.getName());
763 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
765 // AT_decl_file, index into the file table.
766 MCOS->EmitIntValue(Entry.getFileNumber(), 4);
768 // AT_decl_line, source line number.
769 MCOS->EmitIntValue(Entry.getLineNumber(), 4);
771 // AT_low_pc, start address of the label.
772 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
773 MCSymbolRefExpr::VK_None, context);
774 MCOS->EmitValue(AT_low_pc, AddrSize);
776 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
777 MCOS->EmitIntValue(0, 1);
779 // The DW_TAG_unspecified_parameters DIE abbrev (3).
780 MCOS->EmitULEB128IntValue(3);
782 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
783 MCOS->EmitIntValue(0, 1);
786 // Add the NULL DIE terminating the Compile Unit DIE's.
787 MCOS->EmitIntValue(0, 1);
789 // Now set the value of the symbol at the end of the info section.
790 MCOS->EmitLabel(InfoEnd);
793 // When generating dwarf for assembly source files this emits the data for
794 // .debug_ranges section. We only emit one range list, which spans all of the
795 // executable sections of this file.
796 static void EmitGenDwarfRanges(MCStreamer *MCOS) {
797 MCContext &context = MCOS->getContext();
798 auto &Sections = context.getGenDwarfSectionSyms();
800 const MCAsmInfo *AsmInfo = context.getAsmInfo();
801 int AddrSize = AsmInfo->getPointerSize();
803 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
805 for (MCSection *Sec : Sections) {
806 const MCSymbol *StartSymbol = Sec->getBeginSymbol();
807 MCSymbol *EndSymbol = Sec->getEndSymbol(context);
808 assert(StartSymbol && "StartSymbol must not be NULL");
809 assert(EndSymbol && "EndSymbol must not be NULL");
811 // Emit a base address selection entry for the start of this section
812 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
813 StartSymbol, MCSymbolRefExpr::VK_None, context);
814 MCOS->EmitFill(AddrSize, 0xFF);
815 MCOS->EmitValue(SectionStartAddr, AddrSize);
817 // Emit a range list entry spanning this section
818 const MCExpr *SectionSize = MakeStartMinusEndExpr(*MCOS,
819 *StartSymbol, *EndSymbol, 0);
820 MCOS->EmitIntValue(0, AddrSize);
821 emitAbsValue(*MCOS, SectionSize, AddrSize);
824 // Emit end of list entry
825 MCOS->EmitIntValue(0, AddrSize);
826 MCOS->EmitIntValue(0, AddrSize);
830 // When generating dwarf for assembly source files this emits the Dwarf
833 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
834 MCContext &context = MCOS->getContext();
836 // Create the dwarf sections in this order (.debug_line already created).
837 const MCAsmInfo *AsmInfo = context.getAsmInfo();
838 bool CreateDwarfSectionSymbols =
839 AsmInfo->doesDwarfUseRelocationsAcrossSections();
840 MCSymbol *LineSectionSymbol = nullptr;
841 if (CreateDwarfSectionSymbols)
842 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
843 MCSymbol *AbbrevSectionSymbol = nullptr;
844 MCSymbol *InfoSectionSymbol = nullptr;
845 MCSymbol *RangesSectionSymbol = NULL;
847 // Create end symbols for each section, and remove empty sections
848 MCOS->getContext().finalizeDwarfSections(*MCOS);
850 // If there are no sections to generate debug info for, we don't need
852 if (MCOS->getContext().getGenDwarfSectionSyms().empty())
855 // We only use the .debug_ranges section if we have multiple code sections,
856 // and we are emitting a DWARF version which supports it.
857 const bool UseRangesSection =
858 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
859 MCOS->getContext().getDwarfVersion() >= 3;
860 CreateDwarfSectionSymbols |= UseRangesSection;
862 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
863 if (CreateDwarfSectionSymbols) {
864 InfoSectionSymbol = context.createTempSymbol();
865 MCOS->EmitLabel(InfoSectionSymbol);
867 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
868 if (CreateDwarfSectionSymbols) {
869 AbbrevSectionSymbol = context.createTempSymbol();
870 MCOS->EmitLabel(AbbrevSectionSymbol);
872 if (UseRangesSection) {
873 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
874 if (CreateDwarfSectionSymbols) {
875 RangesSectionSymbol = context.createTempSymbol();
876 MCOS->EmitLabel(RangesSectionSymbol);
880 assert((RangesSectionSymbol != NULL) || !UseRangesSection);
882 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
884 // Output the data for .debug_aranges section.
885 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
887 if (UseRangesSection)
888 EmitGenDwarfRanges(MCOS);
890 // Output the data for .debug_abbrev section.
891 EmitGenDwarfAbbrev(MCOS);
893 // Output the data for .debug_info section.
894 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol,
895 RangesSectionSymbol);
899 // When generating dwarf for assembly source files this is called when symbol
900 // for a label is created. If this symbol is not a temporary and is in the
901 // section that dwarf is being generated for, save the needed info to create
904 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
905 SourceMgr &SrcMgr, SMLoc &Loc) {
906 // We won't create dwarf labels for temporary symbols.
907 if (Symbol->isTemporary())
909 MCContext &context = MCOS->getContext();
910 // We won't create dwarf labels for symbols in sections that we are not
911 // generating debug info for.
912 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSection().first))
915 // The dwarf label's name does not have the symbol name's leading
917 StringRef Name = Symbol->getName();
918 if (Name.startswith("_"))
919 Name = Name.substr(1, Name.size()-1);
921 // Get the dwarf file number to be used for the dwarf label.
922 unsigned FileNumber = context.getGenDwarfFileNumber();
924 // Finding the line number is the expensive part which is why we just don't
925 // pass it in as for some symbols we won't create a dwarf label.
926 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
927 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
929 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
930 // values so that they don't have things like an ARM thumb bit from the
931 // original symbol. So when used they won't get a low bit set after
933 MCSymbol *Label = context.createTempSymbol();
934 MCOS->EmitLabel(Label);
936 // Create and entry for the info and add it to the other entries.
937 MCOS->getContext().addMCGenDwarfLabelEntry(
938 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
941 static int getDataAlignmentFactor(MCStreamer &streamer) {
942 MCContext &context = streamer.getContext();
943 const MCAsmInfo *asmInfo = context.getAsmInfo();
944 int size = asmInfo->getCalleeSaveStackSlotSize();
945 if (asmInfo->isStackGrowthDirectionUp())
951 static unsigned getSizeForEncoding(MCStreamer &streamer,
952 unsigned symbolEncoding) {
953 MCContext &context = streamer.getContext();
954 unsigned format = symbolEncoding & 0x0f;
956 default: llvm_unreachable("Unknown Encoding");
957 case dwarf::DW_EH_PE_absptr:
958 case dwarf::DW_EH_PE_signed:
959 return context.getAsmInfo()->getPointerSize();
960 case dwarf::DW_EH_PE_udata2:
961 case dwarf::DW_EH_PE_sdata2:
963 case dwarf::DW_EH_PE_udata4:
964 case dwarf::DW_EH_PE_sdata4:
966 case dwarf::DW_EH_PE_udata8:
967 case dwarf::DW_EH_PE_sdata8:
972 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
973 unsigned symbolEncoding, bool isEH) {
974 MCContext &context = streamer.getContext();
975 const MCAsmInfo *asmInfo = context.getAsmInfo();
976 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
979 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
980 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
981 emitAbsValue(streamer, v, size);
983 streamer.EmitValue(v, size);
986 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
987 unsigned symbolEncoding) {
988 MCContext &context = streamer.getContext();
989 const MCAsmInfo *asmInfo = context.getAsmInfo();
990 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
993 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
994 streamer.EmitValue(v, size);
998 class FrameEmitterImpl {
1000 int InitialCFAOffset;
1002 const MCSymbol *SectionStart;
1004 FrameEmitterImpl(bool isEH)
1005 : CFAOffset(0), InitialCFAOffset(0), IsEH(isEH), SectionStart(nullptr) {
1008 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
1010 /// Emit the unwind information in a compact way.
1011 void EmitCompactUnwind(MCObjectStreamer &streamer,
1012 const MCDwarfFrameInfo &frame);
1014 const MCSymbol &EmitCIE(MCObjectStreamer &streamer,
1015 const MCSymbol *personality,
1016 unsigned personalityEncoding,
1017 const MCSymbol *lsda,
1019 unsigned lsdaEncoding,
1021 MCSymbol *EmitFDE(MCObjectStreamer &streamer,
1022 const MCSymbol &cieStart,
1023 const MCDwarfFrameInfo &frame);
1024 void EmitCFIInstructions(MCObjectStreamer &streamer,
1025 ArrayRef<MCCFIInstruction> Instrs,
1026 MCSymbol *BaseLabel);
1027 void EmitCFIInstruction(MCObjectStreamer &Streamer,
1028 const MCCFIInstruction &Instr);
1031 } // end anonymous namespace
1033 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1034 Streamer.EmitIntValue(Encoding, 1);
1037 void FrameEmitterImpl::EmitCFIInstruction(MCObjectStreamer &Streamer,
1038 const MCCFIInstruction &Instr) {
1039 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1040 auto *MRI = Streamer.getContext().getRegisterInfo();
1042 switch (Instr.getOperation()) {
1043 case MCCFIInstruction::OpRegister: {
1044 unsigned Reg1 = Instr.getRegister();
1045 unsigned Reg2 = Instr.getRegister2();
1047 Reg1 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg1, true), false);
1048 Reg2 = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg2, true), false);
1050 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
1051 Streamer.EmitULEB128IntValue(Reg1);
1052 Streamer.EmitULEB128IntValue(Reg2);
1055 case MCCFIInstruction::OpWindowSave: {
1056 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
1059 case MCCFIInstruction::OpUndefined: {
1060 unsigned Reg = Instr.getRegister();
1061 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1062 Streamer.EmitULEB128IntValue(Reg);
1065 case MCCFIInstruction::OpAdjustCfaOffset:
1066 case MCCFIInstruction::OpDefCfaOffset: {
1067 const bool IsRelative =
1068 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1070 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1073 CFAOffset += Instr.getOffset();
1075 CFAOffset = -Instr.getOffset();
1077 Streamer.EmitULEB128IntValue(CFAOffset);
1081 case MCCFIInstruction::OpDefCfa: {
1082 unsigned Reg = Instr.getRegister();
1084 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1085 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1086 Streamer.EmitULEB128IntValue(Reg);
1087 CFAOffset = -Instr.getOffset();
1088 Streamer.EmitULEB128IntValue(CFAOffset);
1093 case MCCFIInstruction::OpDefCfaRegister: {
1094 unsigned Reg = Instr.getRegister();
1096 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1097 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1098 Streamer.EmitULEB128IntValue(Reg);
1103 case MCCFIInstruction::OpOffset:
1104 case MCCFIInstruction::OpRelOffset: {
1105 const bool IsRelative =
1106 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1108 unsigned Reg = Instr.getRegister();
1110 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1112 int Offset = Instr.getOffset();
1114 Offset -= CFAOffset;
1115 Offset = Offset / dataAlignmentFactor;
1118 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1119 Streamer.EmitULEB128IntValue(Reg);
1120 Streamer.EmitSLEB128IntValue(Offset);
1121 } else if (Reg < 64) {
1122 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1123 Streamer.EmitULEB128IntValue(Offset);
1125 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1126 Streamer.EmitULEB128IntValue(Reg);
1127 Streamer.EmitULEB128IntValue(Offset);
1131 case MCCFIInstruction::OpRememberState:
1132 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1134 case MCCFIInstruction::OpRestoreState:
1135 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1137 case MCCFIInstruction::OpSameValue: {
1138 unsigned Reg = Instr.getRegister();
1139 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1140 Streamer.EmitULEB128IntValue(Reg);
1143 case MCCFIInstruction::OpRestore: {
1144 unsigned Reg = Instr.getRegister();
1146 Reg = MRI->getDwarfRegNum(MRI->getLLVMRegNum(Reg, true), false);
1147 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1150 case MCCFIInstruction::OpEscape:
1151 Streamer.EmitBytes(Instr.getValues());
1154 llvm_unreachable("Unhandled case in switch");
1157 /// Emit frame instructions to describe the layout of the frame.
1158 void FrameEmitterImpl::EmitCFIInstructions(MCObjectStreamer &streamer,
1159 ArrayRef<MCCFIInstruction> Instrs,
1160 MCSymbol *BaseLabel) {
1161 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1162 const MCCFIInstruction &Instr = Instrs[i];
1163 MCSymbol *Label = Instr.getLabel();
1164 // Throw out move if the label is invalid.
1165 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1167 // Advance row if new location.
1168 if (BaseLabel && Label) {
1169 MCSymbol *ThisSym = Label;
1170 if (ThisSym != BaseLabel) {
1171 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1172 BaseLabel = ThisSym;
1176 EmitCFIInstruction(streamer, Instr);
1180 /// Emit the unwind information in a compact way.
1181 void FrameEmitterImpl::EmitCompactUnwind(MCObjectStreamer &Streamer,
1182 const MCDwarfFrameInfo &Frame) {
1183 MCContext &Context = Streamer.getContext();
1184 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1186 // range-start range-length compact-unwind-enc personality-func lsda
1187 // _foo LfooEnd-_foo 0x00000023 0 0
1188 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1190 // .section __LD,__compact_unwind,regular,debug
1192 // # compact unwind for _foo
1194 // .set L1,LfooEnd-_foo
1200 // # compact unwind for _bar
1202 // .set L2,LbarEnd-_bar
1205 // .quad __gxx_personality
1206 // .quad except_tab1
1208 uint32_t Encoding = Frame.CompactUnwindEncoding;
1209 if (!Encoding) return;
1210 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1212 // The encoding needs to know we have an LSDA.
1213 if (!DwarfEHFrameOnly && Frame.Lsda)
1214 Encoding |= 0x40000000;
1217 unsigned FDEEncoding = MOFI->getFDEEncoding();
1218 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1219 Streamer.EmitSymbolValue(Frame.Begin, Size);
1222 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1224 emitAbsValue(Streamer, Range, 4);
1227 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1228 Streamer.EmitIntValue(Encoding, Size);
1230 // Personality Function
1231 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1232 if (!DwarfEHFrameOnly && Frame.Personality)
1233 Streamer.EmitSymbolValue(Frame.Personality, Size);
1235 Streamer.EmitIntValue(0, Size); // No personality fn
1238 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1239 if (!DwarfEHFrameOnly && Frame.Lsda)
1240 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1242 Streamer.EmitIntValue(0, Size); // No LSDA
1245 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1248 switch (DwarfVersion) {
1256 llvm_unreachable("Unknown version");
1259 const MCSymbol &FrameEmitterImpl::EmitCIE(MCObjectStreamer &streamer,
1260 const MCSymbol *personality,
1261 unsigned personalityEncoding,
1262 const MCSymbol *lsda,
1264 unsigned lsdaEncoding,
1266 MCContext &context = streamer.getContext();
1267 const MCRegisterInfo *MRI = context.getRegisterInfo();
1268 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1270 MCSymbol *sectionStart = context.createTempSymbol();
1271 streamer.EmitLabel(sectionStart);
1273 MCSymbol *sectionEnd = context.createTempSymbol();
1276 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1278 emitAbsValue(streamer, Length, 4);
1281 unsigned CIE_ID = IsEH ? 0 : -1;
1282 streamer.EmitIntValue(CIE_ID, 4);
1285 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1286 streamer.EmitIntValue(CIEVersion, 1);
1288 // Augmentation String
1289 SmallString<8> Augmentation;
1291 Augmentation += "z";
1293 Augmentation += "P";
1295 Augmentation += "L";
1296 Augmentation += "R";
1298 Augmentation += "S";
1299 streamer.EmitBytes(Augmentation);
1301 streamer.EmitIntValue(0, 1);
1303 if (CIEVersion >= 4) {
1305 streamer.EmitIntValue(context.getAsmInfo()->getPointerSize(), 1);
1307 // Segment Descriptor Size
1308 streamer.EmitIntValue(0, 1);
1311 // Code Alignment Factor
1312 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1314 // Data Alignment Factor
1315 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1317 // Return Address Register
1318 if (CIEVersion == 1) {
1319 assert(MRI->getRARegister() <= 255 &&
1320 "DWARF 2 encodes return_address_register in one byte");
1321 streamer.EmitIntValue(MRI->getDwarfRegNum(MRI->getRARegister(), IsEH), 1);
1323 streamer.EmitULEB128IntValue(
1324 MRI->getDwarfRegNum(MRI->getRARegister(), IsEH));
1327 // Augmentation Data Length (optional)
1329 unsigned augmentationLength = 0;
1332 // Personality Encoding
1333 augmentationLength += 1;
1335 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1338 augmentationLength += 1;
1339 // Encoding of the FDE pointers
1340 augmentationLength += 1;
1342 streamer.EmitULEB128IntValue(augmentationLength);
1344 // Augmentation Data (optional)
1346 // Personality Encoding
1347 emitEncodingByte(streamer, personalityEncoding);
1349 EmitPersonality(streamer, *personality, personalityEncoding);
1353 emitEncodingByte(streamer, lsdaEncoding);
1355 // Encoding of the FDE pointers
1356 emitEncodingByte(streamer, MOFI->getFDEEncoding());
1359 // Initial Instructions
1361 const MCAsmInfo *MAI = context.getAsmInfo();
1363 const std::vector<MCCFIInstruction> &Instructions =
1364 MAI->getInitialFrameState();
1365 EmitCFIInstructions(streamer, Instructions, nullptr);
1368 InitialCFAOffset = CFAOffset;
1371 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1373 streamer.EmitLabel(sectionEnd);
1374 return *sectionStart;
1377 MCSymbol *FrameEmitterImpl::EmitFDE(MCObjectStreamer &streamer,
1378 const MCSymbol &cieStart,
1379 const MCDwarfFrameInfo &frame) {
1380 MCContext &context = streamer.getContext();
1381 MCSymbol *fdeStart = context.createTempSymbol();
1382 MCSymbol *fdeEnd = context.createTempSymbol();
1383 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1385 CFAOffset = InitialCFAOffset;
1388 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1389 emitAbsValue(streamer, Length, 4);
1391 streamer.EmitLabel(fdeStart);
1394 const MCAsmInfo *asmInfo = context.getAsmInfo();
1396 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1398 emitAbsValue(streamer, offset, 4);
1399 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1400 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1402 emitAbsValue(streamer, offset, 4);
1404 streamer.EmitSymbolValue(&cieStart, 4);
1408 unsigned PCEncoding =
1409 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1410 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1411 emitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH);
1414 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1416 emitAbsValue(streamer, Range, PCSize);
1419 // Augmentation Data Length
1420 unsigned augmentationLength = 0;
1423 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1425 streamer.EmitULEB128IntValue(augmentationLength);
1427 // Augmentation Data
1429 emitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true);
1432 // Call Frame Instructions
1433 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1436 streamer.EmitValueToAlignment(PCSize);
1443 static const CIEKey getEmptyKey() {
1444 return CIEKey(nullptr, 0, -1, false, false);
1446 static const CIEKey getTombstoneKey() {
1447 return CIEKey(nullptr, -1, 0, false, false);
1450 CIEKey(const MCSymbol *Personality_, unsigned PersonalityEncoding_,
1451 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_)
1452 : Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1453 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1454 IsSimple(IsSimple_) {}
1455 const MCSymbol *Personality;
1456 unsigned PersonalityEncoding;
1457 unsigned LsdaEncoding;
1465 struct DenseMapInfo<CIEKey> {
1466 static CIEKey getEmptyKey() {
1467 return CIEKey::getEmptyKey();
1469 static CIEKey getTombstoneKey() {
1470 return CIEKey::getTombstoneKey();
1472 static unsigned getHashValue(const CIEKey &Key) {
1473 return static_cast<unsigned>(hash_combine(Key.Personality,
1474 Key.PersonalityEncoding,
1479 static bool isEqual(const CIEKey &LHS,
1480 const CIEKey &RHS) {
1481 return LHS.Personality == RHS.Personality &&
1482 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1483 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1484 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1485 LHS.IsSimple == RHS.IsSimple;
1490 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1492 Streamer.generateCompactUnwindEncodings(MAB);
1494 MCContext &Context = Streamer.getContext();
1495 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1496 FrameEmitterImpl Emitter(IsEH);
1497 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1499 // Emit the compact unwind info if available.
1500 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1501 if (IsEH && MOFI->getCompactUnwindSection()) {
1502 bool SectionEmitted = false;
1503 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1504 const MCDwarfFrameInfo &Frame = FrameArray[i];
1505 if (Frame.CompactUnwindEncoding == 0) continue;
1506 if (!SectionEmitted) {
1507 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1508 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1509 SectionEmitted = true;
1511 NeedsEHFrameSection |=
1512 Frame.CompactUnwindEncoding ==
1513 MOFI->getCompactUnwindDwarfEHFrameOnly();
1514 Emitter.EmitCompactUnwind(Streamer, Frame);
1518 if (!NeedsEHFrameSection) return;
1520 MCSection &Section =
1521 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1522 : *MOFI->getDwarfFrameSection();
1524 Streamer.SwitchSection(&Section);
1525 MCSymbol *SectionStart = Context.createTempSymbol();
1526 Streamer.EmitLabel(SectionStart);
1527 Emitter.setSectionStart(SectionStart);
1529 MCSymbol *FDEEnd = nullptr;
1530 DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1532 const MCSymbol *DummyDebugKey = nullptr;
1533 NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1534 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1535 const MCDwarfFrameInfo &Frame = FrameArray[i];
1537 // Emit the label from the previous iteration
1539 Streamer.EmitLabel(FDEEnd);
1543 if (!NeedsEHFrameSection && Frame.CompactUnwindEncoding !=
1544 MOFI->getCompactUnwindDwarfEHFrameOnly())
1545 // Don't generate an EH frame if we don't need one. I.e., it's taken care
1546 // of by the compact unwind encoding.
1549 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1550 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1551 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1553 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1554 Frame.PersonalityEncoding, Frame.Lsda,
1555 Frame.IsSignalFrame,
1559 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1562 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1564 Streamer.EmitLabel(FDEEnd);
1567 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1568 uint64_t AddrDelta) {
1569 MCContext &Context = Streamer.getContext();
1570 SmallString<256> Tmp;
1571 raw_svector_ostream OS(Tmp);
1572 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1573 Streamer.EmitBytes(OS.str());
1576 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1579 // Scale the address delta by the minimum instruction length.
1580 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1582 if (AddrDelta == 0) {
1583 } else if (isUIntN(6, AddrDelta)) {
1584 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1586 } else if (isUInt<8>(AddrDelta)) {
1587 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1588 OS << uint8_t(AddrDelta);
1589 } else if (isUInt<16>(AddrDelta)) {
1590 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1591 if (Context.getAsmInfo()->isLittleEndian())
1592 support::endian::Writer<support::little>(OS).write<uint16_t>(AddrDelta);
1594 support::endian::Writer<support::big>(OS).write<uint16_t>(AddrDelta);
1596 assert(isUInt<32>(AddrDelta));
1597 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1598 if (Context.getAsmInfo()->isLittleEndian())
1599 support::endian::Writer<support::little>(OS).write<uint32_t>(AddrDelta);
1601 support::endian::Writer<support::big>(OS).write<uint32_t>(AddrDelta);