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/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCObjectFileInfo.h"
14 #include "llvm/MC/MCObjectWriter.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Config/config.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 // Define the architecture-dependent minimum instruction length (in bytes).
50 // This value should be rather too small than too big.
51 #define DWARF2_LINE_MIN_INSN_LENGTH 1
53 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
54 // this routine is a nop and will be optimized away.
55 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
56 if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
58 if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
59 // TODO: report this error, but really only once.
62 return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
66 // This is called when an instruction is assembled into the specified section
67 // and if there is information from the last .loc directive that has yet to have
68 // a line entry made for it is made.
70 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
71 if (!MCOS->getContext().getDwarfLocSeen())
74 // Create a symbol at in the current section for use in the line entry.
75 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
76 // Set the value of the symbol to use for the MCLineEntry.
77 MCOS->EmitLabel(LineSym);
79 // Get the current .loc info saved in the context.
80 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
82 // Create a (local) line entry with the symbol and the current .loc info.
83 MCLineEntry LineEntry(LineSym, DwarfLoc);
85 // clear DwarfLocSeen saying the current .loc info is now used.
86 MCOS->getContext().ClearDwarfLocSeen();
88 // Get the MCLineSection for this section, if one does not exist for this
90 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
91 MCOS->getContext().getMCLineSections();
92 MCLineSection *LineSection = MCLineSections.lookup(Section);
94 // Create a new MCLineSection. This will be deleted after the dwarf line
95 // table is created using it by iterating through the MCLineSections
97 LineSection = new MCLineSection;
98 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
99 MCOS->getContext().addMCLineSection(Section, LineSection);
102 // Add the line entry to this section's entries.
103 LineSection->addLineEntry(LineEntry);
107 // This helper routine returns an expression of End - Start + IntVal .
109 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
110 const MCSymbol &Start,
113 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
115 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
117 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
119 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
121 MCConstantExpr::Create(IntVal, MCOS.getContext());
123 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
128 // This emits the Dwarf line table for the specified section from the entries
129 // in the LineSection.
131 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
132 const MCSection *Section,
133 const MCLineSection *LineSection) {
134 unsigned FileNum = 1;
135 unsigned LastLine = 1;
137 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
139 MCSymbol *LastLabel = NULL;
141 // Loop through each MCLineEntry and encode the dwarf line number table.
142 for (MCLineSection::const_iterator
143 it = LineSection->getMCLineEntries()->begin(),
144 ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
146 if (FileNum != it->getFileNum()) {
147 FileNum = it->getFileNum();
148 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
149 MCOS->EmitULEB128IntValue(FileNum);
151 if (Column != it->getColumn()) {
152 Column = it->getColumn();
153 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
154 MCOS->EmitULEB128IntValue(Column);
156 if (Isa != it->getIsa()) {
158 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
159 MCOS->EmitULEB128IntValue(Isa);
161 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
162 Flags = it->getFlags();
163 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
165 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
166 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
167 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
168 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
169 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
170 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
172 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
173 MCSymbol *Label = it->getLabel();
175 // At this point we want to emit/create the sequence to encode the delta in
176 // line numbers and the increment of the address from the previous Label
177 // and the current Label.
178 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
179 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
180 asmInfo.getPointerSize());
182 LastLine = it->getLine();
186 // Emit a DW_LNE_end_sequence for the end of the section.
187 // Using the pointer Section create a temporary label at the end of the
188 // section and use that and the LastLabel to compute the address delta
189 // and use INT64_MAX as the line delta which is the signal that this is
190 // actually a DW_LNE_end_sequence.
192 // Switch to the section to be able to create a symbol at its end.
193 MCOS->SwitchSection(Section);
195 MCContext &context = MCOS->getContext();
196 // Create a symbol at the end of the section.
197 MCSymbol *SectionEnd = context.CreateTempSymbol();
198 // Set the value of the symbol, as we are at the end of the section.
199 MCOS->EmitLabel(SectionEnd);
201 // Switch back the the dwarf line section.
202 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
204 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
205 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
206 asmInfo.getPointerSize());
210 // This emits the Dwarf file and the line tables.
212 void MCDwarfFileTable::Emit(MCStreamer *MCOS) {
213 MCContext &context = MCOS->getContext();
214 // Switch to the section where the table will be emitted into.
215 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
217 // Create a symbol at the beginning of this section.
218 MCSymbol *LineStartSym = context.CreateTempSymbol();
219 // Set the value of the symbol, as we are at the start of the section.
220 MCOS->EmitLabel(LineStartSym);
222 // Create a symbol for the end of the section (to be set when we get there).
223 MCSymbol *LineEndSym = context.CreateTempSymbol();
225 // The first 4 bytes is the total length of the information for this
226 // compilation unit (not including these 4 bytes for the length).
227 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
230 // Next 2 bytes is the Version, which is Dwarf 2.
231 MCOS->EmitIntValue(2, 2);
233 // Create a symbol for the end of the prologue (to be set when we get there).
234 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
236 // Length of the prologue, is the next 4 bytes. Which is the start of the
237 // section to the end of the prologue. Not including the 4 bytes for the
238 // total length, the 2 bytes for the version, and these 4 bytes for the
239 // length of the prologue.
240 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
244 // Parameters of the state machine, are next.
245 MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
246 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
247 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
248 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
249 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
251 // Standard opcode lengths
252 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
253 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
254 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
255 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
256 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
257 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
258 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
259 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
260 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
261 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
262 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
263 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
265 // Put out the directory and file tables.
267 // First the directory table.
268 const std::vector<StringRef> &MCDwarfDirs =
269 context.getMCDwarfDirs();
270 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
271 MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
272 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
274 MCOS->EmitIntValue(0, 1); // Terminate the directory list
276 // Second the file table.
277 const std::vector<MCDwarfFile *> &MCDwarfFiles =
278 MCOS->getContext().getMCDwarfFiles();
279 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
280 MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
281 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
283 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
284 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
285 MCOS->EmitIntValue(0, 1); // filesize (always 0)
287 MCOS->EmitIntValue(0, 1); // Terminate the file list
289 // This is the end of the prologue, so set the value of the symbol at the
290 // end of the prologue (that was used in a previous expression).
291 MCOS->EmitLabel(ProEndSym);
293 // Put out the line tables.
294 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
295 MCOS->getContext().getMCLineSections();
296 const std::vector<const MCSection *> &MCLineSectionOrder =
297 MCOS->getContext().getMCLineSectionOrder();
298 for (std::vector<const MCSection*>::const_iterator it =
299 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
301 const MCSection *Sec = *it;
302 const MCLineSection *Line = MCLineSections.lookup(Sec);
303 EmitDwarfLineTable(MCOS, Sec, Line);
305 // Now delete the MCLineSections that were created in MCLineEntry::Make()
306 // and used to emit the line table.
310 if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
311 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
312 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
314 // total_length >= prologue_length + 10
315 // We are 4 bytes short, since we have total_length = 51 and
316 // prologue_length = 45
318 // The regular end_sequence should be sufficient.
319 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
322 // This is the end of the section, so set the value of the symbol at the end
323 // of this section (that was used in a previous expression).
324 MCOS->EmitLabel(LineEndSym);
327 /// Utility function to write the encoding to an object writer.
328 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
329 uint64_t AddrDelta) {
330 SmallString<256> Tmp;
331 raw_svector_ostream OS(Tmp);
332 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
333 OW->WriteBytes(OS.str());
336 /// Utility function to emit the encoding to a streamer.
337 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
338 uint64_t AddrDelta) {
339 SmallString<256> Tmp;
340 raw_svector_ostream OS(Tmp);
341 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
342 MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
345 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
346 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
348 uint64_t Temp, Opcode;
349 bool NeedCopy = false;
351 // Scale the address delta by the minimum instruction length.
352 AddrDelta = ScaleAddrDelta(AddrDelta);
354 // A LineDelta of INT64_MAX is a signal that this is actually a
355 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
356 // end_sequence to emit the matrix entry.
357 if (LineDelta == INT64_MAX) {
358 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
359 OS << char(dwarf::DW_LNS_const_add_pc);
361 OS << char(dwarf::DW_LNS_advance_pc);
362 MCObjectWriter::EncodeULEB128(AddrDelta, OS);
364 OS << char(dwarf::DW_LNS_extended_op);
366 OS << char(dwarf::DW_LNE_end_sequence);
370 // Bias the line delta by the base.
371 Temp = LineDelta - DWARF2_LINE_BASE;
373 // If the line increment is out of range of a special opcode, we must encode
374 // it with DW_LNS_advance_line.
375 if (Temp >= DWARF2_LINE_RANGE) {
376 OS << char(dwarf::DW_LNS_advance_line);
377 MCObjectWriter::EncodeSLEB128(LineDelta, OS);
380 Temp = 0 - DWARF2_LINE_BASE;
384 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
385 if (LineDelta == 0 && AddrDelta == 0) {
386 OS << char(dwarf::DW_LNS_copy);
390 // Bias the opcode by the special opcode base.
391 Temp += DWARF2_LINE_OPCODE_BASE;
393 // Avoid overflow when addr_delta is large.
394 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
395 // Try using a special opcode.
396 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
402 // Try using DW_LNS_const_add_pc followed by special op.
403 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
405 OS << char(dwarf::DW_LNS_const_add_pc);
411 // Otherwise use DW_LNS_advance_pc.
412 OS << char(dwarf::DW_LNS_advance_pc);
413 MCObjectWriter::EncodeULEB128(AddrDelta, OS);
416 OS << char(dwarf::DW_LNS_copy);
421 void MCDwarfFile::print(raw_ostream &OS) const {
422 OS << '"' << getName() << '"';
425 void MCDwarfFile::dump() const {
429 // Utility function to write a tuple for .debug_abbrev.
430 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
431 MCOS->EmitULEB128IntValue(Name);
432 MCOS->EmitULEB128IntValue(Form);
435 // When generating dwarf for assembly source files this emits
436 // the data for .debug_abbrev section which contains three DIEs.
437 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
438 MCContext &context = MCOS->getContext();
439 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
441 // DW_TAG_compile_unit DIE abbrev (1).
442 MCOS->EmitULEB128IntValue(1);
443 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
444 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
445 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
446 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
447 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
448 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
449 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
450 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
451 if (!DwarfDebugFlags.empty())
452 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
453 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
454 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
455 EmitAbbrev(MCOS, 0, 0);
457 // DW_TAG_subprogram DIE abbrev (2).
458 MCOS->EmitULEB128IntValue(2);
459 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_subprogram);
460 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
461 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
462 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
463 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
464 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
465 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
466 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
467 EmitAbbrev(MCOS, 0, 0);
469 // DW_TAG_unspecified_parameters DIE abbrev (3).
470 MCOS->EmitULEB128IntValue(3);
471 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
472 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
473 EmitAbbrev(MCOS, 0, 0);
475 // Terminate the abbreviations for this compilation unit.
476 MCOS->EmitIntValue(0, 1);
479 // When generating dwarf for assembly source files this emits the data for
480 // .debug_aranges section. Which contains a header and a table of pairs of
481 // PointerSize'ed values for the address and size of section(s) with line table
482 // entries (just the default .text in our case) and a terminating pair of zeros.
483 static void EmitGenDwarfAranges(MCStreamer *MCOS) {
484 MCContext &context = MCOS->getContext();
486 // Create a symbol at the end of the section that we are creating the dwarf
487 // debugging info to use later in here as part of the expression to calculate
488 // the size of the section for the table.
489 MCOS->SwitchSection(context.getGenDwarfSection());
490 MCSymbol *SectionEndSym = context.CreateTempSymbol();
491 MCOS->EmitLabel(SectionEndSym);
492 context.setGenDwarfSectionEndSym(SectionEndSym);
494 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
496 // This will be the length of the .debug_aranges section, first account for
497 // the size of each item in the header (see below where we emit these items).
498 int Length = 4 + 2 + 4 + 1 + 1;
500 // Figure the padding after the header before the table of address and size
501 // pairs who's values are PointerSize'ed.
502 const MCAsmInfo &asmInfo = context.getAsmInfo();
503 int AddrSize = asmInfo.getPointerSize();
504 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
505 if (Pad == 2 * AddrSize)
509 // Add the size of the pair of PointerSize'ed values for the address and size
510 // of the one default .text section we have in the table.
511 Length += 2 * AddrSize;
512 // And the pair of terminating zeros.
513 Length += 2 * AddrSize;
516 // Emit the header for this section.
517 // The 4 byte length not including the 4 byte value for the length.
518 MCOS->EmitIntValue(Length - 4, 4);
519 // The 2 byte version, which is 2.
520 MCOS->EmitIntValue(2, 2);
521 // The 4 byte offset to the compile unit in the .debug_info from the start
522 // of the .debug_info, it is at the start of that section so this is zero.
523 MCOS->EmitIntValue(0, 4);
524 // The 1 byte size of an address.
525 MCOS->EmitIntValue(AddrSize, 1);
526 // The 1 byte size of a segment descriptor, we use a value of zero.
527 MCOS->EmitIntValue(0, 1);
528 // Align the header with the padding if needed, before we put out the table.
529 for(int i = 0; i < Pad; i++)
530 MCOS->EmitIntValue(0, 1);
532 // Now emit the table of pairs of PointerSize'ed values for the section(s)
533 // address and size, in our case just the one default .text section.
534 const MCExpr *Addr = MCSymbolRefExpr::Create(
535 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
536 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
537 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
538 MCOS->EmitAbsValue(Addr, AddrSize);
539 MCOS->EmitAbsValue(Size, AddrSize);
541 // And finally the pair of terminating zeros.
542 MCOS->EmitIntValue(0, AddrSize);
543 MCOS->EmitIntValue(0, AddrSize);
546 // When generating dwarf for assembly source files this emits the data for
547 // .debug_info section which contains three parts. The header, the compile_unit
548 // DIE and a list of subprogram DIEs.
549 static void EmitGenDwarfInfo(MCStreamer *MCOS) {
550 MCContext &context = MCOS->getContext();
552 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
554 // Create a symbol at the start and end of this section used in here for the
555 // expression to calculate the length in the header.
556 MCSymbol *InfoStart = context.CreateTempSymbol();
557 MCOS->EmitLabel(InfoStart);
558 MCSymbol *InfoEnd = context.CreateTempSymbol();
560 // First part: the header.
562 // The 4 byte total length of the information for this compilation unit, not
563 // including these 4 bytes.
564 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
565 MCOS->EmitAbsValue(Length, 4);
567 // The 2 byte DWARF version, which is 2.
568 MCOS->EmitIntValue(2, 2);
570 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
571 // it is at the start of that section so this is zero.
572 MCOS->EmitIntValue(0, 4);
574 const MCAsmInfo &asmInfo = context.getAsmInfo();
575 int AddrSize = asmInfo.getPointerSize();
576 // The 1 byte size of an address.
577 MCOS->EmitIntValue(AddrSize, 1);
579 // Second part: the compile_unit DIE.
581 // The DW_TAG_compile_unit DIE abbrev (1).
582 MCOS->EmitULEB128IntValue(1);
584 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
585 // which is at the start of that section so this is zero.
586 MCOS->EmitIntValue(0, 4);
588 // AT_low_pc, the first address of the default .text section.
589 const MCExpr *Start = MCSymbolRefExpr::Create(
590 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
591 MCOS->EmitAbsValue(Start, AddrSize);
593 // AT_high_pc, the last address of the default .text section.
594 const MCExpr *End = MCSymbolRefExpr::Create(
595 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
596 MCOS->EmitAbsValue(End, AddrSize);
598 // AT_name, the name of the source file. Reconstruct from the first directory
599 // and file table entries.
600 const std::vector<StringRef> &MCDwarfDirs =
601 context.getMCDwarfDirs();
602 if (MCDwarfDirs.size() > 0) {
603 MCOS->EmitBytes(MCDwarfDirs[0], 0);
604 MCOS->EmitBytes("/", 0);
606 const std::vector<MCDwarfFile *> &MCDwarfFiles =
607 MCOS->getContext().getMCDwarfFiles();
608 MCOS->EmitBytes(MCDwarfFiles[1]->getName(), 0);
609 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
611 // AT_comp_dir, the working directory the assembly was done in.
612 llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
613 MCOS->EmitBytes(StringRef(CWD.c_str()), 0);
614 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
616 // AT_APPLE_flags, the command line arguments of the assembler tool.
617 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
618 if (!DwarfDebugFlags.empty()){
619 MCOS->EmitBytes(DwarfDebugFlags, 0);
620 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
623 // AT_producer, the version of the assembler tool.
624 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "), 0);
625 MCOS->EmitBytes(StringRef(PACKAGE_VERSION), 0);
626 MCOS->EmitBytes(StringRef(")"), 0);
627 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
629 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
630 // draft has no standard code for assembler.
631 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
633 // Third part: the list of subprogram DIEs.
635 // Loop on saved info for dwarf subprograms and create the DIEs for them.
636 const std::vector<const MCGenDwarfSubprogramEntry *> &Entries =
637 MCOS->getContext().getMCGenDwarfSubprogramEntries();
638 for (std::vector<const MCGenDwarfSubprogramEntry *>::const_iterator it =
639 Entries.begin(), ie = Entries.end(); it != ie;
641 const MCGenDwarfSubprogramEntry *Entry = *it;
643 // The DW_TAG_subprogram DIE abbrev (2).
644 MCOS->EmitULEB128IntValue(2);
646 // AT_name, of the label without any leading underbar.
647 MCOS->EmitBytes(Entry->getName(), 0);
648 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
650 // AT_decl_file, index into the file table.
651 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
653 // AT_decl_line, source line number.
654 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
656 // AT_low_pc, start address of the label.
657 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
658 MCSymbolRefExpr::VK_None, context);
659 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
661 // AT_high_pc, end address which is the next label or end of the section.
662 std::vector<const MCGenDwarfSubprogramEntry *>::const_iterator next = it+1;
663 if (next != Entries.end()){
664 const MCGenDwarfSubprogramEntry *NextEntry = *next;
665 const MCExpr *AT_high_pc = MCSymbolRefExpr::Create(NextEntry->getLabel(),
666 MCSymbolRefExpr::VK_None, context);
667 MCOS->EmitAbsValue(AT_high_pc, AddrSize);
669 MCOS->EmitAbsValue(End, AddrSize);
672 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
673 MCOS->EmitIntValue(0, 1);
675 // The DW_TAG_unspecified_parameters DIE abbrev (3).
676 MCOS->EmitULEB128IntValue(3);
678 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
679 MCOS->EmitIntValue(0, 1);
681 // Deallocate the MCGenDwarfSubprogramEntry classes that saved away the info
682 // for the dwarf subprograms.
683 for (std::vector<const MCGenDwarfSubprogramEntry *>::const_iterator it =
684 Entries.begin(), ie = Entries.end(); it != ie;
686 const MCGenDwarfSubprogramEntry *Entry = *it;
690 // Add the NULL DIE terminating the Compile Unit DIE's.
691 MCOS->EmitIntValue(0, 1);
693 // Now set the value of the symbol at the end of the info section.
694 MCOS->EmitLabel(InfoEnd);
698 // When generating dwarf for assembly source files this emits the Dwarf
701 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
702 // Create the dwarf sections in this order (.debug_line already created).
703 MCContext &context = MCOS->getContext();
704 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
705 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
706 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
708 // If there are no line table entries then do not emit any section contents.
709 if (context.getMCLineSections().empty())
712 // Output the data for .debug_aranges section.
713 EmitGenDwarfAranges(MCOS);
715 // Output the data for .debug_abbrev section.
716 EmitGenDwarfAbbrev(MCOS);
718 // Output the data for .debug_info section.
719 EmitGenDwarfInfo(MCOS);
723 // When generating dwarf for assembly source files this is called when symbol
724 // for a label is created. If this symbol is not a temporary and is in the
725 // section that dwarf is being generated for, save the needed info to create
726 // a dwarf subprogram.
728 void MCGenDwarfSubprogramEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
729 SourceMgr &SrcMgr, SMLoc &Loc) {
730 // We won't create dwarf subprogram's for temporary symbols or symbols not in
732 if (Symbol->isTemporary())
734 MCContext &context = MCOS->getContext();
735 if (context.getGenDwarfSection() != MCOS->getCurrentSection())
738 // The dwarf subprogram's name does not have the symbol name's leading
740 StringRef Name = Symbol->getName();
741 if (Name.startswith("_"))
742 Name = Name.substr(1, Name.size()-1);
744 // Get the dwarf file number to be used for the dwarf subprogram.
745 unsigned FileNumber = context.getGenDwarfFileNumber();
747 // Finding the line number is the expensive part which is why we just don't
748 // pass it in as for some symbols we won't create a dwarf subprogram.
749 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
750 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
752 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
753 // values so that they don't have things like an ARM thumb bit from the
754 // original symbol. So when used they won't get a low bit set after
756 MCSymbol *Label = context.CreateTempSymbol();
757 MCOS->EmitLabel(Label);
759 // Create and entry for the info and add it to the other entries.
760 MCGenDwarfSubprogramEntry *Entry =
761 new MCGenDwarfSubprogramEntry(Name, FileNumber, LineNumber, Label);
762 MCOS->getContext().addMCGenDwarfSubprogramEntry(Entry);
765 static int getDataAlignmentFactor(MCStreamer &streamer) {
766 MCContext &context = streamer.getContext();
767 const MCAsmInfo &asmInfo = context.getAsmInfo();
768 int size = asmInfo.getPointerSize();
769 if (asmInfo.isStackGrowthDirectionUp())
775 static unsigned getSizeForEncoding(MCStreamer &streamer,
776 unsigned symbolEncoding) {
777 MCContext &context = streamer.getContext();
778 unsigned format = symbolEncoding & 0x0f;
781 assert(0 && "Unknown Encoding");
782 case dwarf::DW_EH_PE_absptr:
783 case dwarf::DW_EH_PE_signed:
784 return context.getAsmInfo().getPointerSize();
785 case dwarf::DW_EH_PE_udata2:
786 case dwarf::DW_EH_PE_sdata2:
788 case dwarf::DW_EH_PE_udata4:
789 case dwarf::DW_EH_PE_sdata4:
791 case dwarf::DW_EH_PE_udata8:
792 case dwarf::DW_EH_PE_sdata8:
797 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
798 unsigned symbolEncoding, const char *comment = 0) {
799 MCContext &context = streamer.getContext();
800 const MCAsmInfo &asmInfo = context.getAsmInfo();
801 const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
804 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
805 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
806 streamer.EmitAbsValue(v, size);
809 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
810 unsigned symbolEncoding) {
811 MCContext &context = streamer.getContext();
812 const MCAsmInfo &asmInfo = context.getAsmInfo();
813 const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
816 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
817 streamer.EmitValue(v, size);
820 static const MachineLocation TranslateMachineLocation(
821 const MCRegisterInfo &MRI,
822 const MachineLocation &Loc) {
823 unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
824 MachineLocation::VirtualFP :
825 unsigned(MRI.getDwarfRegNum(Loc.getReg(), true));
826 const MachineLocation &NewLoc = Loc.isReg() ?
827 MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
832 class FrameEmitterImpl {
837 const MCSymbol *SectionStart;
839 FrameEmitterImpl(bool usingCFI, bool isEH)
840 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
843 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
845 /// EmitCompactUnwind - Emit the unwind information in a compact way. If
846 /// we're successful, return 'true'. Otherwise, return 'false' and it will
847 /// emit the normal CIE and FDE.
848 bool EmitCompactUnwind(MCStreamer &streamer,
849 const MCDwarfFrameInfo &frame);
851 const MCSymbol &EmitCIE(MCStreamer &streamer,
852 const MCSymbol *personality,
853 unsigned personalityEncoding,
854 const MCSymbol *lsda,
855 unsigned lsdaEncoding);
856 MCSymbol *EmitFDE(MCStreamer &streamer,
857 const MCSymbol &cieStart,
858 const MCDwarfFrameInfo &frame);
859 void EmitCFIInstructions(MCStreamer &streamer,
860 const std::vector<MCCFIInstruction> &Instrs,
861 MCSymbol *BaseLabel);
862 void EmitCFIInstruction(MCStreamer &Streamer,
863 const MCCFIInstruction &Instr);
866 } // end anonymous namespace
868 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
870 if (Streamer.isVerboseAsm()) {
871 const char *EncStr = 0;
873 default: EncStr = "<unknown encoding>";
874 case dwarf::DW_EH_PE_absptr: EncStr = "absptr";
875 case dwarf::DW_EH_PE_omit: EncStr = "omit";
876 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel";
877 case dwarf::DW_EH_PE_udata4: EncStr = "udata4";
878 case dwarf::DW_EH_PE_udata8: EncStr = "udata8";
879 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4";
880 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8";
881 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: EncStr = "pcrel udata4";
882 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: EncStr = "pcrel sdata4";
883 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: EncStr = "pcrel udata8";
884 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: EncStr = "pcrel sdata8";
885 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
886 EncStr = "indirect pcrel udata4";
887 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
888 EncStr = "indirect pcrel sdata4";
889 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
890 EncStr = "indirect pcrel udata8";
891 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
892 EncStr = "indirect pcrel sdata8";
895 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
898 Streamer.EmitIntValue(Encoding, 1);
901 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
902 const MCCFIInstruction &Instr) {
903 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
904 bool VerboseAsm = Streamer.isVerboseAsm();
906 switch (Instr.getOperation()) {
907 case MCCFIInstruction::Move:
908 case MCCFIInstruction::RelMove: {
909 const MachineLocation &Dst = Instr.getDestination();
910 const MachineLocation &Src = Instr.getSource();
911 const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
914 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
915 if (Src.getReg() == MachineLocation::VirtualFP) {
916 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
917 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
919 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
920 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
921 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
922 Twine(Src.getReg()));
923 Streamer.EmitULEB128IntValue(Src.getReg());
927 CFAOffset += Src.getOffset();
929 CFAOffset = -Src.getOffset();
931 if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
932 Streamer.EmitULEB128IntValue(CFAOffset);
936 if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
937 assert(Dst.isReg() && "Machine move not supported yet.");
938 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
939 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
940 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
941 Streamer.EmitULEB128IntValue(Dst.getReg());
945 unsigned Reg = Src.getReg();
946 int Offset = Dst.getOffset();
949 Offset = Offset / dataAlignmentFactor;
952 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
953 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
954 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
955 Streamer.EmitULEB128IntValue(Reg);
956 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
957 Streamer.EmitSLEB128IntValue(Offset);
958 } else if (Reg < 64) {
959 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
961 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
962 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
963 Streamer.EmitULEB128IntValue(Offset);
965 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
966 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
967 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
968 Streamer.EmitULEB128IntValue(Reg);
969 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
970 Streamer.EmitULEB128IntValue(Offset);
974 case MCCFIInstruction::Remember:
975 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
976 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
978 case MCCFIInstruction::Restore:
979 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
980 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
982 case MCCFIInstruction::SameValue: {
983 unsigned Reg = Instr.getDestination().getReg();
984 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
985 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
986 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
987 Streamer.EmitULEB128IntValue(Reg);
991 llvm_unreachable("Unhandled case in switch");
994 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
996 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
997 const std::vector<MCCFIInstruction> &Instrs,
998 MCSymbol *BaseLabel) {
999 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1000 const MCCFIInstruction &Instr = Instrs[i];
1001 MCSymbol *Label = Instr.getLabel();
1002 // Throw out move if the label is invalid.
1003 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1005 // Advance row if new location.
1006 if (BaseLabel && Label) {
1007 MCSymbol *ThisSym = Label;
1008 if (ThisSym != BaseLabel) {
1009 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1010 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1011 BaseLabel = ThisSym;
1015 EmitCFIInstruction(streamer, Instr);
1019 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
1020 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
1021 /// normal CIE and FDE.
1022 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1023 const MCDwarfFrameInfo &Frame) {
1024 MCContext &Context = Streamer.getContext();
1025 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1026 bool VerboseAsm = Streamer.isVerboseAsm();
1028 // range-start range-length compact-unwind-enc personality-func lsda
1029 // _foo LfooEnd-_foo 0x00000023 0 0
1030 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1032 // .section __LD,__compact_unwind,regular,debug
1034 // # compact unwind for _foo
1036 // .set L1,LfooEnd-_foo
1042 // # compact unwind for _bar
1044 // .set L2,LbarEnd-_bar
1047 // .quad __gxx_personality
1048 // .quad except_tab1
1050 uint32_t Encoding = Frame.CompactUnwindEncoding;
1051 if (!Encoding) return false;
1053 // The encoding needs to know we have an LSDA.
1055 Encoding |= 0x40000000;
1057 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1060 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1061 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1062 if (VerboseAsm) Streamer.AddComment("Range Start");
1063 Streamer.EmitSymbolValue(Frame.Function, Size);
1066 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1068 if (VerboseAsm) Streamer.AddComment("Range Length");
1069 Streamer.EmitAbsValue(Range, 4);
1072 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1073 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1074 Twine::utohexstr(Encoding));
1075 Streamer.EmitIntValue(Encoding, Size);
1078 // Personality Function
1079 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1080 if (VerboseAsm) Streamer.AddComment("Personality Function");
1081 if (Frame.Personality)
1082 Streamer.EmitSymbolValue(Frame.Personality, Size);
1084 Streamer.EmitIntValue(0, Size); // No personality fn
1087 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1088 if (VerboseAsm) Streamer.AddComment("LSDA");
1090 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1092 Streamer.EmitIntValue(0, Size); // No LSDA
1097 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1098 const MCSymbol *personality,
1099 unsigned personalityEncoding,
1100 const MCSymbol *lsda,
1101 unsigned lsdaEncoding) {
1102 MCContext &context = streamer.getContext();
1103 const MCRegisterInfo &MRI = context.getRegisterInfo();
1104 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1105 bool verboseAsm = streamer.isVerboseAsm();
1107 MCSymbol *sectionStart;
1108 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1109 sectionStart = context.CreateTempSymbol();
1111 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1113 streamer.EmitLabel(sectionStart);
1116 MCSymbol *sectionEnd = context.CreateTempSymbol();
1119 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1121 if (verboseAsm) streamer.AddComment("CIE Length");
1122 streamer.EmitAbsValue(Length, 4);
1125 unsigned CIE_ID = IsEH ? 0 : -1;
1126 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1127 streamer.EmitIntValue(CIE_ID, 4);
1130 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1131 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1133 // Augmentation String
1134 SmallString<8> Augmentation;
1136 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1137 Augmentation += "z";
1139 Augmentation += "P";
1141 Augmentation += "L";
1142 Augmentation += "R";
1143 streamer.EmitBytes(Augmentation.str(), 0);
1145 streamer.EmitIntValue(0, 1);
1147 // Code Alignment Factor
1148 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1149 streamer.EmitULEB128IntValue(1);
1151 // Data Alignment Factor
1152 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1153 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1155 // Return Address Register
1156 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1157 streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true));
1159 // Augmentation Data Length (optional)
1161 unsigned augmentationLength = 0;
1164 // Personality Encoding
1165 augmentationLength += 1;
1167 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1170 augmentationLength += 1;
1171 // Encoding of the FDE pointers
1172 augmentationLength += 1;
1174 if (verboseAsm) streamer.AddComment("Augmentation Size");
1175 streamer.EmitULEB128IntValue(augmentationLength);
1177 // Augmentation Data (optional)
1179 // Personality Encoding
1180 EmitEncodingByte(streamer, personalityEncoding,
1181 "Personality Encoding");
1183 if (verboseAsm) streamer.AddComment("Personality");
1184 EmitPersonality(streamer, *personality, personalityEncoding);
1188 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1190 // Encoding of the FDE pointers
1191 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1195 // Initial Instructions
1197 const MCAsmInfo &MAI = context.getAsmInfo();
1198 const std::vector<MachineMove> &Moves = MAI.getInitialFrameState();
1199 std::vector<MCCFIInstruction> Instructions;
1201 for (int i = 0, n = Moves.size(); i != n; ++i) {
1202 MCSymbol *Label = Moves[i].getLabel();
1203 const MachineLocation &Dst =
1204 TranslateMachineLocation(MRI, Moves[i].getDestination());
1205 const MachineLocation &Src =
1206 TranslateMachineLocation(MRI, Moves[i].getSource());
1207 MCCFIInstruction Inst(Label, Dst, Src);
1208 Instructions.push_back(Inst);
1211 EmitCFIInstructions(streamer, Instructions, NULL);
1214 streamer.EmitValueToAlignment(IsEH
1215 ? 4 : context.getAsmInfo().getPointerSize());
1217 streamer.EmitLabel(sectionEnd);
1218 return *sectionStart;
1221 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1222 const MCSymbol &cieStart,
1223 const MCDwarfFrameInfo &frame) {
1224 MCContext &context = streamer.getContext();
1225 MCSymbol *fdeStart = context.CreateTempSymbol();
1226 MCSymbol *fdeEnd = context.CreateTempSymbol();
1227 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1228 bool verboseAsm = streamer.isVerboseAsm();
1230 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1232 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1233 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1234 streamer.EmitLabel(EHSym);
1238 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1239 if (verboseAsm) streamer.AddComment("FDE Length");
1240 streamer.EmitAbsValue(Length, 4);
1242 streamer.EmitLabel(fdeStart);
1245 const MCAsmInfo &asmInfo = context.getAsmInfo();
1247 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1249 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1250 streamer.EmitAbsValue(offset, 4);
1251 } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
1252 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1254 streamer.EmitAbsValue(offset, 4);
1256 streamer.EmitSymbolValue(&cieStart, 4);
1259 unsigned fdeEncoding = MOFI->getFDEEncoding(UsingCFI);
1260 unsigned size = getSizeForEncoding(streamer, fdeEncoding);
1263 unsigned PCBeginEncoding = IsEH ? fdeEncoding :
1264 (unsigned)dwarf::DW_EH_PE_absptr;
1265 unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
1266 EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location");
1269 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1271 if (verboseAsm) streamer.AddComment("FDE address range");
1272 streamer.EmitAbsValue(Range, size);
1275 // Augmentation Data Length
1276 unsigned augmentationLength = 0;
1279 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1281 if (verboseAsm) streamer.AddComment("Augmentation size");
1282 streamer.EmitULEB128IntValue(augmentationLength);
1284 // Augmentation Data
1286 EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding,
1287 "Language Specific Data Area");
1290 // Call Frame Instructions
1292 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1295 streamer.EmitValueToAlignment(PCBeginSize);
1302 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1); }
1303 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0); }
1305 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1306 unsigned LsdaEncoding_) : Personality(Personality_),
1307 PersonalityEncoding(PersonalityEncoding_),
1308 LsdaEncoding(LsdaEncoding_) {
1310 const MCSymbol* Personality;
1311 unsigned PersonalityEncoding;
1312 unsigned LsdaEncoding;
1318 struct DenseMapInfo<CIEKey> {
1319 static CIEKey getEmptyKey() {
1320 return CIEKey::getEmptyKey();
1322 static CIEKey getTombstoneKey() {
1323 return CIEKey::getTombstoneKey();
1325 static unsigned getHashValue(const CIEKey &Key) {
1326 FoldingSetNodeID ID;
1327 ID.AddPointer(Key.Personality);
1328 ID.AddInteger(Key.PersonalityEncoding);
1329 ID.AddInteger(Key.LsdaEncoding);
1330 return ID.ComputeHash();
1332 static bool isEqual(const CIEKey &LHS,
1333 const CIEKey &RHS) {
1334 return LHS.Personality == RHS.Personality &&
1335 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1336 LHS.LsdaEncoding == RHS.LsdaEncoding;
1341 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
1344 MCContext &Context = Streamer.getContext();
1345 MCObjectFileInfo *MOFI =
1346 const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo());
1347 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1348 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1350 // Emit the compact unwind info if available.
1351 if (IsEH && MOFI->getCompactUnwindSection())
1352 for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
1353 const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
1354 if (Frame.CompactUnwindEncoding)
1355 Emitter.EmitCompactUnwind(Streamer, Frame);
1358 const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() :
1359 *MOFI->getDwarfFrameSection();
1360 Streamer.SwitchSection(&Section);
1361 MCSymbol *SectionStart = Context.CreateTempSymbol();
1362 Streamer.EmitLabel(SectionStart);
1363 Emitter.setSectionStart(SectionStart);
1365 MCSymbol *FDEEnd = NULL;
1366 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1368 const MCSymbol *DummyDebugKey = NULL;
1369 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1370 const MCDwarfFrameInfo &Frame = FrameArray[i];
1371 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1372 Frame.LsdaEncoding);
1373 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1375 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1376 Frame.PersonalityEncoding, Frame.Lsda,
1377 Frame.LsdaEncoding);
1379 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1382 Streamer.EmitLabel(FDEEnd);
1385 Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize());
1387 Streamer.EmitLabel(FDEEnd);
1390 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1391 uint64_t AddrDelta) {
1392 SmallString<256> Tmp;
1393 raw_svector_ostream OS(Tmp);
1394 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
1395 Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
1398 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
1400 // FIXME: Assumes the code alignment factor is 1.
1401 if (AddrDelta == 0) {
1402 } else if (isUIntN(6, AddrDelta)) {
1403 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1405 } else if (isUInt<8>(AddrDelta)) {
1406 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1407 OS << uint8_t(AddrDelta);
1408 } else if (isUInt<16>(AddrDelta)) {
1409 // FIXME: check what is the correct behavior on a big endian machine.
1410 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1411 OS << uint8_t( AddrDelta & 0xff);
1412 OS << uint8_t((AddrDelta >> 8) & 0xff);
1414 // FIXME: check what is the correct behavior on a big endian machine.
1415 assert(isUInt<32>(AddrDelta));
1416 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1417 OS << uint8_t( AddrDelta & 0xff);
1418 OS << uint8_t((AddrDelta >> 8) & 0xff);
1419 OS << uint8_t((AddrDelta >> 16) & 0xff);
1420 OS << uint8_t((AddrDelta >> 24) & 0xff);