1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCDwarf.h"
11 #include "llvm/ADT/Hashing.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/Config/config.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectFileInfo.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
30 // Given a special op, return the address skip amount (in units of
31 // DWARF2_LINE_MIN_INSN_LENGTH.
32 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
34 // The maximum address skip amount that can be encoded with a special op.
35 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
37 // First special line opcode - leave room for the standard opcodes.
38 // Note: If you want to change this, you'll have to update the
39 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
40 #define DWARF2_LINE_OPCODE_BASE 13
42 // Minimum line offset in a special line info. opcode. This value
43 // was chosen to give a reasonable range of values.
44 #define DWARF2_LINE_BASE -5
46 // Range of line offsets in a special line info. opcode.
47 #define DWARF2_LINE_RANGE 14
49 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
50 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
51 if (MinInsnLength == 1)
53 if (AddrDelta % MinInsnLength != 0) {
54 // TODO: report this error, but really only once.
57 return AddrDelta / MinInsnLength;
61 // This is called when an instruction is assembled into the specified section
62 // and if there is information from the last .loc directive that has yet to have
63 // a line entry made for it is made.
65 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
66 if (!MCOS->getContext().getDwarfLocSeen())
69 // Create a symbol at in the current section for use in the line entry.
70 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
71 // Set the value of the symbol to use for the MCLineEntry.
72 MCOS->EmitLabel(LineSym);
74 // Get the current .loc info saved in the context.
75 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
77 // Create a (local) line entry with the symbol and the current .loc info.
78 MCLineEntry LineEntry(LineSym, DwarfLoc);
80 // clear DwarfLocSeen saying the current .loc info is now used.
81 MCOS->getContext().ClearDwarfLocSeen();
83 // Add the line entry to this section's entries.
85 .getMCLineSections()[MCOS->getContext().getDwarfCompileUnitID()]
86 .addLineEntry(LineEntry, Section);
90 // This helper routine returns an expression of End - Start + IntVal .
92 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
93 const MCSymbol &Start,
96 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
98 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
100 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
102 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
104 MCConstantExpr::Create(IntVal, MCOS.getContext());
106 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
111 // This emits the Dwarf line table for the specified section from the entries
112 // in the LineSection.
115 EmitDwarfLineTable(MCStreamer *MCOS, const MCSection *Section,
116 const MCLineSection::MCLineEntryCollection &LineEntries) {
117 unsigned FileNum = 1;
118 unsigned LastLine = 1;
120 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
122 unsigned Discriminator = 0;
123 MCSymbol *LastLabel = NULL;
125 // Loop through each MCLineEntry and encode the dwarf line number table.
126 for (auto it = LineEntries.begin(),
127 ie = LineEntries.end();
130 if (FileNum != it->getFileNum()) {
131 FileNum = it->getFileNum();
132 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
133 MCOS->EmitULEB128IntValue(FileNum);
135 if (Column != it->getColumn()) {
136 Column = it->getColumn();
137 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
138 MCOS->EmitULEB128IntValue(Column);
140 if (Discriminator != it->getDiscriminator()) {
141 Discriminator = it->getDiscriminator();
142 unsigned Size = getULEB128Size(Discriminator);
143 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
144 MCOS->EmitULEB128IntValue(Size + 1);
145 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
146 MCOS->EmitULEB128IntValue(Discriminator);
148 if (Isa != it->getIsa()) {
150 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
151 MCOS->EmitULEB128IntValue(Isa);
153 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
154 Flags = it->getFlags();
155 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
157 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
158 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
159 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
160 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
161 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
162 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
164 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
165 MCSymbol *Label = it->getLabel();
167 // At this point we want to emit/create the sequence to encode the delta in
168 // line numbers and the increment of the address from the previous Label
169 // and the current Label.
170 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
171 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
172 asmInfo->getPointerSize());
174 LastLine = it->getLine();
178 // Emit a DW_LNE_end_sequence for the end of the section.
179 // Using the pointer Section create a temporary label at the end of the
180 // section and use that and the LastLabel to compute the address delta
181 // and use INT64_MAX as the line delta which is the signal that this is
182 // actually a DW_LNE_end_sequence.
184 // Switch to the section to be able to create a symbol at its end.
185 // TODO: keep track of the last subsection so that this symbol appears in the
187 MCOS->SwitchSection(Section);
189 MCContext &context = MCOS->getContext();
190 // Create a symbol at the end of the section.
191 MCSymbol *SectionEnd = context.CreateTempSymbol();
192 // Set the value of the symbol, as we are at the end of the section.
193 MCOS->EmitLabel(SectionEnd);
195 // Switch back the dwarf line section.
196 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
198 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
199 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
200 asmInfo->getPointerSize());
204 // This emits the Dwarf file and the line tables.
206 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
207 MCContext &context = MCOS->getContext();
208 // Switch to the section where the table will be emitted into.
209 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
211 const DenseMap<unsigned, MCSymbol *> &MCLineTableSymbols =
212 MCOS->getContext().getMCLineTableSymbols();
213 // CUID and MCLineTableSymbols are set in DwarfDebug, when DwarfDebug does
214 // not exist, CUID will be 0 and MCLineTableSymbols will be empty.
215 // Handle Compile Unit 0, the line table start symbol is the section symbol.
216 const MCSymbol *LineStartSym = EmitCU(MCOS, 0);
217 // Handle the rest of the Compile Units.
218 for (unsigned Is = 1, Ie = MCLineTableSymbols.size(); Is < Ie; Is++)
224 const MCSymbol *MCDwarfFileTable::EmitCU(MCStreamer *MCOS, unsigned CUID) {
225 MCContext &context = MCOS->getContext();
227 // Create a symbol at the beginning of the line table.
228 MCSymbol *LineStartSym = MCOS->getContext().getMCLineTableSymbol(CUID);
230 LineStartSym = context.CreateTempSymbol();
231 // Set the value of the symbol, as we are at the start of the line table.
232 MCOS->EmitLabel(LineStartSym);
234 // Create a symbol for the end of the section (to be set when we get there).
235 MCSymbol *LineEndSym = context.CreateTempSymbol();
237 // The first 4 bytes is the total length of the information for this
238 // compilation unit (not including these 4 bytes for the length).
239 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
242 // Next 2 bytes is the Version, which is Dwarf 2.
243 MCOS->EmitIntValue(2, 2);
245 // Create a symbol for the end of the prologue (to be set when we get there).
246 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
248 // Length of the prologue, is the next 4 bytes. Which is the start of the
249 // section to the end of the prologue. Not including the 4 bytes for the
250 // total length, the 2 bytes for the version, and these 4 bytes for the
251 // length of the prologue.
252 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
255 // Parameters of the state machine, are next.
256 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
257 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
258 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
259 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
260 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
262 // Standard opcode lengths
263 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
264 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
265 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
266 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
267 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
268 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
269 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
270 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
271 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
272 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
273 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
274 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
276 // Put out the directory and file tables.
278 // First the directory table.
279 const SmallVectorImpl<StringRef> &MCDwarfDirs =
280 context.getMCDwarfDirs(CUID);
281 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
282 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
283 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
285 MCOS->EmitIntValue(0, 1); // Terminate the directory list
287 // Second the file table.
288 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
289 MCOS->getContext().getMCDwarfFiles(CUID);
290 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
291 MCOS->EmitBytes(MCDwarfFiles[i]->getName()); // FileName
292 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
294 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
295 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
296 MCOS->EmitIntValue(0, 1); // filesize (always 0)
298 MCOS->EmitIntValue(0, 1); // Terminate the file list
300 // This is the end of the prologue, so set the value of the symbol at the
301 // end of the prologue (that was used in a previous expression).
302 MCOS->EmitLabel(ProEndSym);
304 // Put out the line tables.
305 const std::map<unsigned, MCLineSection> &MCLineSections =
306 MCOS->getContext().getMCLineSections();
307 auto Iter = MCLineSections.find(CUID);
308 if (Iter != MCLineSections.end())
309 for (const auto &LineSec : Iter->second.getMCLineEntries())
310 EmitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
312 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines() &&
313 Iter == MCLineSections.end()) {
314 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
316 // total_length >= prologue_length + 10
317 // We are 4 bytes short, since we have total_length = 51 and
318 // prologue_length = 45
320 // The regular end_sequence should be sufficient.
321 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
324 // This is the end of the section, so set the value of the symbol at the end
325 // of this section (that was used in a previous expression).
326 MCOS->EmitLabel(LineEndSym);
331 /// Utility function to emit the encoding to a streamer.
332 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
333 uint64_t AddrDelta) {
334 MCContext &Context = MCOS->getContext();
335 SmallString<256> Tmp;
336 raw_svector_ostream OS(Tmp);
337 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
338 MCOS->EmitBytes(OS.str());
341 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
342 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
343 uint64_t AddrDelta, raw_ostream &OS) {
344 uint64_t Temp, Opcode;
345 bool NeedCopy = false;
347 // Scale the address delta by the minimum instruction length.
348 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
350 // A LineDelta of INT64_MAX is a signal that this is actually a
351 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
352 // end_sequence to emit the matrix entry.
353 if (LineDelta == INT64_MAX) {
354 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
355 OS << char(dwarf::DW_LNS_const_add_pc);
357 OS << char(dwarf::DW_LNS_advance_pc);
358 encodeULEB128(AddrDelta, OS);
360 OS << char(dwarf::DW_LNS_extended_op);
362 OS << char(dwarf::DW_LNE_end_sequence);
366 // Bias the line delta by the base.
367 Temp = LineDelta - DWARF2_LINE_BASE;
369 // If the line increment is out of range of a special opcode, we must encode
370 // it with DW_LNS_advance_line.
371 if (Temp >= DWARF2_LINE_RANGE) {
372 OS << char(dwarf::DW_LNS_advance_line);
373 encodeSLEB128(LineDelta, OS);
376 Temp = 0 - DWARF2_LINE_BASE;
380 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
381 if (LineDelta == 0 && AddrDelta == 0) {
382 OS << char(dwarf::DW_LNS_copy);
386 // Bias the opcode by the special opcode base.
387 Temp += DWARF2_LINE_OPCODE_BASE;
389 // Avoid overflow when addr_delta is large.
390 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
391 // Try using a special opcode.
392 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
398 // Try using DW_LNS_const_add_pc followed by special op.
399 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
401 OS << char(dwarf::DW_LNS_const_add_pc);
407 // Otherwise use DW_LNS_advance_pc.
408 OS << char(dwarf::DW_LNS_advance_pc);
409 encodeULEB128(AddrDelta, OS);
412 OS << char(dwarf::DW_LNS_copy);
417 void MCDwarfFile::print(raw_ostream &OS) const {
418 OS << '"' << getName() << '"';
421 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
422 void MCDwarfFile::dump() const {
427 // Utility function to write a tuple for .debug_abbrev.
428 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
429 MCOS->EmitULEB128IntValue(Name);
430 MCOS->EmitULEB128IntValue(Form);
433 // When generating dwarf for assembly source files this emits
434 // the data for .debug_abbrev section which contains three DIEs.
435 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
436 MCContext &context = MCOS->getContext();
437 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
439 // DW_TAG_compile_unit DIE abbrev (1).
440 MCOS->EmitULEB128IntValue(1);
441 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
442 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
443 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
444 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
445 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
446 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
447 if (!context.getCompilationDir().empty())
448 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
449 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
450 if (!DwarfDebugFlags.empty())
451 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
452 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
453 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
454 EmitAbbrev(MCOS, 0, 0);
456 // DW_TAG_label DIE abbrev (2).
457 MCOS->EmitULEB128IntValue(2);
458 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
459 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
460 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
461 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
462 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
463 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
464 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
465 EmitAbbrev(MCOS, 0, 0);
467 // DW_TAG_unspecified_parameters DIE abbrev (3).
468 MCOS->EmitULEB128IntValue(3);
469 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
470 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
471 EmitAbbrev(MCOS, 0, 0);
473 // Terminate the abbreviations for this compilation unit.
474 MCOS->EmitIntValue(0, 1);
477 // When generating dwarf for assembly source files this emits the data for
478 // .debug_aranges section. Which contains a header and a table of pairs of
479 // PointerSize'ed values for the address and size of section(s) with line table
480 // entries (just the default .text in our case) and a terminating pair of zeros.
481 static void EmitGenDwarfAranges(MCStreamer *MCOS,
482 const MCSymbol *InfoSectionSymbol) {
483 MCContext &context = MCOS->getContext();
485 // Create a symbol at the end of the section that we are creating the dwarf
486 // debugging info to use later in here as part of the expression to calculate
487 // the size of the section for the table.
488 MCOS->SwitchSection(context.getGenDwarfSection());
489 MCSymbol *SectionEndSym = context.CreateTempSymbol();
490 MCOS->EmitLabel(SectionEndSym);
491 context.setGenDwarfSectionEndSym(SectionEndSym);
493 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
495 // This will be the length of the .debug_aranges section, first account for
496 // the size of each item in the header (see below where we emit these items).
497 int Length = 4 + 2 + 4 + 1 + 1;
499 // Figure the padding after the header before the table of address and size
500 // pairs who's values are PointerSize'ed.
501 const MCAsmInfo *asmInfo = context.getAsmInfo();
502 int AddrSize = asmInfo->getPointerSize();
503 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
504 if (Pad == 2 * AddrSize)
508 // Add the size of the pair of PointerSize'ed values for the address and size
509 // of the one default .text section we have in the table.
510 Length += 2 * AddrSize;
511 // And the pair of terminating zeros.
512 Length += 2 * AddrSize;
515 // Emit the header for this section.
516 // The 4 byte length not including the 4 byte value for the length.
517 MCOS->EmitIntValue(Length - 4, 4);
518 // The 2 byte version, which is 2.
519 MCOS->EmitIntValue(2, 2);
520 // The 4 byte offset to the compile unit in the .debug_info from the start
521 // of the .debug_info.
522 if (InfoSectionSymbol)
523 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
525 MCOS->EmitIntValue(0, 4);
526 // The 1 byte size of an address.
527 MCOS->EmitIntValue(AddrSize, 1);
528 // The 1 byte size of a segment descriptor, we use a value of zero.
529 MCOS->EmitIntValue(0, 1);
530 // Align the header with the padding if needed, before we put out the table.
531 for(int i = 0; i < Pad; i++)
532 MCOS->EmitIntValue(0, 1);
534 // Now emit the table of pairs of PointerSize'ed values for the section(s)
535 // address and size, in our case just the one default .text section.
536 const MCExpr *Addr = MCSymbolRefExpr::Create(
537 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
538 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
539 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
540 MCOS->EmitAbsValue(Addr, AddrSize);
541 MCOS->EmitAbsValue(Size, AddrSize);
543 // And finally the pair of terminating zeros.
544 MCOS->EmitIntValue(0, AddrSize);
545 MCOS->EmitIntValue(0, AddrSize);
548 // When generating dwarf for assembly source files this emits the data for
549 // .debug_info section which contains three parts. The header, the compile_unit
550 // DIE and a list of label DIEs.
551 static void EmitGenDwarfInfo(MCStreamer *MCOS,
552 const MCSymbol *AbbrevSectionSymbol,
553 const MCSymbol *LineSectionSymbol) {
554 MCContext &context = MCOS->getContext();
556 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
558 // Create a symbol at the start and end of this section used in here for the
559 // expression to calculate the length in the header.
560 MCSymbol *InfoStart = context.CreateTempSymbol();
561 MCOS->EmitLabel(InfoStart);
562 MCSymbol *InfoEnd = context.CreateTempSymbol();
564 // First part: the header.
566 // The 4 byte total length of the information for this compilation unit, not
567 // including these 4 bytes.
568 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
569 MCOS->EmitAbsValue(Length, 4);
571 // The 2 byte DWARF version, which is 2.
572 MCOS->EmitIntValue(2, 2);
574 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
575 // it is at the start of that section so this is zero.
576 if (AbbrevSectionSymbol) {
577 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
579 MCOS->EmitIntValue(0, 4);
582 const MCAsmInfo *asmInfo = context.getAsmInfo();
583 int AddrSize = asmInfo->getPointerSize();
584 // The 1 byte size of an address.
585 MCOS->EmitIntValue(AddrSize, 1);
587 // Second part: the compile_unit DIE.
589 // The DW_TAG_compile_unit DIE abbrev (1).
590 MCOS->EmitULEB128IntValue(1);
592 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
593 // which is at the start of that section so this is zero.
594 if (LineSectionSymbol) {
595 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
597 MCOS->EmitIntValue(0, 4);
600 // AT_low_pc, the first address of the default .text section.
601 const MCExpr *Start = MCSymbolRefExpr::Create(
602 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
603 MCOS->EmitAbsValue(Start, AddrSize);
605 // AT_high_pc, the last address of the default .text section.
606 const MCExpr *End = MCSymbolRefExpr::Create(
607 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
608 MCOS->EmitAbsValue(End, AddrSize);
610 // AT_name, the name of the source file. Reconstruct from the first directory
611 // and file table entries.
612 const SmallVectorImpl<StringRef> &MCDwarfDirs =
613 context.getMCDwarfDirs();
614 if (MCDwarfDirs.size() > 0) {
615 MCOS->EmitBytes(MCDwarfDirs[0]);
616 MCOS->EmitBytes("/");
618 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
619 MCOS->getContext().getMCDwarfFiles();
620 MCOS->EmitBytes(MCDwarfFiles[1]->getName());
621 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
623 // AT_comp_dir, the working directory the assembly was done in.
624 if (!context.getCompilationDir().empty()) {
625 MCOS->EmitBytes(context.getCompilationDir());
626 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
629 // AT_APPLE_flags, the command line arguments of the assembler tool.
630 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
631 if (!DwarfDebugFlags.empty()){
632 MCOS->EmitBytes(DwarfDebugFlags);
633 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
636 // AT_producer, the version of the assembler tool.
637 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
638 if (!DwarfDebugProducer.empty()){
639 MCOS->EmitBytes(DwarfDebugProducer);
642 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
643 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
644 MCOS->EmitBytes(StringRef(")"));
646 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
648 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
649 // draft has no standard code for assembler.
650 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
652 // Third part: the list of label DIEs.
654 // Loop on saved info for dwarf labels and create the DIEs for them.
655 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
656 MCOS->getContext().getMCGenDwarfLabelEntries();
657 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
658 Entries.begin(), ie = Entries.end(); it != ie;
660 const MCGenDwarfLabelEntry *Entry = *it;
662 // The DW_TAG_label DIE abbrev (2).
663 MCOS->EmitULEB128IntValue(2);
665 // AT_name, of the label without any leading underbar.
666 MCOS->EmitBytes(Entry->getName());
667 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
669 // AT_decl_file, index into the file table.
670 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
672 // AT_decl_line, source line number.
673 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
675 // AT_low_pc, start address of the label.
676 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
677 MCSymbolRefExpr::VK_None, context);
678 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
680 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
681 MCOS->EmitIntValue(0, 1);
683 // The DW_TAG_unspecified_parameters DIE abbrev (3).
684 MCOS->EmitULEB128IntValue(3);
686 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
687 MCOS->EmitIntValue(0, 1);
689 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
690 // for the dwarf labels.
691 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
692 Entries.begin(), ie = Entries.end(); it != ie;
694 const MCGenDwarfLabelEntry *Entry = *it;
698 // Add the NULL DIE terminating the Compile Unit DIE's.
699 MCOS->EmitIntValue(0, 1);
701 // Now set the value of the symbol at the end of the info section.
702 MCOS->EmitLabel(InfoEnd);
706 // When generating dwarf for assembly source files this emits the Dwarf
709 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
710 // Create the dwarf sections in this order (.debug_line already created).
711 MCContext &context = MCOS->getContext();
712 const MCAsmInfo *AsmInfo = context.getAsmInfo();
713 bool CreateDwarfSectionSymbols =
714 AsmInfo->doesDwarfUseRelocationsAcrossSections();
715 if (!CreateDwarfSectionSymbols)
716 LineSectionSymbol = NULL;
717 MCSymbol *AbbrevSectionSymbol = NULL;
718 MCSymbol *InfoSectionSymbol = NULL;
719 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
720 if (CreateDwarfSectionSymbols) {
721 InfoSectionSymbol = context.CreateTempSymbol();
722 MCOS->EmitLabel(InfoSectionSymbol);
724 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
725 if (CreateDwarfSectionSymbols) {
726 AbbrevSectionSymbol = context.CreateTempSymbol();
727 MCOS->EmitLabel(AbbrevSectionSymbol);
729 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
731 // If there are no line table entries then do not emit any section contents.
732 if (context.getMCLineSections().empty())
735 // Output the data for .debug_aranges section.
736 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
738 // Output the data for .debug_abbrev section.
739 EmitGenDwarfAbbrev(MCOS);
741 // Output the data for .debug_info section.
742 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
746 // When generating dwarf for assembly source files this is called when symbol
747 // for a label is created. If this symbol is not a temporary and is in the
748 // section that dwarf is being generated for, save the needed info to create
751 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
752 SourceMgr &SrcMgr, SMLoc &Loc) {
753 // We won't create dwarf labels for temporary symbols or symbols not in
755 if (Symbol->isTemporary())
757 MCContext &context = MCOS->getContext();
758 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
761 // The dwarf label's name does not have the symbol name's leading
763 StringRef Name = Symbol->getName();
764 if (Name.startswith("_"))
765 Name = Name.substr(1, Name.size()-1);
767 // Get the dwarf file number to be used for the dwarf label.
768 unsigned FileNumber = context.getGenDwarfFileNumber();
770 // Finding the line number is the expensive part which is why we just don't
771 // pass it in as for some symbols we won't create a dwarf label.
772 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
773 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
775 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
776 // values so that they don't have things like an ARM thumb bit from the
777 // original symbol. So when used they won't get a low bit set after
779 MCSymbol *Label = context.CreateTempSymbol();
780 MCOS->EmitLabel(Label);
782 // Create and entry for the info and add it to the other entries.
783 MCGenDwarfLabelEntry *Entry =
784 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
785 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
788 static int getDataAlignmentFactor(MCStreamer &streamer) {
789 MCContext &context = streamer.getContext();
790 const MCAsmInfo *asmInfo = context.getAsmInfo();
791 int size = asmInfo->getCalleeSaveStackSlotSize();
792 if (asmInfo->isStackGrowthDirectionUp())
798 static unsigned getSizeForEncoding(MCStreamer &streamer,
799 unsigned symbolEncoding) {
800 MCContext &context = streamer.getContext();
801 unsigned format = symbolEncoding & 0x0f;
803 default: llvm_unreachable("Unknown Encoding");
804 case dwarf::DW_EH_PE_absptr:
805 case dwarf::DW_EH_PE_signed:
806 return context.getAsmInfo()->getPointerSize();
807 case dwarf::DW_EH_PE_udata2:
808 case dwarf::DW_EH_PE_sdata2:
810 case dwarf::DW_EH_PE_udata4:
811 case dwarf::DW_EH_PE_sdata4:
813 case dwarf::DW_EH_PE_udata8:
814 case dwarf::DW_EH_PE_sdata8:
819 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
820 unsigned symbolEncoding, bool isEH,
821 const char *comment = 0) {
822 MCContext &context = streamer.getContext();
823 const MCAsmInfo *asmInfo = context.getAsmInfo();
824 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
827 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
828 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
829 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
830 streamer.EmitAbsValue(v, size);
832 streamer.EmitValue(v, size);
835 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
836 unsigned symbolEncoding) {
837 MCContext &context = streamer.getContext();
838 const MCAsmInfo *asmInfo = context.getAsmInfo();
839 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
842 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
843 streamer.EmitValue(v, size);
847 class FrameEmitterImpl {
852 const MCSymbol *SectionStart;
854 FrameEmitterImpl(bool usingCFI, bool isEH)
855 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
858 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
860 /// EmitCompactUnwind - Emit the unwind information in a compact way.
861 void EmitCompactUnwind(MCStreamer &streamer,
862 const MCDwarfFrameInfo &frame);
864 const MCSymbol &EmitCIE(MCStreamer &streamer,
865 const MCSymbol *personality,
866 unsigned personalityEncoding,
867 const MCSymbol *lsda,
869 unsigned lsdaEncoding,
871 MCSymbol *EmitFDE(MCStreamer &streamer,
872 const MCSymbol &cieStart,
873 const MCDwarfFrameInfo &frame);
874 void EmitCFIInstructions(MCStreamer &streamer,
875 ArrayRef<MCCFIInstruction> Instrs,
876 MCSymbol *BaseLabel);
877 void EmitCFIInstruction(MCStreamer &Streamer,
878 const MCCFIInstruction &Instr);
881 } // end anonymous namespace
883 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
885 if (Streamer.isVerboseAsm()) {
888 default: EncStr = "<unknown encoding>"; break;
889 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
890 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
891 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
892 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
893 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
894 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
895 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
896 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
897 EncStr = "pcrel udata4";
899 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
900 EncStr = "pcrel sdata4";
902 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
903 EncStr = "pcrel udata8";
905 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
906 EncStr = "screl sdata8";
908 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
909 EncStr = "indirect pcrel udata4";
911 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
912 EncStr = "indirect pcrel sdata4";
914 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
915 EncStr = "indirect pcrel udata8";
917 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
918 EncStr = "indirect pcrel sdata8";
922 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
925 Streamer.EmitIntValue(Encoding, 1);
928 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
929 const MCCFIInstruction &Instr) {
930 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
931 bool VerboseAsm = Streamer.isVerboseAsm();
933 switch (Instr.getOperation()) {
934 case MCCFIInstruction::OpRegister: {
935 unsigned Reg1 = Instr.getRegister();
936 unsigned Reg2 = Instr.getRegister2();
938 Streamer.AddComment("DW_CFA_register");
939 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
940 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
942 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
943 Streamer.EmitULEB128IntValue(Reg1);
944 Streamer.EmitULEB128IntValue(Reg2);
947 case MCCFIInstruction::OpWindowSave: {
948 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
951 case MCCFIInstruction::OpUndefined: {
952 unsigned Reg = Instr.getRegister();
954 Streamer.AddComment("DW_CFA_undefined");
955 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
957 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
958 Streamer.EmitULEB128IntValue(Reg);
961 case MCCFIInstruction::OpAdjustCfaOffset:
962 case MCCFIInstruction::OpDefCfaOffset: {
963 const bool IsRelative =
964 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
967 Streamer.AddComment("DW_CFA_def_cfa_offset");
968 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
971 CFAOffset += Instr.getOffset();
973 CFAOffset = -Instr.getOffset();
976 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
977 Streamer.EmitULEB128IntValue(CFAOffset);
981 case MCCFIInstruction::OpDefCfa: {
983 Streamer.AddComment("DW_CFA_def_cfa");
984 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
987 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
988 Streamer.EmitULEB128IntValue(Instr.getRegister());
990 CFAOffset = -Instr.getOffset();
993 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
994 Streamer.EmitULEB128IntValue(CFAOffset);
999 case MCCFIInstruction::OpDefCfaRegister: {
1001 Streamer.AddComment("DW_CFA_def_cfa_register");
1002 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1005 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1006 Streamer.EmitULEB128IntValue(Instr.getRegister());
1011 case MCCFIInstruction::OpOffset:
1012 case MCCFIInstruction::OpRelOffset: {
1013 const bool IsRelative =
1014 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1016 unsigned Reg = Instr.getRegister();
1017 int Offset = Instr.getOffset();
1019 Offset -= CFAOffset;
1020 Offset = Offset / dataAlignmentFactor;
1023 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1024 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1025 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1026 Streamer.EmitULEB128IntValue(Reg);
1027 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1028 Streamer.EmitSLEB128IntValue(Offset);
1029 } else if (Reg < 64) {
1030 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1032 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1033 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1034 Streamer.EmitULEB128IntValue(Offset);
1036 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1037 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1038 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1039 Streamer.EmitULEB128IntValue(Reg);
1040 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1041 Streamer.EmitULEB128IntValue(Offset);
1045 case MCCFIInstruction::OpRememberState:
1046 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1047 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1049 case MCCFIInstruction::OpRestoreState:
1050 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1051 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1053 case MCCFIInstruction::OpSameValue: {
1054 unsigned Reg = Instr.getRegister();
1055 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1056 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1057 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1058 Streamer.EmitULEB128IntValue(Reg);
1061 case MCCFIInstruction::OpRestore: {
1062 unsigned Reg = Instr.getRegister();
1064 Streamer.AddComment("DW_CFA_restore");
1065 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1067 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1070 case MCCFIInstruction::OpEscape:
1071 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1072 Streamer.EmitBytes(Instr.getValues());
1075 llvm_unreachable("Unhandled case in switch");
1078 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1080 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1081 ArrayRef<MCCFIInstruction> Instrs,
1082 MCSymbol *BaseLabel) {
1083 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1084 const MCCFIInstruction &Instr = Instrs[i];
1085 MCSymbol *Label = Instr.getLabel();
1086 // Throw out move if the label is invalid.
1087 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1089 // Advance row if new location.
1090 if (BaseLabel && Label) {
1091 MCSymbol *ThisSym = Label;
1092 if (ThisSym != BaseLabel) {
1093 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1094 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1095 BaseLabel = ThisSym;
1099 EmitCFIInstruction(streamer, Instr);
1103 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1104 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1105 const MCDwarfFrameInfo &Frame) {
1106 MCContext &Context = Streamer.getContext();
1107 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1108 bool VerboseAsm = Streamer.isVerboseAsm();
1110 // range-start range-length compact-unwind-enc personality-func lsda
1111 // _foo LfooEnd-_foo 0x00000023 0 0
1112 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1114 // .section __LD,__compact_unwind,regular,debug
1116 // # compact unwind for _foo
1118 // .set L1,LfooEnd-_foo
1124 // # compact unwind for _bar
1126 // .set L2,LbarEnd-_bar
1129 // .quad __gxx_personality
1130 // .quad except_tab1
1132 uint32_t Encoding = Frame.CompactUnwindEncoding;
1133 if (!Encoding) return;
1134 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1136 // The encoding needs to know we have an LSDA.
1137 if (!DwarfEHFrameOnly && Frame.Lsda)
1138 Encoding |= 0x40000000;
1141 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1142 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1143 if (VerboseAsm) Streamer.AddComment("Range Start");
1144 Streamer.EmitSymbolValue(Frame.Function, Size);
1147 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1149 if (VerboseAsm) Streamer.AddComment("Range Length");
1150 Streamer.EmitAbsValue(Range, 4);
1153 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1154 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1155 Twine::utohexstr(Encoding));
1156 Streamer.EmitIntValue(Encoding, Size);
1158 // Personality Function
1159 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1160 if (VerboseAsm) Streamer.AddComment("Personality Function");
1161 if (!DwarfEHFrameOnly && Frame.Personality)
1162 Streamer.EmitSymbolValue(Frame.Personality, Size);
1164 Streamer.EmitIntValue(0, Size); // No personality fn
1167 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1168 if (VerboseAsm) Streamer.AddComment("LSDA");
1169 if (!DwarfEHFrameOnly && Frame.Lsda)
1170 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1172 Streamer.EmitIntValue(0, Size); // No LSDA
1175 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1176 const MCSymbol *personality,
1177 unsigned personalityEncoding,
1178 const MCSymbol *lsda,
1180 unsigned lsdaEncoding,
1182 MCContext &context = streamer.getContext();
1183 const MCRegisterInfo *MRI = context.getRegisterInfo();
1184 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1185 bool verboseAsm = streamer.isVerboseAsm();
1187 MCSymbol *sectionStart;
1188 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1189 sectionStart = context.CreateTempSymbol();
1191 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1193 streamer.EmitLabel(sectionStart);
1196 MCSymbol *sectionEnd = context.CreateTempSymbol();
1199 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1201 if (verboseAsm) streamer.AddComment("CIE Length");
1202 streamer.EmitAbsValue(Length, 4);
1205 unsigned CIE_ID = IsEH ? 0 : -1;
1206 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1207 streamer.EmitIntValue(CIE_ID, 4);
1210 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1211 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1213 // Augmentation String
1214 SmallString<8> Augmentation;
1216 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1217 Augmentation += "z";
1219 Augmentation += "P";
1221 Augmentation += "L";
1222 Augmentation += "R";
1224 Augmentation += "S";
1225 streamer.EmitBytes(Augmentation.str());
1227 streamer.EmitIntValue(0, 1);
1229 // Code Alignment Factor
1230 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1231 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1233 // Data Alignment Factor
1234 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1235 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1237 // Return Address Register
1238 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1239 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1241 // Augmentation Data Length (optional)
1243 unsigned augmentationLength = 0;
1246 // Personality Encoding
1247 augmentationLength += 1;
1249 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1252 augmentationLength += 1;
1253 // Encoding of the FDE pointers
1254 augmentationLength += 1;
1256 if (verboseAsm) streamer.AddComment("Augmentation Size");
1257 streamer.EmitULEB128IntValue(augmentationLength);
1259 // Augmentation Data (optional)
1261 // Personality Encoding
1262 EmitEncodingByte(streamer, personalityEncoding,
1263 "Personality Encoding");
1265 if (verboseAsm) streamer.AddComment("Personality");
1266 EmitPersonality(streamer, *personality, personalityEncoding);
1270 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1272 // Encoding of the FDE pointers
1273 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1277 // Initial Instructions
1279 const MCAsmInfo *MAI = context.getAsmInfo();
1281 const std::vector<MCCFIInstruction> &Instructions =
1282 MAI->getInitialFrameState();
1283 EmitCFIInstructions(streamer, Instructions, NULL);
1287 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1289 streamer.EmitLabel(sectionEnd);
1290 return *sectionStart;
1293 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1294 const MCSymbol &cieStart,
1295 const MCDwarfFrameInfo &frame) {
1296 MCContext &context = streamer.getContext();
1297 MCSymbol *fdeStart = context.CreateTempSymbol();
1298 MCSymbol *fdeEnd = context.CreateTempSymbol();
1299 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1300 bool verboseAsm = streamer.isVerboseAsm();
1302 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1304 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1305 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1306 streamer.EmitLabel(EHSym);
1310 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1311 if (verboseAsm) streamer.AddComment("FDE Length");
1312 streamer.EmitAbsValue(Length, 4);
1314 streamer.EmitLabel(fdeStart);
1317 const MCAsmInfo *asmInfo = context.getAsmInfo();
1319 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1321 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1322 streamer.EmitAbsValue(offset, 4);
1323 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1324 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1326 streamer.EmitAbsValue(offset, 4);
1328 streamer.EmitSymbolValue(&cieStart, 4);
1332 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1333 : (unsigned)dwarf::DW_EH_PE_absptr;
1334 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1335 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1338 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1340 if (verboseAsm) streamer.AddComment("FDE address range");
1341 streamer.EmitAbsValue(Range, PCSize);
1344 // Augmentation Data Length
1345 unsigned augmentationLength = 0;
1348 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1350 if (verboseAsm) streamer.AddComment("Augmentation size");
1351 streamer.EmitULEB128IntValue(augmentationLength);
1353 // Augmentation Data
1355 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1356 "Language Specific Data Area");
1359 // Call Frame Instructions
1360 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1363 streamer.EmitValueToAlignment(PCSize);
1370 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1371 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1373 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1374 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1375 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1376 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1377 IsSimple(IsSimple_) {
1379 const MCSymbol* Personality;
1380 unsigned PersonalityEncoding;
1381 unsigned LsdaEncoding;
1389 struct DenseMapInfo<CIEKey> {
1390 static CIEKey getEmptyKey() {
1391 return CIEKey::getEmptyKey();
1393 static CIEKey getTombstoneKey() {
1394 return CIEKey::getTombstoneKey();
1396 static unsigned getHashValue(const CIEKey &Key) {
1397 return static_cast<unsigned>(hash_combine(Key.Personality,
1398 Key.PersonalityEncoding,
1403 static bool isEqual(const CIEKey &LHS,
1404 const CIEKey &RHS) {
1405 return LHS.Personality == RHS.Personality &&
1406 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1407 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1408 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1409 LHS.IsSimple == RHS.IsSimple;
1414 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1415 bool UsingCFI, bool IsEH) {
1416 Streamer.generateCompactUnwindEncodings(MAB);
1418 MCContext &Context = Streamer.getContext();
1419 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1420 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1421 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1423 // Emit the compact unwind info if available.
1424 if (IsEH && MOFI->getCompactUnwindSection()) {
1425 bool SectionEmitted = false;
1426 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1427 const MCDwarfFrameInfo &Frame = FrameArray[i];
1428 if (Frame.CompactUnwindEncoding == 0) continue;
1429 if (!SectionEmitted) {
1430 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1431 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1432 SectionEmitted = true;
1434 Emitter.EmitCompactUnwind(Streamer, Frame);
1438 const MCSection &Section =
1439 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1440 *MOFI->getDwarfFrameSection();
1441 Streamer.SwitchSection(&Section);
1442 MCSymbol *SectionStart = Context.CreateTempSymbol();
1443 Streamer.EmitLabel(SectionStart);
1444 Emitter.setSectionStart(SectionStart);
1446 MCSymbol *FDEEnd = NULL;
1447 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1449 const MCSymbol *DummyDebugKey = NULL;
1450 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1451 const MCDwarfFrameInfo &Frame = FrameArray[i];
1452 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1453 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1454 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1456 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1457 Frame.PersonalityEncoding, Frame.Lsda,
1458 Frame.IsSignalFrame,
1462 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1465 Streamer.EmitLabel(FDEEnd);
1468 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1470 Streamer.EmitLabel(FDEEnd);
1473 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1474 uint64_t AddrDelta) {
1475 MCContext &Context = Streamer.getContext();
1476 SmallString<256> Tmp;
1477 raw_svector_ostream OS(Tmp);
1478 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1479 Streamer.EmitBytes(OS.str());
1482 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1485 // Scale the address delta by the minimum instruction length.
1486 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1488 if (AddrDelta == 0) {
1489 } else if (isUIntN(6, AddrDelta)) {
1490 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1492 } else if (isUInt<8>(AddrDelta)) {
1493 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1494 OS << uint8_t(AddrDelta);
1495 } else if (isUInt<16>(AddrDelta)) {
1496 // FIXME: check what is the correct behavior on a big endian machine.
1497 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1498 OS << uint8_t( AddrDelta & 0xff);
1499 OS << uint8_t((AddrDelta >> 8) & 0xff);
1501 // FIXME: check what is the correct behavior on a big endian machine.
1502 assert(isUInt<32>(AddrDelta));
1503 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1504 OS << uint8_t( AddrDelta & 0xff);
1505 OS << uint8_t((AddrDelta >> 8) & 0xff);
1506 OS << uint8_t((AddrDelta >> 16) & 0xff);
1507 OS << uint8_t((AddrDelta >> 24) & 0xff);