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 // Get the MCLineSection for this section, if one does not exist for this
85 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
86 MCOS->getContext().getMCLineSections();
87 MCLineSection *LineSection = MCLineSections.lookup(Section);
89 // Create a new MCLineSection. This will be deleted after the dwarf line
90 // table is created using it by iterating through the MCLineSections
92 LineSection = new MCLineSection;
93 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
94 MCOS->getContext().addMCLineSection(Section, LineSection);
97 // Add the line entry to this section's entries.
98 LineSection->addLineEntry(LineEntry,
99 MCOS->getContext().getDwarfCompileUnitID());
103 // This helper routine returns an expression of End - Start + IntVal .
105 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
106 const MCSymbol &Start,
109 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
111 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
113 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
115 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
117 MCConstantExpr::Create(IntVal, MCOS.getContext());
119 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
124 // This emits the Dwarf line table for the specified section from the entries
125 // in the LineSection.
127 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
128 const MCSection *Section,
129 const MCLineSection *LineSection,
131 // This LineSection does not contain any LineEntry for the given Compile Unit.
132 if (!LineSection->containEntriesForID(CUID))
135 unsigned FileNum = 1;
136 unsigned LastLine = 1;
138 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
140 unsigned Discriminator = 0;
141 MCSymbol *LastLabel = NULL;
143 // Loop through each MCLineEntry and encode the dwarf line number table.
144 for (MCLineSection::const_iterator
145 it = LineSection->getMCLineEntries(CUID).begin(),
146 ie = LineSection->getMCLineEntries(CUID).end(); it != ie; ++it) {
148 if (FileNum != it->getFileNum()) {
149 FileNum = it->getFileNum();
150 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
151 MCOS->EmitULEB128IntValue(FileNum);
153 if (Column != it->getColumn()) {
154 Column = it->getColumn();
155 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
156 MCOS->EmitULEB128IntValue(Column);
158 if (Discriminator != it->getDiscriminator()) {
159 Discriminator = it->getDiscriminator();
161 MCOS->getContext().getAsmInfo()->getULEB128Size(Discriminator);
162 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
163 MCOS->EmitULEB128IntValue(Size + 1);
164 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
165 MCOS->EmitULEB128IntValue(Discriminator);
167 if (Isa != it->getIsa()) {
169 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
170 MCOS->EmitULEB128IntValue(Isa);
172 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
173 Flags = it->getFlags();
174 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
176 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
177 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
178 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
179 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
180 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
181 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
183 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
184 MCSymbol *Label = it->getLabel();
186 // At this point we want to emit/create the sequence to encode the delta in
187 // line numbers and the increment of the address from the previous Label
188 // and the current Label.
189 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
190 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
191 asmInfo->getPointerSize());
193 LastLine = it->getLine();
197 // Emit a DW_LNE_end_sequence for the end of the section.
198 // Using the pointer Section create a temporary label at the end of the
199 // section and use that and the LastLabel to compute the address delta
200 // and use INT64_MAX as the line delta which is the signal that this is
201 // actually a DW_LNE_end_sequence.
203 // Switch to the section to be able to create a symbol at its end.
204 // TODO: keep track of the last subsection so that this symbol appears in the
206 MCOS->SwitchSection(Section);
208 MCContext &context = MCOS->getContext();
209 // Create a symbol at the end of the section.
210 MCSymbol *SectionEnd = context.CreateTempSymbol();
211 // Set the value of the symbol, as we are at the end of the section.
212 MCOS->EmitLabel(SectionEnd);
214 // Switch back the dwarf line section.
215 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
217 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
218 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
219 asmInfo->getPointerSize());
223 // This emits the Dwarf file and the line tables.
225 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
226 MCContext &context = MCOS->getContext();
227 // Switch to the section where the table will be emitted into.
228 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
230 const DenseMap<unsigned, MCSymbol *> &MCLineTableSymbols =
231 MCOS->getContext().getMCLineTableSymbols();
232 // CUID and MCLineTableSymbols are set in DwarfDebug, when DwarfDebug does
233 // not exist, CUID will be 0 and MCLineTableSymbols will be empty.
234 // Handle Compile Unit 0, the line table start symbol is the section symbol.
235 const MCSymbol *LineStartSym = EmitCU(MCOS, 0);
236 // Handle the rest of the Compile Units.
237 for (unsigned Is = 1, Ie = MCLineTableSymbols.size(); Is < Ie; Is++)
240 // Now delete the MCLineSections that were created in MCLineEntry::Make()
241 // and used to emit the line table.
242 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
243 MCOS->getContext().getMCLineSections();
244 for (DenseMap<const MCSection *, MCLineSection *>::const_iterator it =
245 MCLineSections.begin(), ie = MCLineSections.end(); it != ie;
252 const MCSymbol *MCDwarfFileTable::EmitCU(MCStreamer *MCOS, unsigned CUID) {
253 MCContext &context = MCOS->getContext();
255 // Create a symbol at the beginning of the line table.
256 MCSymbol *LineStartSym = MCOS->getContext().getMCLineTableSymbol(CUID);
258 LineStartSym = context.CreateTempSymbol();
259 // Set the value of the symbol, as we are at the start of the line table.
260 MCOS->EmitLabel(LineStartSym);
262 // Create a symbol for the end of the section (to be set when we get there).
263 MCSymbol *LineEndSym = context.CreateTempSymbol();
265 // The first 4 bytes is the total length of the information for this
266 // compilation unit (not including these 4 bytes for the length).
267 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
270 // Next 2 bytes is the Version, which is Dwarf 2.
271 MCOS->EmitIntValue(2, 2);
273 // Create a symbol for the end of the prologue (to be set when we get there).
274 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
276 // Length of the prologue, is the next 4 bytes. Which is the start of the
277 // section to the end of the prologue. Not including the 4 bytes for the
278 // total length, the 2 bytes for the version, and these 4 bytes for the
279 // length of the prologue.
280 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
283 // Parameters of the state machine, are next.
284 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
285 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
286 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
287 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
288 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
290 // Standard opcode lengths
291 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
292 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
293 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
294 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
295 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
296 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
297 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
298 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
299 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
300 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
301 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
302 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
304 // Put out the directory and file tables.
306 // First the directory table.
307 const SmallVectorImpl<StringRef> &MCDwarfDirs =
308 context.getMCDwarfDirs(CUID);
309 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
310 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
311 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
313 MCOS->EmitIntValue(0, 1); // Terminate the directory list
315 // Second the file table.
316 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
317 MCOS->getContext().getMCDwarfFiles(CUID);
318 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
319 MCOS->EmitBytes(MCDwarfFiles[i]->getName()); // FileName
320 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
322 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
323 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
324 MCOS->EmitIntValue(0, 1); // filesize (always 0)
326 MCOS->EmitIntValue(0, 1); // Terminate the file list
328 // This is the end of the prologue, so set the value of the symbol at the
329 // end of the prologue (that was used in a previous expression).
330 MCOS->EmitLabel(ProEndSym);
332 // Put out the line tables.
333 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
334 MCOS->getContext().getMCLineSections();
335 const std::vector<const MCSection *> &MCLineSectionOrder =
336 MCOS->getContext().getMCLineSectionOrder();
337 for (std::vector<const MCSection*>::const_iterator it =
338 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
340 const MCSection *Sec = *it;
341 const MCLineSection *Line = MCLineSections.lookup(Sec);
342 EmitDwarfLineTable(MCOS, Sec, Line, CUID);
345 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines()
346 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
347 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
349 // total_length >= prologue_length + 10
350 // We are 4 bytes short, since we have total_length = 51 and
351 // prologue_length = 45
353 // The regular end_sequence should be sufficient.
354 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
357 // This is the end of the section, so set the value of the symbol at the end
358 // of this section (that was used in a previous expression).
359 MCOS->EmitLabel(LineEndSym);
364 /// Utility function to emit the encoding to a streamer.
365 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
366 uint64_t AddrDelta) {
367 MCContext &Context = MCOS->getContext();
368 SmallString<256> Tmp;
369 raw_svector_ostream OS(Tmp);
370 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
371 MCOS->EmitBytes(OS.str());
374 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
375 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
376 uint64_t AddrDelta, raw_ostream &OS) {
377 uint64_t Temp, Opcode;
378 bool NeedCopy = false;
380 // Scale the address delta by the minimum instruction length.
381 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
383 // A LineDelta of INT64_MAX is a signal that this is actually a
384 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
385 // end_sequence to emit the matrix entry.
386 if (LineDelta == INT64_MAX) {
387 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
388 OS << char(dwarf::DW_LNS_const_add_pc);
390 OS << char(dwarf::DW_LNS_advance_pc);
391 encodeULEB128(AddrDelta, OS);
393 OS << char(dwarf::DW_LNS_extended_op);
395 OS << char(dwarf::DW_LNE_end_sequence);
399 // Bias the line delta by the base.
400 Temp = LineDelta - DWARF2_LINE_BASE;
402 // If the line increment is out of range of a special opcode, we must encode
403 // it with DW_LNS_advance_line.
404 if (Temp >= DWARF2_LINE_RANGE) {
405 OS << char(dwarf::DW_LNS_advance_line);
406 encodeSLEB128(LineDelta, OS);
409 Temp = 0 - DWARF2_LINE_BASE;
413 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
414 if (LineDelta == 0 && AddrDelta == 0) {
415 OS << char(dwarf::DW_LNS_copy);
419 // Bias the opcode by the special opcode base.
420 Temp += DWARF2_LINE_OPCODE_BASE;
422 // Avoid overflow when addr_delta is large.
423 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
424 // Try using a special opcode.
425 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
431 // Try using DW_LNS_const_add_pc followed by special op.
432 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
434 OS << char(dwarf::DW_LNS_const_add_pc);
440 // Otherwise use DW_LNS_advance_pc.
441 OS << char(dwarf::DW_LNS_advance_pc);
442 encodeULEB128(AddrDelta, OS);
445 OS << char(dwarf::DW_LNS_copy);
450 void MCDwarfFile::print(raw_ostream &OS) const {
451 OS << '"' << getName() << '"';
454 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
455 void MCDwarfFile::dump() const {
460 // Utility function to write a tuple for .debug_abbrev.
461 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
462 MCOS->EmitULEB128IntValue(Name);
463 MCOS->EmitULEB128IntValue(Form);
466 // When generating dwarf for assembly source files this emits
467 // the data for .debug_abbrev section which contains three DIEs.
468 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
469 MCContext &context = MCOS->getContext();
470 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
472 // DW_TAG_compile_unit DIE abbrev (1).
473 MCOS->EmitULEB128IntValue(1);
474 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
475 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
476 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
477 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
478 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
479 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
480 if (!context.getCompilationDir().empty())
481 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
482 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
483 if (!DwarfDebugFlags.empty())
484 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
485 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
486 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
487 EmitAbbrev(MCOS, 0, 0);
489 // DW_TAG_label DIE abbrev (2).
490 MCOS->EmitULEB128IntValue(2);
491 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
492 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
493 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
494 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
495 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
496 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
497 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
498 EmitAbbrev(MCOS, 0, 0);
500 // DW_TAG_unspecified_parameters DIE abbrev (3).
501 MCOS->EmitULEB128IntValue(3);
502 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
503 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
504 EmitAbbrev(MCOS, 0, 0);
506 // Terminate the abbreviations for this compilation unit.
507 MCOS->EmitIntValue(0, 1);
510 // When generating dwarf for assembly source files this emits the data for
511 // .debug_aranges section. Which contains a header and a table of pairs of
512 // PointerSize'ed values for the address and size of section(s) with line table
513 // entries (just the default .text in our case) and a terminating pair of zeros.
514 static void EmitGenDwarfAranges(MCStreamer *MCOS,
515 const MCSymbol *InfoSectionSymbol) {
516 MCContext &context = MCOS->getContext();
518 // Create a symbol at the end of the section that we are creating the dwarf
519 // debugging info to use later in here as part of the expression to calculate
520 // the size of the section for the table.
521 MCOS->SwitchSection(context.getGenDwarfSection());
522 MCSymbol *SectionEndSym = context.CreateTempSymbol();
523 MCOS->EmitLabel(SectionEndSym);
524 context.setGenDwarfSectionEndSym(SectionEndSym);
526 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
528 // This will be the length of the .debug_aranges section, first account for
529 // the size of each item in the header (see below where we emit these items).
530 int Length = 4 + 2 + 4 + 1 + 1;
532 // Figure the padding after the header before the table of address and size
533 // pairs who's values are PointerSize'ed.
534 const MCAsmInfo *asmInfo = context.getAsmInfo();
535 int AddrSize = asmInfo->getPointerSize();
536 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
537 if (Pad == 2 * AddrSize)
541 // Add the size of the pair of PointerSize'ed values for the address and size
542 // of the one default .text section we have in the table.
543 Length += 2 * AddrSize;
544 // And the pair of terminating zeros.
545 Length += 2 * AddrSize;
548 // Emit the header for this section.
549 // The 4 byte length not including the 4 byte value for the length.
550 MCOS->EmitIntValue(Length - 4, 4);
551 // The 2 byte version, which is 2.
552 MCOS->EmitIntValue(2, 2);
553 // The 4 byte offset to the compile unit in the .debug_info from the start
554 // of the .debug_info.
555 if (InfoSectionSymbol)
556 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
558 MCOS->EmitIntValue(0, 4);
559 // The 1 byte size of an address.
560 MCOS->EmitIntValue(AddrSize, 1);
561 // The 1 byte size of a segment descriptor, we use a value of zero.
562 MCOS->EmitIntValue(0, 1);
563 // Align the header with the padding if needed, before we put out the table.
564 for(int i = 0; i < Pad; i++)
565 MCOS->EmitIntValue(0, 1);
567 // Now emit the table of pairs of PointerSize'ed values for the section(s)
568 // address and size, in our case just the one default .text section.
569 const MCExpr *Addr = MCSymbolRefExpr::Create(
570 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
571 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
572 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
573 MCOS->EmitAbsValue(Addr, AddrSize);
574 MCOS->EmitAbsValue(Size, AddrSize);
576 // And finally the pair of terminating zeros.
577 MCOS->EmitIntValue(0, AddrSize);
578 MCOS->EmitIntValue(0, AddrSize);
581 // When generating dwarf for assembly source files this emits the data for
582 // .debug_info section which contains three parts. The header, the compile_unit
583 // DIE and a list of label DIEs.
584 static void EmitGenDwarfInfo(MCStreamer *MCOS,
585 const MCSymbol *AbbrevSectionSymbol,
586 const MCSymbol *LineSectionSymbol) {
587 MCContext &context = MCOS->getContext();
589 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
591 // Create a symbol at the start and end of this section used in here for the
592 // expression to calculate the length in the header.
593 MCSymbol *InfoStart = context.CreateTempSymbol();
594 MCOS->EmitLabel(InfoStart);
595 MCSymbol *InfoEnd = context.CreateTempSymbol();
597 // First part: the header.
599 // The 4 byte total length of the information for this compilation unit, not
600 // including these 4 bytes.
601 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
602 MCOS->EmitAbsValue(Length, 4);
604 // The 2 byte DWARF version, which is 2.
605 MCOS->EmitIntValue(2, 2);
607 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
608 // it is at the start of that section so this is zero.
609 if (AbbrevSectionSymbol) {
610 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
612 MCOS->EmitIntValue(0, 4);
615 const MCAsmInfo *asmInfo = context.getAsmInfo();
616 int AddrSize = asmInfo->getPointerSize();
617 // The 1 byte size of an address.
618 MCOS->EmitIntValue(AddrSize, 1);
620 // Second part: the compile_unit DIE.
622 // The DW_TAG_compile_unit DIE abbrev (1).
623 MCOS->EmitULEB128IntValue(1);
625 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
626 // which is at the start of that section so this is zero.
627 if (LineSectionSymbol) {
628 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
630 MCOS->EmitIntValue(0, 4);
633 // AT_low_pc, the first address of the default .text section.
634 const MCExpr *Start = MCSymbolRefExpr::Create(
635 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
636 MCOS->EmitAbsValue(Start, AddrSize);
638 // AT_high_pc, the last address of the default .text section.
639 const MCExpr *End = MCSymbolRefExpr::Create(
640 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
641 MCOS->EmitAbsValue(End, AddrSize);
643 // AT_name, the name of the source file. Reconstruct from the first directory
644 // and file table entries.
645 const SmallVectorImpl<StringRef> &MCDwarfDirs =
646 context.getMCDwarfDirs();
647 if (MCDwarfDirs.size() > 0) {
648 MCOS->EmitBytes(MCDwarfDirs[0]);
649 MCOS->EmitBytes("/");
651 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
652 MCOS->getContext().getMCDwarfFiles();
653 MCOS->EmitBytes(MCDwarfFiles[1]->getName());
654 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
656 // AT_comp_dir, the working directory the assembly was done in.
657 if (!context.getCompilationDir().empty()) {
658 MCOS->EmitBytes(context.getCompilationDir());
659 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
662 // AT_APPLE_flags, the command line arguments of the assembler tool.
663 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
664 if (!DwarfDebugFlags.empty()){
665 MCOS->EmitBytes(DwarfDebugFlags);
666 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
669 // AT_producer, the version of the assembler tool.
670 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
671 if (!DwarfDebugProducer.empty()){
672 MCOS->EmitBytes(DwarfDebugProducer);
675 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
676 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
677 MCOS->EmitBytes(StringRef(")"));
679 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
681 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
682 // draft has no standard code for assembler.
683 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
685 // Third part: the list of label DIEs.
687 // Loop on saved info for dwarf labels and create the DIEs for them.
688 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
689 MCOS->getContext().getMCGenDwarfLabelEntries();
690 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
691 Entries.begin(), ie = Entries.end(); it != ie;
693 const MCGenDwarfLabelEntry *Entry = *it;
695 // The DW_TAG_label DIE abbrev (2).
696 MCOS->EmitULEB128IntValue(2);
698 // AT_name, of the label without any leading underbar.
699 MCOS->EmitBytes(Entry->getName());
700 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
702 // AT_decl_file, index into the file table.
703 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
705 // AT_decl_line, source line number.
706 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
708 // AT_low_pc, start address of the label.
709 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
710 MCSymbolRefExpr::VK_None, context);
711 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
713 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
714 MCOS->EmitIntValue(0, 1);
716 // The DW_TAG_unspecified_parameters DIE abbrev (3).
717 MCOS->EmitULEB128IntValue(3);
719 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
720 MCOS->EmitIntValue(0, 1);
722 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
723 // for the dwarf labels.
724 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
725 Entries.begin(), ie = Entries.end(); it != ie;
727 const MCGenDwarfLabelEntry *Entry = *it;
731 // Add the NULL DIE terminating the Compile Unit DIE's.
732 MCOS->EmitIntValue(0, 1);
734 // Now set the value of the symbol at the end of the info section.
735 MCOS->EmitLabel(InfoEnd);
739 // When generating dwarf for assembly source files this emits the Dwarf
742 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
743 // Create the dwarf sections in this order (.debug_line already created).
744 MCContext &context = MCOS->getContext();
745 const MCAsmInfo *AsmInfo = context.getAsmInfo();
746 bool CreateDwarfSectionSymbols =
747 AsmInfo->doesDwarfUseRelocationsAcrossSections();
748 if (!CreateDwarfSectionSymbols)
749 LineSectionSymbol = NULL;
750 MCSymbol *AbbrevSectionSymbol = NULL;
751 MCSymbol *InfoSectionSymbol = NULL;
752 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
753 if (CreateDwarfSectionSymbols) {
754 InfoSectionSymbol = context.CreateTempSymbol();
755 MCOS->EmitLabel(InfoSectionSymbol);
757 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
758 if (CreateDwarfSectionSymbols) {
759 AbbrevSectionSymbol = context.CreateTempSymbol();
760 MCOS->EmitLabel(AbbrevSectionSymbol);
762 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
764 // If there are no line table entries then do not emit any section contents.
765 if (context.getMCLineSections().empty())
768 // Output the data for .debug_aranges section.
769 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
771 // Output the data for .debug_abbrev section.
772 EmitGenDwarfAbbrev(MCOS);
774 // Output the data for .debug_info section.
775 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
779 // When generating dwarf for assembly source files this is called when symbol
780 // for a label is created. If this symbol is not a temporary and is in the
781 // section that dwarf is being generated for, save the needed info to create
784 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
785 SourceMgr &SrcMgr, SMLoc &Loc) {
786 // We won't create dwarf labels for temporary symbols or symbols not in
788 if (Symbol->isTemporary())
790 MCContext &context = MCOS->getContext();
791 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
794 // The dwarf label's name does not have the symbol name's leading
796 StringRef Name = Symbol->getName();
797 if (Name.startswith("_"))
798 Name = Name.substr(1, Name.size()-1);
800 // Get the dwarf file number to be used for the dwarf label.
801 unsigned FileNumber = context.getGenDwarfFileNumber();
803 // Finding the line number is the expensive part which is why we just don't
804 // pass it in as for some symbols we won't create a dwarf label.
805 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
806 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
808 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
809 // values so that they don't have things like an ARM thumb bit from the
810 // original symbol. So when used they won't get a low bit set after
812 MCSymbol *Label = context.CreateTempSymbol();
813 MCOS->EmitLabel(Label);
815 // Create and entry for the info and add it to the other entries.
816 MCGenDwarfLabelEntry *Entry =
817 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
818 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
821 static int getDataAlignmentFactor(MCStreamer &streamer) {
822 MCContext &context = streamer.getContext();
823 const MCAsmInfo *asmInfo = context.getAsmInfo();
824 int size = asmInfo->getCalleeSaveStackSlotSize();
825 if (asmInfo->isStackGrowthDirectionUp())
831 static unsigned getSizeForEncoding(MCStreamer &streamer,
832 unsigned symbolEncoding) {
833 MCContext &context = streamer.getContext();
834 unsigned format = symbolEncoding & 0x0f;
836 default: llvm_unreachable("Unknown Encoding");
837 case dwarf::DW_EH_PE_absptr:
838 case dwarf::DW_EH_PE_signed:
839 return context.getAsmInfo()->getPointerSize();
840 case dwarf::DW_EH_PE_udata2:
841 case dwarf::DW_EH_PE_sdata2:
843 case dwarf::DW_EH_PE_udata4:
844 case dwarf::DW_EH_PE_sdata4:
846 case dwarf::DW_EH_PE_udata8:
847 case dwarf::DW_EH_PE_sdata8:
852 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
853 unsigned symbolEncoding, bool isEH,
854 const char *comment = 0) {
855 MCContext &context = streamer.getContext();
856 const MCAsmInfo *asmInfo = context.getAsmInfo();
857 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
860 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
861 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
862 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
863 streamer.EmitAbsValue(v, size);
865 streamer.EmitValue(v, size);
868 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
869 unsigned symbolEncoding) {
870 MCContext &context = streamer.getContext();
871 const MCAsmInfo *asmInfo = context.getAsmInfo();
872 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
875 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
876 streamer.EmitValue(v, size);
880 class FrameEmitterImpl {
885 const MCSymbol *SectionStart;
887 FrameEmitterImpl(bool usingCFI, bool isEH)
888 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
891 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
893 /// EmitCompactUnwind - Emit the unwind information in a compact way.
894 void EmitCompactUnwind(MCStreamer &streamer,
895 const MCDwarfFrameInfo &frame);
897 const MCSymbol &EmitCIE(MCStreamer &streamer,
898 const MCSymbol *personality,
899 unsigned personalityEncoding,
900 const MCSymbol *lsda,
902 unsigned lsdaEncoding,
904 MCSymbol *EmitFDE(MCStreamer &streamer,
905 const MCSymbol &cieStart,
906 const MCDwarfFrameInfo &frame);
907 void EmitCFIInstructions(MCStreamer &streamer,
908 ArrayRef<MCCFIInstruction> Instrs,
909 MCSymbol *BaseLabel);
910 void EmitCFIInstruction(MCStreamer &Streamer,
911 const MCCFIInstruction &Instr);
914 } // end anonymous namespace
916 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
918 if (Streamer.isVerboseAsm()) {
921 default: EncStr = "<unknown encoding>"; break;
922 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
923 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
924 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
925 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
926 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
927 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
928 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
929 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
930 EncStr = "pcrel udata4";
932 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
933 EncStr = "pcrel sdata4";
935 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
936 EncStr = "pcrel udata8";
938 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
939 EncStr = "screl sdata8";
941 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
942 EncStr = "indirect pcrel udata4";
944 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
945 EncStr = "indirect pcrel sdata4";
947 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
948 EncStr = "indirect pcrel udata8";
950 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
951 EncStr = "indirect pcrel sdata8";
955 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
958 Streamer.EmitIntValue(Encoding, 1);
961 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
962 const MCCFIInstruction &Instr) {
963 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
964 bool VerboseAsm = Streamer.isVerboseAsm();
966 switch (Instr.getOperation()) {
967 case MCCFIInstruction::OpRegister: {
968 unsigned Reg1 = Instr.getRegister();
969 unsigned Reg2 = Instr.getRegister2();
971 Streamer.AddComment("DW_CFA_register");
972 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
973 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
975 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
976 Streamer.EmitULEB128IntValue(Reg1);
977 Streamer.EmitULEB128IntValue(Reg2);
980 case MCCFIInstruction::OpWindowSave: {
981 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
984 case MCCFIInstruction::OpUndefined: {
985 unsigned Reg = Instr.getRegister();
987 Streamer.AddComment("DW_CFA_undefined");
988 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
990 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
991 Streamer.EmitULEB128IntValue(Reg);
994 case MCCFIInstruction::OpAdjustCfaOffset:
995 case MCCFIInstruction::OpDefCfaOffset: {
996 const bool IsRelative =
997 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1000 Streamer.AddComment("DW_CFA_def_cfa_offset");
1001 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1004 CFAOffset += Instr.getOffset();
1006 CFAOffset = -Instr.getOffset();
1009 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1010 Streamer.EmitULEB128IntValue(CFAOffset);
1014 case MCCFIInstruction::OpDefCfa: {
1016 Streamer.AddComment("DW_CFA_def_cfa");
1017 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1020 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1021 Streamer.EmitULEB128IntValue(Instr.getRegister());
1023 CFAOffset = -Instr.getOffset();
1026 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1027 Streamer.EmitULEB128IntValue(CFAOffset);
1032 case MCCFIInstruction::OpDefCfaRegister: {
1034 Streamer.AddComment("DW_CFA_def_cfa_register");
1035 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1038 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1039 Streamer.EmitULEB128IntValue(Instr.getRegister());
1044 case MCCFIInstruction::OpOffset:
1045 case MCCFIInstruction::OpRelOffset: {
1046 const bool IsRelative =
1047 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1049 unsigned Reg = Instr.getRegister();
1050 int Offset = Instr.getOffset();
1052 Offset -= CFAOffset;
1053 Offset = Offset / dataAlignmentFactor;
1056 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1057 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1058 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1059 Streamer.EmitULEB128IntValue(Reg);
1060 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1061 Streamer.EmitSLEB128IntValue(Offset);
1062 } else if (Reg < 64) {
1063 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1065 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1066 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1067 Streamer.EmitULEB128IntValue(Offset);
1069 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1070 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 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.EmitULEB128IntValue(Offset);
1078 case MCCFIInstruction::OpRememberState:
1079 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1080 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1082 case MCCFIInstruction::OpRestoreState:
1083 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1084 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1086 case MCCFIInstruction::OpSameValue: {
1087 unsigned Reg = Instr.getRegister();
1088 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1089 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1090 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1091 Streamer.EmitULEB128IntValue(Reg);
1094 case MCCFIInstruction::OpRestore: {
1095 unsigned Reg = Instr.getRegister();
1097 Streamer.AddComment("DW_CFA_restore");
1098 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1100 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1103 case MCCFIInstruction::OpEscape:
1104 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1105 Streamer.EmitBytes(Instr.getValues());
1108 llvm_unreachable("Unhandled case in switch");
1111 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1113 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1114 ArrayRef<MCCFIInstruction> Instrs,
1115 MCSymbol *BaseLabel) {
1116 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1117 const MCCFIInstruction &Instr = Instrs[i];
1118 MCSymbol *Label = Instr.getLabel();
1119 // Throw out move if the label is invalid.
1120 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1122 // Advance row if new location.
1123 if (BaseLabel && Label) {
1124 MCSymbol *ThisSym = Label;
1125 if (ThisSym != BaseLabel) {
1126 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1127 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1128 BaseLabel = ThisSym;
1132 EmitCFIInstruction(streamer, Instr);
1136 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1137 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1138 const MCDwarfFrameInfo &Frame) {
1139 MCContext &Context = Streamer.getContext();
1140 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1141 bool VerboseAsm = Streamer.isVerboseAsm();
1143 // range-start range-length compact-unwind-enc personality-func lsda
1144 // _foo LfooEnd-_foo 0x00000023 0 0
1145 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1147 // .section __LD,__compact_unwind,regular,debug
1149 // # compact unwind for _foo
1151 // .set L1,LfooEnd-_foo
1157 // # compact unwind for _bar
1159 // .set L2,LbarEnd-_bar
1162 // .quad __gxx_personality
1163 // .quad except_tab1
1165 uint32_t Encoding = Frame.CompactUnwindEncoding;
1166 if (!Encoding) return;
1167 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1169 // The encoding needs to know we have an LSDA.
1170 if (!DwarfEHFrameOnly && Frame.Lsda)
1171 Encoding |= 0x40000000;
1174 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1175 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1176 if (VerboseAsm) Streamer.AddComment("Range Start");
1177 Streamer.EmitSymbolValue(Frame.Function, Size);
1180 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1182 if (VerboseAsm) Streamer.AddComment("Range Length");
1183 Streamer.EmitAbsValue(Range, 4);
1186 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1187 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1188 Twine::utohexstr(Encoding));
1189 Streamer.EmitIntValue(Encoding, Size);
1191 // Personality Function
1192 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1193 if (VerboseAsm) Streamer.AddComment("Personality Function");
1194 if (!DwarfEHFrameOnly && Frame.Personality)
1195 Streamer.EmitSymbolValue(Frame.Personality, Size);
1197 Streamer.EmitIntValue(0, Size); // No personality fn
1200 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1201 if (VerboseAsm) Streamer.AddComment("LSDA");
1202 if (!DwarfEHFrameOnly && Frame.Lsda)
1203 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1205 Streamer.EmitIntValue(0, Size); // No LSDA
1208 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1209 const MCSymbol *personality,
1210 unsigned personalityEncoding,
1211 const MCSymbol *lsda,
1213 unsigned lsdaEncoding,
1215 MCContext &context = streamer.getContext();
1216 const MCRegisterInfo *MRI = context.getRegisterInfo();
1217 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1218 bool verboseAsm = streamer.isVerboseAsm();
1220 MCSymbol *sectionStart;
1221 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1222 sectionStart = context.CreateTempSymbol();
1224 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1226 streamer.EmitLabel(sectionStart);
1229 MCSymbol *sectionEnd = context.CreateTempSymbol();
1232 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1234 if (verboseAsm) streamer.AddComment("CIE Length");
1235 streamer.EmitAbsValue(Length, 4);
1238 unsigned CIE_ID = IsEH ? 0 : -1;
1239 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1240 streamer.EmitIntValue(CIE_ID, 4);
1243 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1244 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1246 // Augmentation String
1247 SmallString<8> Augmentation;
1249 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1250 Augmentation += "z";
1252 Augmentation += "P";
1254 Augmentation += "L";
1255 Augmentation += "R";
1257 Augmentation += "S";
1258 streamer.EmitBytes(Augmentation.str());
1260 streamer.EmitIntValue(0, 1);
1262 // Code Alignment Factor
1263 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1264 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1266 // Data Alignment Factor
1267 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1268 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1270 // Return Address Register
1271 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1272 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1274 // Augmentation Data Length (optional)
1276 unsigned augmentationLength = 0;
1279 // Personality Encoding
1280 augmentationLength += 1;
1282 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1285 augmentationLength += 1;
1286 // Encoding of the FDE pointers
1287 augmentationLength += 1;
1289 if (verboseAsm) streamer.AddComment("Augmentation Size");
1290 streamer.EmitULEB128IntValue(augmentationLength);
1292 // Augmentation Data (optional)
1294 // Personality Encoding
1295 EmitEncodingByte(streamer, personalityEncoding,
1296 "Personality Encoding");
1298 if (verboseAsm) streamer.AddComment("Personality");
1299 EmitPersonality(streamer, *personality, personalityEncoding);
1303 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1305 // Encoding of the FDE pointers
1306 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1310 // Initial Instructions
1312 const MCAsmInfo *MAI = context.getAsmInfo();
1314 const std::vector<MCCFIInstruction> &Instructions =
1315 MAI->getInitialFrameState();
1316 EmitCFIInstructions(streamer, Instructions, NULL);
1320 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1322 streamer.EmitLabel(sectionEnd);
1323 return *sectionStart;
1326 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1327 const MCSymbol &cieStart,
1328 const MCDwarfFrameInfo &frame) {
1329 MCContext &context = streamer.getContext();
1330 MCSymbol *fdeStart = context.CreateTempSymbol();
1331 MCSymbol *fdeEnd = context.CreateTempSymbol();
1332 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1333 bool verboseAsm = streamer.isVerboseAsm();
1335 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1337 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1338 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1339 streamer.EmitLabel(EHSym);
1343 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1344 if (verboseAsm) streamer.AddComment("FDE Length");
1345 streamer.EmitAbsValue(Length, 4);
1347 streamer.EmitLabel(fdeStart);
1350 const MCAsmInfo *asmInfo = context.getAsmInfo();
1352 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1354 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1355 streamer.EmitAbsValue(offset, 4);
1356 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1357 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1359 streamer.EmitAbsValue(offset, 4);
1361 streamer.EmitSymbolValue(&cieStart, 4);
1365 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1366 : (unsigned)dwarf::DW_EH_PE_absptr;
1367 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1368 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1371 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1373 if (verboseAsm) streamer.AddComment("FDE address range");
1374 streamer.EmitAbsValue(Range, PCSize);
1377 // Augmentation Data Length
1378 unsigned augmentationLength = 0;
1381 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1383 if (verboseAsm) streamer.AddComment("Augmentation size");
1384 streamer.EmitULEB128IntValue(augmentationLength);
1386 // Augmentation Data
1388 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1389 "Language Specific Data Area");
1392 // Call Frame Instructions
1393 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1396 streamer.EmitValueToAlignment(PCSize);
1403 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1404 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1406 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1407 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1408 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1409 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1410 IsSimple(IsSimple_) {
1412 const MCSymbol* Personality;
1413 unsigned PersonalityEncoding;
1414 unsigned LsdaEncoding;
1422 struct DenseMapInfo<CIEKey> {
1423 static CIEKey getEmptyKey() {
1424 return CIEKey::getEmptyKey();
1426 static CIEKey getTombstoneKey() {
1427 return CIEKey::getTombstoneKey();
1429 static unsigned getHashValue(const CIEKey &Key) {
1430 return static_cast<unsigned>(hash_combine(Key.Personality,
1431 Key.PersonalityEncoding,
1436 static bool isEqual(const CIEKey &LHS,
1437 const CIEKey &RHS) {
1438 return LHS.Personality == RHS.Personality &&
1439 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1440 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1441 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1442 LHS.IsSimple == RHS.IsSimple;
1447 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1448 bool UsingCFI, bool IsEH) {
1449 Streamer.generateCompactUnwindEncodings(MAB);
1451 MCContext &Context = Streamer.getContext();
1452 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1453 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1454 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1456 // Emit the compact unwind info if available.
1457 if (IsEH && MOFI->getCompactUnwindSection()) {
1458 bool SectionEmitted = false;
1459 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1460 const MCDwarfFrameInfo &Frame = FrameArray[i];
1461 if (Frame.CompactUnwindEncoding == 0) continue;
1462 if (!SectionEmitted) {
1463 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1464 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1465 SectionEmitted = true;
1467 Emitter.EmitCompactUnwind(Streamer, Frame);
1471 const MCSection &Section =
1472 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1473 *MOFI->getDwarfFrameSection();
1474 Streamer.SwitchSection(&Section);
1475 MCSymbol *SectionStart = Context.CreateTempSymbol();
1476 Streamer.EmitLabel(SectionStart);
1477 Emitter.setSectionStart(SectionStart);
1479 MCSymbol *FDEEnd = NULL;
1480 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1482 const MCSymbol *DummyDebugKey = NULL;
1483 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1484 const MCDwarfFrameInfo &Frame = FrameArray[i];
1485 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1486 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1487 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1489 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1490 Frame.PersonalityEncoding, Frame.Lsda,
1491 Frame.IsSignalFrame,
1495 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1498 Streamer.EmitLabel(FDEEnd);
1501 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1503 Streamer.EmitLabel(FDEEnd);
1506 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1507 uint64_t AddrDelta) {
1508 MCContext &Context = Streamer.getContext();
1509 SmallString<256> Tmp;
1510 raw_svector_ostream OS(Tmp);
1511 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1512 Streamer.EmitBytes(OS.str());
1515 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1518 // Scale the address delta by the minimum instruction length.
1519 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1521 if (AddrDelta == 0) {
1522 } else if (isUIntN(6, AddrDelta)) {
1523 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1525 } else if (isUInt<8>(AddrDelta)) {
1526 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1527 OS << uint8_t(AddrDelta);
1528 } else if (isUInt<16>(AddrDelta)) {
1529 // FIXME: check what is the correct behavior on a big endian machine.
1530 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1531 OS << uint8_t( AddrDelta & 0xff);
1532 OS << uint8_t((AddrDelta >> 8) & 0xff);
1534 // FIXME: check what is the correct behavior on a big endian machine.
1535 assert(isUInt<32>(AddrDelta));
1536 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1537 OS << uint8_t( AddrDelta & 0xff);
1538 OS << uint8_t((AddrDelta >> 8) & 0xff);
1539 OS << uint8_t((AddrDelta >> 16) & 0xff);
1540 OS << uint8_t((AddrDelta >> 24) & 0xff);