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/SmallString.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/Config/config.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectFileInfo.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
30 // Given a special op, return the address skip amount (in units of
31 // DWARF2_LINE_MIN_INSN_LENGTH.
32 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
34 // The maximum address skip amount that can be encoded with a special op.
35 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
37 // First special line opcode - leave room for the standard opcodes.
38 // Note: If you want to change this, you'll have to update the
39 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
40 #define DWARF2_LINE_OPCODE_BASE 13
42 // Minimum line offset in a special line info. opcode. This value
43 // was chosen to give a reasonable range of values.
44 #define DWARF2_LINE_BASE -5
46 // Range of line offsets in a special line info. opcode.
47 #define DWARF2_LINE_RANGE 14
49 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
50 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
51 if (MinInsnLength == 1)
53 if (AddrDelta % MinInsnLength != 0) {
54 // TODO: report this error, but really only once.
57 return AddrDelta / MinInsnLength;
61 // This is called when an instruction is assembled into the specified section
62 // and if there is information from the last .loc directive that has yet to have
63 // a line entry made for it is made.
65 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
66 if (!MCOS->getContext().getDwarfLocSeen())
69 // Create a symbol at in the current section for use in the line entry.
70 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
71 // Set the value of the symbol to use for the MCLineEntry.
72 MCOS->EmitLabel(LineSym);
74 // Get the current .loc info saved in the context.
75 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
77 // Create a (local) line entry with the symbol and the current .loc info.
78 MCLineEntry LineEntry(LineSym, DwarfLoc);
80 // clear DwarfLocSeen saying the current .loc info is now used.
81 MCOS->getContext().ClearDwarfLocSeen();
83 // Add the line entry to this section's entries.
85 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
87 .addLineEntry(LineEntry, Section);
91 // This helper routine returns an expression of End - Start + IntVal .
93 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
94 const MCSymbol &Start,
97 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
99 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
101 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
103 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
105 MCConstantExpr::Create(IntVal, MCOS.getContext());
107 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
112 // This emits the Dwarf line table for the specified section from the entries
113 // in the LineSection.
116 EmitDwarfLineTable(MCStreamer *MCOS, const MCSection *Section,
117 const MCLineSection::MCLineEntryCollection &LineEntries) {
118 unsigned FileNum = 1;
119 unsigned LastLine = 1;
121 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
123 unsigned Discriminator = 0;
124 MCSymbol *LastLabel = NULL;
126 // Loop through each MCLineEntry and encode the dwarf line number table.
127 for (auto it = LineEntries.begin(),
128 ie = LineEntries.end();
131 if (FileNum != it->getFileNum()) {
132 FileNum = it->getFileNum();
133 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
134 MCOS->EmitULEB128IntValue(FileNum);
136 if (Column != it->getColumn()) {
137 Column = it->getColumn();
138 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
139 MCOS->EmitULEB128IntValue(Column);
141 if (Discriminator != it->getDiscriminator()) {
142 Discriminator = it->getDiscriminator();
143 unsigned Size = getULEB128Size(Discriminator);
144 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
145 MCOS->EmitULEB128IntValue(Size + 1);
146 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
147 MCOS->EmitULEB128IntValue(Discriminator);
149 if (Isa != it->getIsa()) {
151 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
152 MCOS->EmitULEB128IntValue(Isa);
154 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
155 Flags = it->getFlags();
156 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
158 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
159 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
160 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
161 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
162 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
163 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
165 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
166 MCSymbol *Label = it->getLabel();
168 // At this point we want to emit/create the sequence to encode the delta in
169 // line numbers and the increment of the address from the previous Label
170 // and the current Label.
171 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
172 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
173 asmInfo->getPointerSize());
175 LastLine = it->getLine();
179 // Emit a DW_LNE_end_sequence for the end of the section.
180 // Using the pointer Section create a temporary label at the end of the
181 // section and use that and the LastLabel to compute the address delta
182 // and use INT64_MAX as the line delta which is the signal that this is
183 // actually a DW_LNE_end_sequence.
185 // Switch to the section to be able to create a symbol at its end.
186 // TODO: keep track of the last subsection so that this symbol appears in the
188 MCOS->SwitchSection(Section);
190 MCContext &context = MCOS->getContext();
191 // Create a symbol at the end of the section.
192 MCSymbol *SectionEnd = context.CreateTempSymbol();
193 // Set the value of the symbol, as we are at the end of the section.
194 MCOS->EmitLabel(SectionEnd);
196 // Switch back the dwarf line section.
197 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
199 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
200 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
201 asmInfo->getPointerSize());
205 // This emits the Dwarf file and the line tables.
207 const MCSymbol *MCDwarfLineTable::Emit(MCStreamer *MCOS) {
208 MCContext &context = MCOS->getContext();
210 // CUID and MCLineTableSymbols are set in DwarfDebug, when DwarfDebug does
211 // not exist, CUID will be 0 and MCLineTableSymbols will be empty.
212 // Handle Compile Unit 0, the line table start symbol is the section symbol.
213 auto I = MCOS->getContext().getMCDwarfLineTables().begin(),
214 E = MCOS->getContext().getMCDwarfLineTables().end();
216 // Switch to the section where the table will be emitted into.
217 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
219 const MCSymbol *LineStartSym = I->second.EmitCU(MCOS);
220 // Handle the rest of the Compile Units.
221 for (++I; I != E; ++I)
222 I->second.EmitCU(MCOS);
227 std::pair<MCSymbol *, MCSymbol *> MCDwarfLineTableHeader::Emit(MCStreamer *MCOS) const {
228 MCContext &context = MCOS->getContext();
230 // Create a symbol at the beginning of the line table.
231 MCSymbol *LineStartSym = Label;
233 LineStartSym = context.CreateTempSymbol();
234 // Set the value of the symbol, as we are at the start of the line table.
235 MCOS->EmitLabel(LineStartSym);
237 // Create a symbol for the end of the section (to be set when we get there).
238 MCSymbol *LineEndSym = context.CreateTempSymbol();
240 // The first 4 bytes is the total length of the information for this
241 // compilation unit (not including these 4 bytes for the length).
242 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
245 // Next 2 bytes is the Version, which is Dwarf 2.
246 MCOS->EmitIntValue(2, 2);
248 // Create a symbol for the end of the prologue (to be set when we get there).
249 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
251 // Length of the prologue, is the next 4 bytes. Which is the start of the
252 // section to the end of the prologue. Not including the 4 bytes for the
253 // total length, the 2 bytes for the version, and these 4 bytes for the
254 // length of the prologue.
255 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
258 // Parameters of the state machine, are next.
259 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
260 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
261 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
262 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
263 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
265 // Standard opcode lengths
266 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
267 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
268 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
269 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
270 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
271 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
272 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
273 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
274 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
275 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
276 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
277 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
279 // Put out the directory and file tables.
281 // First the directory table.
282 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
283 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
284 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
286 MCOS->EmitIntValue(0, 1); // Terminate the directory list
288 // Second the file table.
289 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
290 MCOS->EmitBytes(MCDwarfFiles[i].Name); // FileName
291 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
293 MCOS->EmitULEB128IntValue(MCDwarfFiles[i].DirIndex);
294 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
295 MCOS->EmitIntValue(0, 1); // filesize (always 0)
297 MCOS->EmitIntValue(0, 1); // Terminate the file list
299 // This is the end of the prologue, so set the value of the symbol at the
300 // end of the prologue (that was used in a previous expression).
301 MCOS->EmitLabel(ProEndSym);
303 return std::make_pair(LineStartSym, LineEndSym);
306 const MCSymbol *MCDwarfLineTable::EmitCU(MCStreamer *MCOS) const {
307 MCSymbol *LineStartSym;
308 MCSymbol *LineEndSym;
309 std::tie(LineStartSym, LineEndSym) = Header.Emit(MCOS);
311 // Put out the line tables.
312 for (const auto &LineSec : MCLineSections.getMCLineEntries())
313 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
315 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
316 MCLineSections.getMCLineEntries().empty()) {
317 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
319 // total_length >= prologue_length + 10
320 // We are 4 bytes short, since we have total_length = 51 and
321 // prologue_length = 45
323 // The regular end_sequence should be sufficient.
324 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
327 // This is the end of the section, so set the value of the symbol at the end
328 // of this section (that was used in a previous expression).
329 MCOS->EmitLabel(LineEndSym);
334 unsigned MCDwarfLineTable::getFile(StringRef Directory, StringRef FileName,
335 unsigned FileNumber) {
336 return Header.getFile(Directory, FileName, FileNumber);
339 unsigned MCDwarfLineTableHeader::getFile(StringRef Directory, StringRef FileName, unsigned FileNumber) {
340 // Make space for this FileNumber in the MCDwarfFiles vector if needed.
341 MCDwarfFiles.resize(FileNumber + 1);
343 // Get the new MCDwarfFile slot for this FileNumber.
344 MCDwarfFile &File = MCDwarfFiles[FileNumber];
346 // It is an error to use see the same number more than once.
347 if (!File.Name.empty())
350 if (Directory.empty()) {
351 // Separate the directory part from the basename of the FileName.
352 StringRef tFileName = sys::path::filename(FileName);
353 if (!tFileName.empty()) {
354 Directory = sys::path::parent_path(FileName);
355 if (!Directory.empty())
356 FileName = tFileName;
360 // Find or make an entry in the MCDwarfDirs vector for this Directory.
361 // Capture directory name.
363 if (Directory.empty()) {
364 // For FileNames with no directories a DirIndex of 0 is used.
368 for (unsigned End = MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
369 if (Directory == MCDwarfDirs[DirIndex])
372 if (DirIndex >= MCDwarfDirs.size())
373 MCDwarfDirs.push_back(Directory);
374 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
375 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
376 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
377 // are stored at MCDwarfFiles[FileNumber].Name .
381 File.Name = FileName;
382 File.DirIndex = DirIndex;
384 // return the allocated FileNumber.
388 /// Utility function to emit the encoding to a streamer.
389 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
390 uint64_t AddrDelta) {
391 MCContext &Context = MCOS->getContext();
392 SmallString<256> Tmp;
393 raw_svector_ostream OS(Tmp);
394 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
395 MCOS->EmitBytes(OS.str());
398 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
399 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
400 uint64_t AddrDelta, raw_ostream &OS) {
401 uint64_t Temp, Opcode;
402 bool NeedCopy = false;
404 // Scale the address delta by the minimum instruction length.
405 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
407 // A LineDelta of INT64_MAX is a signal that this is actually a
408 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
409 // end_sequence to emit the matrix entry.
410 if (LineDelta == INT64_MAX) {
411 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
412 OS << char(dwarf::DW_LNS_const_add_pc);
414 OS << char(dwarf::DW_LNS_advance_pc);
415 encodeULEB128(AddrDelta, OS);
417 OS << char(dwarf::DW_LNS_extended_op);
419 OS << char(dwarf::DW_LNE_end_sequence);
423 // Bias the line delta by the base.
424 Temp = LineDelta - DWARF2_LINE_BASE;
426 // If the line increment is out of range of a special opcode, we must encode
427 // it with DW_LNS_advance_line.
428 if (Temp >= DWARF2_LINE_RANGE) {
429 OS << char(dwarf::DW_LNS_advance_line);
430 encodeSLEB128(LineDelta, OS);
433 Temp = 0 - DWARF2_LINE_BASE;
437 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
438 if (LineDelta == 0 && AddrDelta == 0) {
439 OS << char(dwarf::DW_LNS_copy);
443 // Bias the opcode by the special opcode base.
444 Temp += DWARF2_LINE_OPCODE_BASE;
446 // Avoid overflow when addr_delta is large.
447 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
448 // Try using a special opcode.
449 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
455 // Try using DW_LNS_const_add_pc followed by special op.
456 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
458 OS << char(dwarf::DW_LNS_const_add_pc);
464 // Otherwise use DW_LNS_advance_pc.
465 OS << char(dwarf::DW_LNS_advance_pc);
466 encodeULEB128(AddrDelta, OS);
469 OS << char(dwarf::DW_LNS_copy);
474 // Utility function to write a tuple for .debug_abbrev.
475 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
476 MCOS->EmitULEB128IntValue(Name);
477 MCOS->EmitULEB128IntValue(Form);
480 // When generating dwarf for assembly source files this emits
481 // the data for .debug_abbrev section which contains three DIEs.
482 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
483 MCContext &context = MCOS->getContext();
484 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
486 // DW_TAG_compile_unit DIE abbrev (1).
487 MCOS->EmitULEB128IntValue(1);
488 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
489 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
490 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
491 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
492 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
493 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
494 if (!context.getCompilationDir().empty())
495 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
496 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
497 if (!DwarfDebugFlags.empty())
498 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
499 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
500 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
501 EmitAbbrev(MCOS, 0, 0);
503 // DW_TAG_label DIE abbrev (2).
504 MCOS->EmitULEB128IntValue(2);
505 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
506 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
507 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
508 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
509 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
510 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
511 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
512 EmitAbbrev(MCOS, 0, 0);
514 // DW_TAG_unspecified_parameters DIE abbrev (3).
515 MCOS->EmitULEB128IntValue(3);
516 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
517 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
518 EmitAbbrev(MCOS, 0, 0);
520 // Terminate the abbreviations for this compilation unit.
521 MCOS->EmitIntValue(0, 1);
524 // When generating dwarf for assembly source files this emits the data for
525 // .debug_aranges section. Which contains a header and a table of pairs of
526 // PointerSize'ed values for the address and size of section(s) with line table
527 // entries (just the default .text in our case) and a terminating pair of zeros.
528 static void EmitGenDwarfAranges(MCStreamer *MCOS,
529 const MCSymbol *InfoSectionSymbol) {
530 MCContext &context = MCOS->getContext();
532 // Create a symbol at the end of the section that we are creating the dwarf
533 // debugging info to use later in here as part of the expression to calculate
534 // the size of the section for the table.
535 MCOS->SwitchSection(context.getGenDwarfSection());
536 MCSymbol *SectionEndSym = context.CreateTempSymbol();
537 MCOS->EmitLabel(SectionEndSym);
538 context.setGenDwarfSectionEndSym(SectionEndSym);
540 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
542 // This will be the length of the .debug_aranges section, first account for
543 // the size of each item in the header (see below where we emit these items).
544 int Length = 4 + 2 + 4 + 1 + 1;
546 // Figure the padding after the header before the table of address and size
547 // pairs who's values are PointerSize'ed.
548 const MCAsmInfo *asmInfo = context.getAsmInfo();
549 int AddrSize = asmInfo->getPointerSize();
550 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
551 if (Pad == 2 * AddrSize)
555 // Add the size of the pair of PointerSize'ed values for the address and size
556 // of the one default .text section we have in the table.
557 Length += 2 * AddrSize;
558 // And the pair of terminating zeros.
559 Length += 2 * AddrSize;
562 // Emit the header for this section.
563 // The 4 byte length not including the 4 byte value for the length.
564 MCOS->EmitIntValue(Length - 4, 4);
565 // The 2 byte version, which is 2.
566 MCOS->EmitIntValue(2, 2);
567 // The 4 byte offset to the compile unit in the .debug_info from the start
568 // of the .debug_info.
569 if (InfoSectionSymbol)
570 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
572 MCOS->EmitIntValue(0, 4);
573 // The 1 byte size of an address.
574 MCOS->EmitIntValue(AddrSize, 1);
575 // The 1 byte size of a segment descriptor, we use a value of zero.
576 MCOS->EmitIntValue(0, 1);
577 // Align the header with the padding if needed, before we put out the table.
578 for(int i = 0; i < Pad; i++)
579 MCOS->EmitIntValue(0, 1);
581 // Now emit the table of pairs of PointerSize'ed values for the section(s)
582 // address and size, in our case just the one default .text section.
583 const MCExpr *Addr = MCSymbolRefExpr::Create(
584 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
585 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
586 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
587 MCOS->EmitAbsValue(Addr, AddrSize);
588 MCOS->EmitAbsValue(Size, AddrSize);
590 // And finally the pair of terminating zeros.
591 MCOS->EmitIntValue(0, AddrSize);
592 MCOS->EmitIntValue(0, AddrSize);
595 // When generating dwarf for assembly source files this emits the data for
596 // .debug_info section which contains three parts. The header, the compile_unit
597 // DIE and a list of label DIEs.
598 static void EmitGenDwarfInfo(MCStreamer *MCOS,
599 const MCSymbol *AbbrevSectionSymbol,
600 const MCSymbol *LineSectionSymbol) {
601 MCContext &context = MCOS->getContext();
603 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
605 // Create a symbol at the start and end of this section used in here for the
606 // expression to calculate the length in the header.
607 MCSymbol *InfoStart = context.CreateTempSymbol();
608 MCOS->EmitLabel(InfoStart);
609 MCSymbol *InfoEnd = context.CreateTempSymbol();
611 // First part: the header.
613 // The 4 byte total length of the information for this compilation unit, not
614 // including these 4 bytes.
615 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
616 MCOS->EmitAbsValue(Length, 4);
618 // The 2 byte DWARF version, which is 2.
619 MCOS->EmitIntValue(2, 2);
621 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
622 // it is at the start of that section so this is zero.
623 if (AbbrevSectionSymbol) {
624 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
626 MCOS->EmitIntValue(0, 4);
629 const MCAsmInfo *asmInfo = context.getAsmInfo();
630 int AddrSize = asmInfo->getPointerSize();
631 // The 1 byte size of an address.
632 MCOS->EmitIntValue(AddrSize, 1);
634 // Second part: the compile_unit DIE.
636 // The DW_TAG_compile_unit DIE abbrev (1).
637 MCOS->EmitULEB128IntValue(1);
639 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
640 // which is at the start of that section so this is zero.
641 if (LineSectionSymbol) {
642 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
644 MCOS->EmitIntValue(0, 4);
647 // AT_low_pc, the first address of the default .text section.
648 const MCExpr *Start = MCSymbolRefExpr::Create(
649 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
650 MCOS->EmitAbsValue(Start, AddrSize);
652 // AT_high_pc, the last address of the default .text section.
653 const MCExpr *End = MCSymbolRefExpr::Create(
654 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
655 MCOS->EmitAbsValue(End, AddrSize);
657 // AT_name, the name of the source file. Reconstruct from the first directory
658 // and file table entries.
659 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
660 if (MCDwarfDirs.size() > 0) {
661 MCOS->EmitBytes(MCDwarfDirs[0]);
662 MCOS->EmitBytes("/");
664 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles =
665 MCOS->getContext().getMCDwarfFiles();
666 MCOS->EmitBytes(MCDwarfFiles[1].Name);
667 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
669 // AT_comp_dir, the working directory the assembly was done in.
670 if (!context.getCompilationDir().empty()) {
671 MCOS->EmitBytes(context.getCompilationDir());
672 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
675 // AT_APPLE_flags, the command line arguments of the assembler tool.
676 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
677 if (!DwarfDebugFlags.empty()){
678 MCOS->EmitBytes(DwarfDebugFlags);
679 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
682 // AT_producer, the version of the assembler tool.
683 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
684 if (!DwarfDebugProducer.empty()){
685 MCOS->EmitBytes(DwarfDebugProducer);
688 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
689 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
690 MCOS->EmitBytes(StringRef(")"));
692 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
694 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
695 // draft has no standard code for assembler.
696 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
698 // Third part: the list of label DIEs.
700 // Loop on saved info for dwarf labels and create the DIEs for them.
701 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
702 MCOS->getContext().getMCGenDwarfLabelEntries();
703 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
704 Entries.begin(), ie = Entries.end(); it != ie;
706 const MCGenDwarfLabelEntry *Entry = *it;
708 // The DW_TAG_label DIE abbrev (2).
709 MCOS->EmitULEB128IntValue(2);
711 // AT_name, of the label without any leading underbar.
712 MCOS->EmitBytes(Entry->getName());
713 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
715 // AT_decl_file, index into the file table.
716 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
718 // AT_decl_line, source line number.
719 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
721 // AT_low_pc, start address of the label.
722 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
723 MCSymbolRefExpr::VK_None, context);
724 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
726 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
727 MCOS->EmitIntValue(0, 1);
729 // The DW_TAG_unspecified_parameters DIE abbrev (3).
730 MCOS->EmitULEB128IntValue(3);
732 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
733 MCOS->EmitIntValue(0, 1);
735 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
736 // for the dwarf labels.
737 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
738 Entries.begin(), ie = Entries.end(); it != ie;
740 const MCGenDwarfLabelEntry *Entry = *it;
744 // Add the NULL DIE terminating the Compile Unit DIE's.
745 MCOS->EmitIntValue(0, 1);
747 // Now set the value of the symbol at the end of the info section.
748 MCOS->EmitLabel(InfoEnd);
752 // When generating dwarf for assembly source files this emits the Dwarf
755 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
756 // Create the dwarf sections in this order (.debug_line already created).
757 MCContext &context = MCOS->getContext();
758 const MCAsmInfo *AsmInfo = context.getAsmInfo();
759 bool CreateDwarfSectionSymbols =
760 AsmInfo->doesDwarfUseRelocationsAcrossSections();
761 if (!CreateDwarfSectionSymbols)
762 LineSectionSymbol = NULL;
763 MCSymbol *AbbrevSectionSymbol = NULL;
764 MCSymbol *InfoSectionSymbol = NULL;
765 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
766 if (CreateDwarfSectionSymbols) {
767 InfoSectionSymbol = context.CreateTempSymbol();
768 MCOS->EmitLabel(InfoSectionSymbol);
770 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
771 if (CreateDwarfSectionSymbols) {
772 AbbrevSectionSymbol = context.CreateTempSymbol();
773 MCOS->EmitLabel(AbbrevSectionSymbol);
775 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
777 // If there are no line table entries then do not emit any section contents.
778 if (!context.hasMCLineSections())
781 // Output the data for .debug_aranges section.
782 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
784 // Output the data for .debug_abbrev section.
785 EmitGenDwarfAbbrev(MCOS);
787 // Output the data for .debug_info section.
788 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
792 // When generating dwarf for assembly source files this is called when symbol
793 // for a label is created. If this symbol is not a temporary and is in the
794 // section that dwarf is being generated for, save the needed info to create
797 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
798 SourceMgr &SrcMgr, SMLoc &Loc) {
799 // We won't create dwarf labels for temporary symbols or symbols not in
801 if (Symbol->isTemporary())
803 MCContext &context = MCOS->getContext();
804 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
807 // The dwarf label's name does not have the symbol name's leading
809 StringRef Name = Symbol->getName();
810 if (Name.startswith("_"))
811 Name = Name.substr(1, Name.size()-1);
813 // Get the dwarf file number to be used for the dwarf label.
814 unsigned FileNumber = context.getGenDwarfFileNumber();
816 // Finding the line number is the expensive part which is why we just don't
817 // pass it in as for some symbols we won't create a dwarf label.
818 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
819 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
821 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
822 // values so that they don't have things like an ARM thumb bit from the
823 // original symbol. So when used they won't get a low bit set after
825 MCSymbol *Label = context.CreateTempSymbol();
826 MCOS->EmitLabel(Label);
828 // Create and entry for the info and add it to the other entries.
829 MCGenDwarfLabelEntry *Entry =
830 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
831 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
834 static int getDataAlignmentFactor(MCStreamer &streamer) {
835 MCContext &context = streamer.getContext();
836 const MCAsmInfo *asmInfo = context.getAsmInfo();
837 int size = asmInfo->getCalleeSaveStackSlotSize();
838 if (asmInfo->isStackGrowthDirectionUp())
844 static unsigned getSizeForEncoding(MCStreamer &streamer,
845 unsigned symbolEncoding) {
846 MCContext &context = streamer.getContext();
847 unsigned format = symbolEncoding & 0x0f;
849 default: llvm_unreachable("Unknown Encoding");
850 case dwarf::DW_EH_PE_absptr:
851 case dwarf::DW_EH_PE_signed:
852 return context.getAsmInfo()->getPointerSize();
853 case dwarf::DW_EH_PE_udata2:
854 case dwarf::DW_EH_PE_sdata2:
856 case dwarf::DW_EH_PE_udata4:
857 case dwarf::DW_EH_PE_sdata4:
859 case dwarf::DW_EH_PE_udata8:
860 case dwarf::DW_EH_PE_sdata8:
865 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
866 unsigned symbolEncoding, bool isEH,
867 const char *comment = 0) {
868 MCContext &context = streamer.getContext();
869 const MCAsmInfo *asmInfo = context.getAsmInfo();
870 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
873 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
874 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
875 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
876 streamer.EmitAbsValue(v, size);
878 streamer.EmitValue(v, size);
881 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
882 unsigned symbolEncoding) {
883 MCContext &context = streamer.getContext();
884 const MCAsmInfo *asmInfo = context.getAsmInfo();
885 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
888 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
889 streamer.EmitValue(v, size);
893 class FrameEmitterImpl {
898 const MCSymbol *SectionStart;
900 FrameEmitterImpl(bool usingCFI, bool isEH)
901 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
904 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
906 /// EmitCompactUnwind - Emit the unwind information in a compact way.
907 void EmitCompactUnwind(MCStreamer &streamer,
908 const MCDwarfFrameInfo &frame);
910 const MCSymbol &EmitCIE(MCStreamer &streamer,
911 const MCSymbol *personality,
912 unsigned personalityEncoding,
913 const MCSymbol *lsda,
915 unsigned lsdaEncoding,
917 MCSymbol *EmitFDE(MCStreamer &streamer,
918 const MCSymbol &cieStart,
919 const MCDwarfFrameInfo &frame);
920 void EmitCFIInstructions(MCStreamer &streamer,
921 ArrayRef<MCCFIInstruction> Instrs,
922 MCSymbol *BaseLabel);
923 void EmitCFIInstruction(MCStreamer &Streamer,
924 const MCCFIInstruction &Instr);
927 } // end anonymous namespace
929 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
931 if (Streamer.isVerboseAsm()) {
934 default: EncStr = "<unknown encoding>"; break;
935 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
936 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
937 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
938 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
939 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
940 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
941 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
942 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
943 EncStr = "pcrel udata4";
945 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
946 EncStr = "pcrel sdata4";
948 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
949 EncStr = "pcrel udata8";
951 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
952 EncStr = "screl sdata8";
954 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
955 EncStr = "indirect pcrel udata4";
957 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
958 EncStr = "indirect pcrel sdata4";
960 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
961 EncStr = "indirect pcrel udata8";
963 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
964 EncStr = "indirect pcrel sdata8";
968 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
971 Streamer.EmitIntValue(Encoding, 1);
974 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
975 const MCCFIInstruction &Instr) {
976 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
977 bool VerboseAsm = Streamer.isVerboseAsm();
979 switch (Instr.getOperation()) {
980 case MCCFIInstruction::OpRegister: {
981 unsigned Reg1 = Instr.getRegister();
982 unsigned Reg2 = Instr.getRegister2();
984 Streamer.AddComment("DW_CFA_register");
985 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
986 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
988 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
989 Streamer.EmitULEB128IntValue(Reg1);
990 Streamer.EmitULEB128IntValue(Reg2);
993 case MCCFIInstruction::OpWindowSave: {
994 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
997 case MCCFIInstruction::OpUndefined: {
998 unsigned Reg = Instr.getRegister();
1000 Streamer.AddComment("DW_CFA_undefined");
1001 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1003 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
1004 Streamer.EmitULEB128IntValue(Reg);
1007 case MCCFIInstruction::OpAdjustCfaOffset:
1008 case MCCFIInstruction::OpDefCfaOffset: {
1009 const bool IsRelative =
1010 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1013 Streamer.AddComment("DW_CFA_def_cfa_offset");
1014 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1017 CFAOffset += Instr.getOffset();
1019 CFAOffset = -Instr.getOffset();
1022 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1023 Streamer.EmitULEB128IntValue(CFAOffset);
1027 case MCCFIInstruction::OpDefCfa: {
1029 Streamer.AddComment("DW_CFA_def_cfa");
1030 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1033 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1034 Streamer.EmitULEB128IntValue(Instr.getRegister());
1036 CFAOffset = -Instr.getOffset();
1039 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1040 Streamer.EmitULEB128IntValue(CFAOffset);
1045 case MCCFIInstruction::OpDefCfaRegister: {
1047 Streamer.AddComment("DW_CFA_def_cfa_register");
1048 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1051 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1052 Streamer.EmitULEB128IntValue(Instr.getRegister());
1057 case MCCFIInstruction::OpOffset:
1058 case MCCFIInstruction::OpRelOffset: {
1059 const bool IsRelative =
1060 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1062 unsigned Reg = Instr.getRegister();
1063 int Offset = Instr.getOffset();
1065 Offset -= CFAOffset;
1066 Offset = Offset / dataAlignmentFactor;
1069 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1070 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1071 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1072 Streamer.EmitULEB128IntValue(Reg);
1073 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1074 Streamer.EmitSLEB128IntValue(Offset);
1075 } else if (Reg < 64) {
1076 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1078 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1079 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1080 Streamer.EmitULEB128IntValue(Offset);
1082 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1083 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1084 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1085 Streamer.EmitULEB128IntValue(Reg);
1086 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1087 Streamer.EmitULEB128IntValue(Offset);
1091 case MCCFIInstruction::OpRememberState:
1092 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1093 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1095 case MCCFIInstruction::OpRestoreState:
1096 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1097 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1099 case MCCFIInstruction::OpSameValue: {
1100 unsigned Reg = Instr.getRegister();
1101 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1102 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1103 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1104 Streamer.EmitULEB128IntValue(Reg);
1107 case MCCFIInstruction::OpRestore: {
1108 unsigned Reg = Instr.getRegister();
1110 Streamer.AddComment("DW_CFA_restore");
1111 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1113 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1116 case MCCFIInstruction::OpEscape:
1117 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1118 Streamer.EmitBytes(Instr.getValues());
1121 llvm_unreachable("Unhandled case in switch");
1124 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1126 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1127 ArrayRef<MCCFIInstruction> Instrs,
1128 MCSymbol *BaseLabel) {
1129 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1130 const MCCFIInstruction &Instr = Instrs[i];
1131 MCSymbol *Label = Instr.getLabel();
1132 // Throw out move if the label is invalid.
1133 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1135 // Advance row if new location.
1136 if (BaseLabel && Label) {
1137 MCSymbol *ThisSym = Label;
1138 if (ThisSym != BaseLabel) {
1139 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1140 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1141 BaseLabel = ThisSym;
1145 EmitCFIInstruction(streamer, Instr);
1149 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1150 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1151 const MCDwarfFrameInfo &Frame) {
1152 MCContext &Context = Streamer.getContext();
1153 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1154 bool VerboseAsm = Streamer.isVerboseAsm();
1156 // range-start range-length compact-unwind-enc personality-func lsda
1157 // _foo LfooEnd-_foo 0x00000023 0 0
1158 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1160 // .section __LD,__compact_unwind,regular,debug
1162 // # compact unwind for _foo
1164 // .set L1,LfooEnd-_foo
1170 // # compact unwind for _bar
1172 // .set L2,LbarEnd-_bar
1175 // .quad __gxx_personality
1176 // .quad except_tab1
1178 uint32_t Encoding = Frame.CompactUnwindEncoding;
1179 if (!Encoding) return;
1180 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1182 // The encoding needs to know we have an LSDA.
1183 if (!DwarfEHFrameOnly && Frame.Lsda)
1184 Encoding |= 0x40000000;
1187 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1188 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1189 if (VerboseAsm) Streamer.AddComment("Range Start");
1190 Streamer.EmitSymbolValue(Frame.Function, Size);
1193 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1195 if (VerboseAsm) Streamer.AddComment("Range Length");
1196 Streamer.EmitAbsValue(Range, 4);
1199 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1200 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1201 Twine::utohexstr(Encoding));
1202 Streamer.EmitIntValue(Encoding, Size);
1204 // Personality Function
1205 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1206 if (VerboseAsm) Streamer.AddComment("Personality Function");
1207 if (!DwarfEHFrameOnly && Frame.Personality)
1208 Streamer.EmitSymbolValue(Frame.Personality, Size);
1210 Streamer.EmitIntValue(0, Size); // No personality fn
1213 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1214 if (VerboseAsm) Streamer.AddComment("LSDA");
1215 if (!DwarfEHFrameOnly && Frame.Lsda)
1216 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1218 Streamer.EmitIntValue(0, Size); // No LSDA
1221 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1222 const MCSymbol *personality,
1223 unsigned personalityEncoding,
1224 const MCSymbol *lsda,
1226 unsigned lsdaEncoding,
1228 MCContext &context = streamer.getContext();
1229 const MCRegisterInfo *MRI = context.getRegisterInfo();
1230 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1231 bool verboseAsm = streamer.isVerboseAsm();
1233 MCSymbol *sectionStart;
1234 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1235 sectionStart = context.CreateTempSymbol();
1237 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1239 streamer.EmitLabel(sectionStart);
1242 MCSymbol *sectionEnd = context.CreateTempSymbol();
1245 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1247 if (verboseAsm) streamer.AddComment("CIE Length");
1248 streamer.EmitAbsValue(Length, 4);
1251 unsigned CIE_ID = IsEH ? 0 : -1;
1252 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1253 streamer.EmitIntValue(CIE_ID, 4);
1256 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1257 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1259 // Augmentation String
1260 SmallString<8> Augmentation;
1262 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1263 Augmentation += "z";
1265 Augmentation += "P";
1267 Augmentation += "L";
1268 Augmentation += "R";
1270 Augmentation += "S";
1271 streamer.EmitBytes(Augmentation.str());
1273 streamer.EmitIntValue(0, 1);
1275 // Code Alignment Factor
1276 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1277 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1279 // Data Alignment Factor
1280 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1281 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1283 // Return Address Register
1284 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1285 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1287 // Augmentation Data Length (optional)
1289 unsigned augmentationLength = 0;
1292 // Personality Encoding
1293 augmentationLength += 1;
1295 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1298 augmentationLength += 1;
1299 // Encoding of the FDE pointers
1300 augmentationLength += 1;
1302 if (verboseAsm) streamer.AddComment("Augmentation Size");
1303 streamer.EmitULEB128IntValue(augmentationLength);
1305 // Augmentation Data (optional)
1307 // Personality Encoding
1308 EmitEncodingByte(streamer, personalityEncoding,
1309 "Personality Encoding");
1311 if (verboseAsm) streamer.AddComment("Personality");
1312 EmitPersonality(streamer, *personality, personalityEncoding);
1316 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1318 // Encoding of the FDE pointers
1319 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1323 // Initial Instructions
1325 const MCAsmInfo *MAI = context.getAsmInfo();
1327 const std::vector<MCCFIInstruction> &Instructions =
1328 MAI->getInitialFrameState();
1329 EmitCFIInstructions(streamer, Instructions, NULL);
1333 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1335 streamer.EmitLabel(sectionEnd);
1336 return *sectionStart;
1339 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1340 const MCSymbol &cieStart,
1341 const MCDwarfFrameInfo &frame) {
1342 MCContext &context = streamer.getContext();
1343 MCSymbol *fdeStart = context.CreateTempSymbol();
1344 MCSymbol *fdeEnd = context.CreateTempSymbol();
1345 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1346 bool verboseAsm = streamer.isVerboseAsm();
1348 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1350 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1351 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1352 streamer.EmitLabel(EHSym);
1356 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1357 if (verboseAsm) streamer.AddComment("FDE Length");
1358 streamer.EmitAbsValue(Length, 4);
1360 streamer.EmitLabel(fdeStart);
1363 const MCAsmInfo *asmInfo = context.getAsmInfo();
1365 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1367 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1368 streamer.EmitAbsValue(offset, 4);
1369 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1370 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1372 streamer.EmitAbsValue(offset, 4);
1374 streamer.EmitSymbolValue(&cieStart, 4);
1378 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1379 : (unsigned)dwarf::DW_EH_PE_absptr;
1380 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1381 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1384 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1386 if (verboseAsm) streamer.AddComment("FDE address range");
1387 streamer.EmitAbsValue(Range, PCSize);
1390 // Augmentation Data Length
1391 unsigned augmentationLength = 0;
1394 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1396 if (verboseAsm) streamer.AddComment("Augmentation size");
1397 streamer.EmitULEB128IntValue(augmentationLength);
1399 // Augmentation Data
1401 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1402 "Language Specific Data Area");
1405 // Call Frame Instructions
1406 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1409 streamer.EmitValueToAlignment(PCSize);
1416 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1417 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1419 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1420 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1421 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1422 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1423 IsSimple(IsSimple_) {
1425 const MCSymbol* Personality;
1426 unsigned PersonalityEncoding;
1427 unsigned LsdaEncoding;
1435 struct DenseMapInfo<CIEKey> {
1436 static CIEKey getEmptyKey() {
1437 return CIEKey::getEmptyKey();
1439 static CIEKey getTombstoneKey() {
1440 return CIEKey::getTombstoneKey();
1442 static unsigned getHashValue(const CIEKey &Key) {
1443 return static_cast<unsigned>(hash_combine(Key.Personality,
1444 Key.PersonalityEncoding,
1449 static bool isEqual(const CIEKey &LHS,
1450 const CIEKey &RHS) {
1451 return LHS.Personality == RHS.Personality &&
1452 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1453 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1454 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1455 LHS.IsSimple == RHS.IsSimple;
1460 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1461 bool UsingCFI, bool IsEH) {
1462 Streamer.generateCompactUnwindEncodings(MAB);
1464 MCContext &Context = Streamer.getContext();
1465 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1466 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1467 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1469 // Emit the compact unwind info if available.
1470 if (IsEH && MOFI->getCompactUnwindSection()) {
1471 bool SectionEmitted = false;
1472 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1473 const MCDwarfFrameInfo &Frame = FrameArray[i];
1474 if (Frame.CompactUnwindEncoding == 0) continue;
1475 if (!SectionEmitted) {
1476 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1477 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1478 SectionEmitted = true;
1480 Emitter.EmitCompactUnwind(Streamer, Frame);
1484 const MCSection &Section =
1485 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1486 *MOFI->getDwarfFrameSection();
1487 Streamer.SwitchSection(&Section);
1488 MCSymbol *SectionStart = Context.CreateTempSymbol();
1489 Streamer.EmitLabel(SectionStart);
1490 Emitter.setSectionStart(SectionStart);
1492 MCSymbol *FDEEnd = NULL;
1493 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1495 const MCSymbol *DummyDebugKey = NULL;
1496 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1497 const MCDwarfFrameInfo &Frame = FrameArray[i];
1498 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1499 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1500 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1502 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1503 Frame.PersonalityEncoding, Frame.Lsda,
1504 Frame.IsSignalFrame,
1508 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1511 Streamer.EmitLabel(FDEEnd);
1514 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1516 Streamer.EmitLabel(FDEEnd);
1519 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1520 uint64_t AddrDelta) {
1521 MCContext &Context = Streamer.getContext();
1522 SmallString<256> Tmp;
1523 raw_svector_ostream OS(Tmp);
1524 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1525 Streamer.EmitBytes(OS.str());
1528 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1531 // Scale the address delta by the minimum instruction length.
1532 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1534 if (AddrDelta == 0) {
1535 } else if (isUIntN(6, AddrDelta)) {
1536 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1538 } else if (isUInt<8>(AddrDelta)) {
1539 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1540 OS << uint8_t(AddrDelta);
1541 } else if (isUInt<16>(AddrDelta)) {
1542 // FIXME: check what is the correct behavior on a big endian machine.
1543 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1544 OS << uint8_t( AddrDelta & 0xff);
1545 OS << uint8_t((AddrDelta >> 8) & 0xff);
1547 // FIXME: check what is the correct behavior on a big endian machine.
1548 assert(isUInt<32>(AddrDelta));
1549 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1550 OS << uint8_t( AddrDelta & 0xff);
1551 OS << uint8_t((AddrDelta >> 8) & 0xff);
1552 OS << uint8_t((AddrDelta >> 16) & 0xff);
1553 OS << uint8_t((AddrDelta >> 24) & 0xff);