1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCDwarf.h"
11 #include "llvm/ADT/Hashing.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/Config/config.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectFileInfo.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
30 // Given a special op, return the address skip amount (in units of
31 // DWARF2_LINE_MIN_INSN_LENGTH.
32 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
34 // The maximum address skip amount that can be encoded with a special op.
35 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
37 // First special line opcode - leave room for the standard opcodes.
38 // Note: If you want to change this, you'll have to update the
39 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
40 #define DWARF2_LINE_OPCODE_BASE 13
42 // Minimum line offset in a special line info. opcode. This value
43 // was chosen to give a reasonable range of values.
44 #define DWARF2_LINE_BASE -5
46 // Range of line offsets in a special line info. opcode.
47 #define DWARF2_LINE_RANGE 14
49 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
50 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
51 if (MinInsnLength == 1)
53 if (AddrDelta % MinInsnLength != 0) {
54 // TODO: report this error, but really only once.
57 return AddrDelta / MinInsnLength;
61 // This is called when an instruction is assembled into the specified section
62 // and if there is information from the last .loc directive that has yet to have
63 // a line entry made for it is made.
65 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
66 if (!MCOS->getContext().getDwarfLocSeen())
69 // Create a symbol at in the current section for use in the line entry.
70 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
71 // Set the value of the symbol to use for the MCLineEntry.
72 MCOS->EmitLabel(LineSym);
74 // Get the current .loc info saved in the context.
75 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
77 // Create a (local) line entry with the symbol and the current .loc info.
78 MCLineEntry LineEntry(LineSym, DwarfLoc);
80 // clear DwarfLocSeen saying the current .loc info is now used.
81 MCOS->getContext().ClearDwarfLocSeen();
83 // Get the MCLineSection for this section, if one does not exist for this
85 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
86 MCOS->getContext().getMCLineSections();
87 MCLineSection *LineSection = MCLineSections.lookup(Section);
89 // Create a new MCLineSection. This will be deleted after the dwarf line
90 // table is created using it by iterating through the MCLineSections
92 LineSection = new MCLineSection;
93 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
94 MCOS->getContext().addMCLineSection(Section, LineSection);
97 // Add the line entry to this section's entries.
98 LineSection->addLineEntry(LineEntry,
99 MCOS->getContext().getDwarfCompileUnitID());
103 // This helper routine returns an expression of End - Start + IntVal .
105 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
106 const MCSymbol &Start,
109 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
111 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
113 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
115 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
117 MCConstantExpr::Create(IntVal, MCOS.getContext());
119 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
124 // This emits the Dwarf line table for the specified section from the entries
125 // in the LineSection.
127 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
128 const MCSection *Section,
129 const MCLineSection *LineSection,
131 // This LineSection does not contain any LineEntry for the given Compile Unit.
132 if (!LineSection->containEntriesForID(CUID))
135 unsigned FileNum = 1;
136 unsigned LastLine = 1;
138 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
140 unsigned Discriminator = 0;
141 MCSymbol *LastLabel = NULL;
143 // Loop through each MCLineEntry and encode the dwarf line number table.
144 for (MCLineSection::const_iterator
145 it = LineSection->getMCLineEntries(CUID).begin(),
146 ie = LineSection->getMCLineEntries(CUID).end(); it != ie; ++it) {
148 if (FileNum != it->getFileNum()) {
149 FileNum = it->getFileNum();
150 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
151 MCOS->EmitULEB128IntValue(FileNum);
153 if (Column != it->getColumn()) {
154 Column = it->getColumn();
155 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
156 MCOS->EmitULEB128IntValue(Column);
158 if (Discriminator != it->getDiscriminator()) {
159 Discriminator = it->getDiscriminator();
160 unsigned Size = getULEB128Size(Discriminator);
161 MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
162 MCOS->EmitULEB128IntValue(Size + 1);
163 MCOS->EmitIntValue(dwarf::DW_LNE_set_discriminator, 1);
164 MCOS->EmitULEB128IntValue(Discriminator);
166 if (Isa != it->getIsa()) {
168 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
169 MCOS->EmitULEB128IntValue(Isa);
171 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
172 Flags = it->getFlags();
173 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
175 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
176 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
177 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
178 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
179 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
180 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
182 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
183 MCSymbol *Label = it->getLabel();
185 // At this point we want to emit/create the sequence to encode the delta in
186 // line numbers and the increment of the address from the previous Label
187 // and the current Label.
188 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
189 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
190 asmInfo->getPointerSize());
192 LastLine = it->getLine();
196 // Emit a DW_LNE_end_sequence for the end of the section.
197 // Using the pointer Section create a temporary label at the end of the
198 // section and use that and the LastLabel to compute the address delta
199 // and use INT64_MAX as the line delta which is the signal that this is
200 // actually a DW_LNE_end_sequence.
202 // Switch to the section to be able to create a symbol at its end.
203 // TODO: keep track of the last subsection so that this symbol appears in the
205 MCOS->SwitchSection(Section);
207 MCContext &context = MCOS->getContext();
208 // Create a symbol at the end of the section.
209 MCSymbol *SectionEnd = context.CreateTempSymbol();
210 // Set the value of the symbol, as we are at the end of the section.
211 MCOS->EmitLabel(SectionEnd);
213 // Switch back the dwarf line section.
214 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
216 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
217 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
218 asmInfo->getPointerSize());
222 // This emits the Dwarf file and the line tables.
224 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
225 MCContext &context = MCOS->getContext();
226 // Switch to the section where the table will be emitted into.
227 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
229 const DenseMap<unsigned, MCSymbol *> &MCLineTableSymbols =
230 MCOS->getContext().getMCLineTableSymbols();
231 // CUID and MCLineTableSymbols are set in DwarfDebug, when DwarfDebug does
232 // not exist, CUID will be 0 and MCLineTableSymbols will be empty.
233 // Handle Compile Unit 0, the line table start symbol is the section symbol.
234 const MCSymbol *LineStartSym = EmitCU(MCOS, 0);
235 // Handle the rest of the Compile Units.
236 for (unsigned Is = 1, Ie = MCLineTableSymbols.size(); Is < Ie; Is++)
239 // Now delete the MCLineSections that were created in MCLineEntry::Make()
240 // and used to emit the line table.
241 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
242 MCOS->getContext().getMCLineSections();
243 for (DenseMap<const MCSection *, MCLineSection *>::const_iterator it =
244 MCLineSections.begin(), ie = MCLineSections.end(); it != ie;
251 const MCSymbol *MCDwarfFileTable::EmitCU(MCStreamer *MCOS, unsigned CUID) {
252 MCContext &context = MCOS->getContext();
254 // Create a symbol at the beginning of the line table.
255 MCSymbol *LineStartSym = MCOS->getContext().getMCLineTableSymbol(CUID);
257 LineStartSym = context.CreateTempSymbol();
258 // Set the value of the symbol, as we are at the start of the line table.
259 MCOS->EmitLabel(LineStartSym);
261 // Create a symbol for the end of the section (to be set when we get there).
262 MCSymbol *LineEndSym = context.CreateTempSymbol();
264 // The first 4 bytes is the total length of the information for this
265 // compilation unit (not including these 4 bytes for the length).
266 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
269 // Next 2 bytes is the Version, which is Dwarf 2.
270 MCOS->EmitIntValue(2, 2);
272 // Create a symbol for the end of the prologue (to be set when we get there).
273 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
275 // Length of the prologue, is the next 4 bytes. Which is the start of the
276 // section to the end of the prologue. Not including the 4 bytes for the
277 // total length, the 2 bytes for the version, and these 4 bytes for the
278 // length of the prologue.
279 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
282 // Parameters of the state machine, are next.
283 MCOS->EmitIntValue(context.getAsmInfo()->getMinInstAlignment(), 1);
284 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
285 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
286 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
287 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
289 // Standard opcode lengths
290 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
291 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
292 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
293 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
294 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
295 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
296 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
297 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
298 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
299 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
300 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
301 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
303 // Put out the directory and file tables.
305 // First the directory table.
306 const SmallVectorImpl<StringRef> &MCDwarfDirs =
307 context.getMCDwarfDirs(CUID);
308 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
309 MCOS->EmitBytes(MCDwarfDirs[i]); // the DirectoryName
310 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
312 MCOS->EmitIntValue(0, 1); // Terminate the directory list
314 // Second the file table.
315 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
316 MCOS->getContext().getMCDwarfFiles(CUID);
317 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
318 MCOS->EmitBytes(MCDwarfFiles[i]->getName()); // FileName
319 MCOS->EmitBytes(StringRef("\0", 1)); // the null term. of the string
321 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
322 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
323 MCOS->EmitIntValue(0, 1); // filesize (always 0)
325 MCOS->EmitIntValue(0, 1); // Terminate the file list
327 // This is the end of the prologue, so set the value of the symbol at the
328 // end of the prologue (that was used in a previous expression).
329 MCOS->EmitLabel(ProEndSym);
331 // Put out the line tables.
332 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
333 MCOS->getContext().getMCLineSections();
334 const std::vector<const MCSection *> &MCLineSectionOrder =
335 MCOS->getContext().getMCLineSectionOrder();
336 for (std::vector<const MCSection*>::const_iterator it =
337 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
339 const MCSection *Sec = *it;
340 const MCLineSection *Line = MCLineSections.lookup(Sec);
341 EmitDwarfLineTable(MCOS, Sec, Line, CUID);
344 if (MCOS->getContext().getAsmInfo()->getLinkerRequiresNonEmptyDwarfLines()
345 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
346 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
348 // total_length >= prologue_length + 10
349 // We are 4 bytes short, since we have total_length = 51 and
350 // prologue_length = 45
352 // The regular end_sequence should be sufficient.
353 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
356 // This is the end of the section, so set the value of the symbol at the end
357 // of this section (that was used in a previous expression).
358 MCOS->EmitLabel(LineEndSym);
363 /// Utility function to emit the encoding to a streamer.
364 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
365 uint64_t AddrDelta) {
366 MCContext &Context = MCOS->getContext();
367 SmallString<256> Tmp;
368 raw_svector_ostream OS(Tmp);
369 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OS);
370 MCOS->EmitBytes(OS.str());
373 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
374 void MCDwarfLineAddr::Encode(MCContext &Context, int64_t LineDelta,
375 uint64_t AddrDelta, raw_ostream &OS) {
376 uint64_t Temp, Opcode;
377 bool NeedCopy = false;
379 // Scale the address delta by the minimum instruction length.
380 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
382 // A LineDelta of INT64_MAX is a signal that this is actually a
383 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
384 // end_sequence to emit the matrix entry.
385 if (LineDelta == INT64_MAX) {
386 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
387 OS << char(dwarf::DW_LNS_const_add_pc);
389 OS << char(dwarf::DW_LNS_advance_pc);
390 encodeULEB128(AddrDelta, OS);
392 OS << char(dwarf::DW_LNS_extended_op);
394 OS << char(dwarf::DW_LNE_end_sequence);
398 // Bias the line delta by the base.
399 Temp = LineDelta - DWARF2_LINE_BASE;
401 // If the line increment is out of range of a special opcode, we must encode
402 // it with DW_LNS_advance_line.
403 if (Temp >= DWARF2_LINE_RANGE) {
404 OS << char(dwarf::DW_LNS_advance_line);
405 encodeSLEB128(LineDelta, OS);
408 Temp = 0 - DWARF2_LINE_BASE;
412 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
413 if (LineDelta == 0 && AddrDelta == 0) {
414 OS << char(dwarf::DW_LNS_copy);
418 // Bias the opcode by the special opcode base.
419 Temp += DWARF2_LINE_OPCODE_BASE;
421 // Avoid overflow when addr_delta is large.
422 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
423 // Try using a special opcode.
424 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
430 // Try using DW_LNS_const_add_pc followed by special op.
431 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
433 OS << char(dwarf::DW_LNS_const_add_pc);
439 // Otherwise use DW_LNS_advance_pc.
440 OS << char(dwarf::DW_LNS_advance_pc);
441 encodeULEB128(AddrDelta, OS);
444 OS << char(dwarf::DW_LNS_copy);
449 void MCDwarfFile::print(raw_ostream &OS) const {
450 OS << '"' << getName() << '"';
453 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
454 void MCDwarfFile::dump() const {
459 // Utility function to write a tuple for .debug_abbrev.
460 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
461 MCOS->EmitULEB128IntValue(Name);
462 MCOS->EmitULEB128IntValue(Form);
465 // When generating dwarf for assembly source files this emits
466 // the data for .debug_abbrev section which contains three DIEs.
467 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
468 MCContext &context = MCOS->getContext();
469 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
471 // DW_TAG_compile_unit DIE abbrev (1).
472 MCOS->EmitULEB128IntValue(1);
473 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
474 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
475 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
476 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
477 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
478 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
479 if (!context.getCompilationDir().empty())
480 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
481 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
482 if (!DwarfDebugFlags.empty())
483 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
484 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
485 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
486 EmitAbbrev(MCOS, 0, 0);
488 // DW_TAG_label DIE abbrev (2).
489 MCOS->EmitULEB128IntValue(2);
490 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
491 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
492 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
493 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
494 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
495 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
496 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
497 EmitAbbrev(MCOS, 0, 0);
499 // DW_TAG_unspecified_parameters DIE abbrev (3).
500 MCOS->EmitULEB128IntValue(3);
501 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
502 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
503 EmitAbbrev(MCOS, 0, 0);
505 // Terminate the abbreviations for this compilation unit.
506 MCOS->EmitIntValue(0, 1);
509 // When generating dwarf for assembly source files this emits the data for
510 // .debug_aranges section. Which contains a header and a table of pairs of
511 // PointerSize'ed values for the address and size of section(s) with line table
512 // entries (just the default .text in our case) and a terminating pair of zeros.
513 static void EmitGenDwarfAranges(MCStreamer *MCOS,
514 const MCSymbol *InfoSectionSymbol) {
515 MCContext &context = MCOS->getContext();
517 // Create a symbol at the end of the section that we are creating the dwarf
518 // debugging info to use later in here as part of the expression to calculate
519 // the size of the section for the table.
520 MCOS->SwitchSection(context.getGenDwarfSection());
521 MCSymbol *SectionEndSym = context.CreateTempSymbol();
522 MCOS->EmitLabel(SectionEndSym);
523 context.setGenDwarfSectionEndSym(SectionEndSym);
525 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
527 // This will be the length of the .debug_aranges section, first account for
528 // the size of each item in the header (see below where we emit these items).
529 int Length = 4 + 2 + 4 + 1 + 1;
531 // Figure the padding after the header before the table of address and size
532 // pairs who's values are PointerSize'ed.
533 const MCAsmInfo *asmInfo = context.getAsmInfo();
534 int AddrSize = asmInfo->getPointerSize();
535 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
536 if (Pad == 2 * AddrSize)
540 // Add the size of the pair of PointerSize'ed values for the address and size
541 // of the one default .text section we have in the table.
542 Length += 2 * AddrSize;
543 // And the pair of terminating zeros.
544 Length += 2 * AddrSize;
547 // Emit the header for this section.
548 // The 4 byte length not including the 4 byte value for the length.
549 MCOS->EmitIntValue(Length - 4, 4);
550 // The 2 byte version, which is 2.
551 MCOS->EmitIntValue(2, 2);
552 // The 4 byte offset to the compile unit in the .debug_info from the start
553 // of the .debug_info.
554 if (InfoSectionSymbol)
555 MCOS->EmitSymbolValue(InfoSectionSymbol, 4);
557 MCOS->EmitIntValue(0, 4);
558 // The 1 byte size of an address.
559 MCOS->EmitIntValue(AddrSize, 1);
560 // The 1 byte size of a segment descriptor, we use a value of zero.
561 MCOS->EmitIntValue(0, 1);
562 // Align the header with the padding if needed, before we put out the table.
563 for(int i = 0; i < Pad; i++)
564 MCOS->EmitIntValue(0, 1);
566 // Now emit the table of pairs of PointerSize'ed values for the section(s)
567 // address and size, in our case just the one default .text section.
568 const MCExpr *Addr = MCSymbolRefExpr::Create(
569 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
570 const MCExpr *Size = MakeStartMinusEndExpr(*MCOS,
571 *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
572 MCOS->EmitAbsValue(Addr, AddrSize);
573 MCOS->EmitAbsValue(Size, AddrSize);
575 // And finally the pair of terminating zeros.
576 MCOS->EmitIntValue(0, AddrSize);
577 MCOS->EmitIntValue(0, AddrSize);
580 // When generating dwarf for assembly source files this emits the data for
581 // .debug_info section which contains three parts. The header, the compile_unit
582 // DIE and a list of label DIEs.
583 static void EmitGenDwarfInfo(MCStreamer *MCOS,
584 const MCSymbol *AbbrevSectionSymbol,
585 const MCSymbol *LineSectionSymbol) {
586 MCContext &context = MCOS->getContext();
588 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
590 // Create a symbol at the start and end of this section used in here for the
591 // expression to calculate the length in the header.
592 MCSymbol *InfoStart = context.CreateTempSymbol();
593 MCOS->EmitLabel(InfoStart);
594 MCSymbol *InfoEnd = context.CreateTempSymbol();
596 // First part: the header.
598 // The 4 byte total length of the information for this compilation unit, not
599 // including these 4 bytes.
600 const MCExpr *Length = MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoEnd, 4);
601 MCOS->EmitAbsValue(Length, 4);
603 // The 2 byte DWARF version, which is 2.
604 MCOS->EmitIntValue(2, 2);
606 // The 4 byte offset to the debug abbrevs from the start of the .debug_abbrev,
607 // it is at the start of that section so this is zero.
608 if (AbbrevSectionSymbol) {
609 MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
611 MCOS->EmitIntValue(0, 4);
614 const MCAsmInfo *asmInfo = context.getAsmInfo();
615 int AddrSize = asmInfo->getPointerSize();
616 // The 1 byte size of an address.
617 MCOS->EmitIntValue(AddrSize, 1);
619 // Second part: the compile_unit DIE.
621 // The DW_TAG_compile_unit DIE abbrev (1).
622 MCOS->EmitULEB128IntValue(1);
624 // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line section,
625 // which is at the start of that section so this is zero.
626 if (LineSectionSymbol) {
627 MCOS->EmitSymbolValue(LineSectionSymbol, 4);
629 MCOS->EmitIntValue(0, 4);
632 // AT_low_pc, the first address of the default .text section.
633 const MCExpr *Start = MCSymbolRefExpr::Create(
634 context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, context);
635 MCOS->EmitAbsValue(Start, AddrSize);
637 // AT_high_pc, the last address of the default .text section.
638 const MCExpr *End = MCSymbolRefExpr::Create(
639 context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
640 MCOS->EmitAbsValue(End, AddrSize);
642 // AT_name, the name of the source file. Reconstruct from the first directory
643 // and file table entries.
644 const SmallVectorImpl<StringRef> &MCDwarfDirs =
645 context.getMCDwarfDirs();
646 if (MCDwarfDirs.size() > 0) {
647 MCOS->EmitBytes(MCDwarfDirs[0]);
648 MCOS->EmitBytes("/");
650 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
651 MCOS->getContext().getMCDwarfFiles();
652 MCOS->EmitBytes(MCDwarfFiles[1]->getName());
653 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
655 // AT_comp_dir, the working directory the assembly was done in.
656 if (!context.getCompilationDir().empty()) {
657 MCOS->EmitBytes(context.getCompilationDir());
658 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
661 // AT_APPLE_flags, the command line arguments of the assembler tool.
662 StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
663 if (!DwarfDebugFlags.empty()){
664 MCOS->EmitBytes(DwarfDebugFlags);
665 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
668 // AT_producer, the version of the assembler tool.
669 StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
670 if (!DwarfDebugProducer.empty()){
671 MCOS->EmitBytes(DwarfDebugProducer);
674 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "));
675 MCOS->EmitBytes(StringRef(PACKAGE_VERSION));
676 MCOS->EmitBytes(StringRef(")"));
678 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
680 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2
681 // draft has no standard code for assembler.
682 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
684 // Third part: the list of label DIEs.
686 // Loop on saved info for dwarf labels and create the DIEs for them.
687 const std::vector<const MCGenDwarfLabelEntry *> &Entries =
688 MCOS->getContext().getMCGenDwarfLabelEntries();
689 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
690 Entries.begin(), ie = Entries.end(); it != ie;
692 const MCGenDwarfLabelEntry *Entry = *it;
694 // The DW_TAG_label DIE abbrev (2).
695 MCOS->EmitULEB128IntValue(2);
697 // AT_name, of the label without any leading underbar.
698 MCOS->EmitBytes(Entry->getName());
699 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
701 // AT_decl_file, index into the file table.
702 MCOS->EmitIntValue(Entry->getFileNumber(), 4);
704 // AT_decl_line, source line number.
705 MCOS->EmitIntValue(Entry->getLineNumber(), 4);
707 // AT_low_pc, start address of the label.
708 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(),
709 MCSymbolRefExpr::VK_None, context);
710 MCOS->EmitAbsValue(AT_low_pc, AddrSize);
712 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype.
713 MCOS->EmitIntValue(0, 1);
715 // The DW_TAG_unspecified_parameters DIE abbrev (3).
716 MCOS->EmitULEB128IntValue(3);
718 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's.
719 MCOS->EmitIntValue(0, 1);
721 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
722 // for the dwarf labels.
723 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =
724 Entries.begin(), ie = Entries.end(); it != ie;
726 const MCGenDwarfLabelEntry *Entry = *it;
730 // Add the NULL DIE terminating the Compile Unit DIE's.
731 MCOS->EmitIntValue(0, 1);
733 // Now set the value of the symbol at the end of the info section.
734 MCOS->EmitLabel(InfoEnd);
738 // When generating dwarf for assembly source files this emits the Dwarf
741 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) {
742 // Create the dwarf sections in this order (.debug_line already created).
743 MCContext &context = MCOS->getContext();
744 const MCAsmInfo *AsmInfo = context.getAsmInfo();
745 bool CreateDwarfSectionSymbols =
746 AsmInfo->doesDwarfUseRelocationsAcrossSections();
747 if (!CreateDwarfSectionSymbols)
748 LineSectionSymbol = NULL;
749 MCSymbol *AbbrevSectionSymbol = NULL;
750 MCSymbol *InfoSectionSymbol = NULL;
751 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
752 if (CreateDwarfSectionSymbols) {
753 InfoSectionSymbol = context.CreateTempSymbol();
754 MCOS->EmitLabel(InfoSectionSymbol);
756 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
757 if (CreateDwarfSectionSymbols) {
758 AbbrevSectionSymbol = context.CreateTempSymbol();
759 MCOS->EmitLabel(AbbrevSectionSymbol);
761 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
763 // If there are no line table entries then do not emit any section contents.
764 if (context.getMCLineSections().empty())
767 // Output the data for .debug_aranges section.
768 EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
770 // Output the data for .debug_abbrev section.
771 EmitGenDwarfAbbrev(MCOS);
773 // Output the data for .debug_info section.
774 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
778 // When generating dwarf for assembly source files this is called when symbol
779 // for a label is created. If this symbol is not a temporary and is in the
780 // section that dwarf is being generated for, save the needed info to create
783 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
784 SourceMgr &SrcMgr, SMLoc &Loc) {
785 // We won't create dwarf labels for temporary symbols or symbols not in
787 if (Symbol->isTemporary())
789 MCContext &context = MCOS->getContext();
790 if (context.getGenDwarfSection() != MCOS->getCurrentSection().first)
793 // The dwarf label's name does not have the symbol name's leading
795 StringRef Name = Symbol->getName();
796 if (Name.startswith("_"))
797 Name = Name.substr(1, Name.size()-1);
799 // Get the dwarf file number to be used for the dwarf label.
800 unsigned FileNumber = context.getGenDwarfFileNumber();
802 // Finding the line number is the expensive part which is why we just don't
803 // pass it in as for some symbols we won't create a dwarf label.
804 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
805 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
807 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
808 // values so that they don't have things like an ARM thumb bit from the
809 // original symbol. So when used they won't get a low bit set after
811 MCSymbol *Label = context.CreateTempSymbol();
812 MCOS->EmitLabel(Label);
814 // Create and entry for the info and add it to the other entries.
815 MCGenDwarfLabelEntry *Entry =
816 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
817 MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
820 static int getDataAlignmentFactor(MCStreamer &streamer) {
821 MCContext &context = streamer.getContext();
822 const MCAsmInfo *asmInfo = context.getAsmInfo();
823 int size = asmInfo->getCalleeSaveStackSlotSize();
824 if (asmInfo->isStackGrowthDirectionUp())
830 static unsigned getSizeForEncoding(MCStreamer &streamer,
831 unsigned symbolEncoding) {
832 MCContext &context = streamer.getContext();
833 unsigned format = symbolEncoding & 0x0f;
835 default: llvm_unreachable("Unknown Encoding");
836 case dwarf::DW_EH_PE_absptr:
837 case dwarf::DW_EH_PE_signed:
838 return context.getAsmInfo()->getPointerSize();
839 case dwarf::DW_EH_PE_udata2:
840 case dwarf::DW_EH_PE_sdata2:
842 case dwarf::DW_EH_PE_udata4:
843 case dwarf::DW_EH_PE_sdata4:
845 case dwarf::DW_EH_PE_udata8:
846 case dwarf::DW_EH_PE_sdata8:
851 static void EmitFDESymbol(MCStreamer &streamer, const MCSymbol &symbol,
852 unsigned symbolEncoding, bool isEH,
853 const char *comment = 0) {
854 MCContext &context = streamer.getContext();
855 const MCAsmInfo *asmInfo = context.getAsmInfo();
856 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
859 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
860 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
861 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
862 streamer.EmitAbsValue(v, size);
864 streamer.EmitValue(v, size);
867 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
868 unsigned symbolEncoding) {
869 MCContext &context = streamer.getContext();
870 const MCAsmInfo *asmInfo = context.getAsmInfo();
871 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
874 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
875 streamer.EmitValue(v, size);
879 class FrameEmitterImpl {
884 const MCSymbol *SectionStart;
886 FrameEmitterImpl(bool usingCFI, bool isEH)
887 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
890 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
892 /// EmitCompactUnwind - Emit the unwind information in a compact way.
893 void EmitCompactUnwind(MCStreamer &streamer,
894 const MCDwarfFrameInfo &frame);
896 const MCSymbol &EmitCIE(MCStreamer &streamer,
897 const MCSymbol *personality,
898 unsigned personalityEncoding,
899 const MCSymbol *lsda,
901 unsigned lsdaEncoding,
903 MCSymbol *EmitFDE(MCStreamer &streamer,
904 const MCSymbol &cieStart,
905 const MCDwarfFrameInfo &frame);
906 void EmitCFIInstructions(MCStreamer &streamer,
907 ArrayRef<MCCFIInstruction> Instrs,
908 MCSymbol *BaseLabel);
909 void EmitCFIInstruction(MCStreamer &Streamer,
910 const MCCFIInstruction &Instr);
913 } // end anonymous namespace
915 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
917 if (Streamer.isVerboseAsm()) {
920 default: EncStr = "<unknown encoding>"; break;
921 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break;
922 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break;
923 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break;
924 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break;
925 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break;
926 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break;
927 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break;
928 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
929 EncStr = "pcrel udata4";
931 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
932 EncStr = "pcrel sdata4";
934 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
935 EncStr = "pcrel udata8";
937 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
938 EncStr = "screl sdata8";
940 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
941 EncStr = "indirect pcrel udata4";
943 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
944 EncStr = "indirect pcrel sdata4";
946 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
947 EncStr = "indirect pcrel udata8";
949 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
950 EncStr = "indirect pcrel sdata8";
954 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
957 Streamer.EmitIntValue(Encoding, 1);
960 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
961 const MCCFIInstruction &Instr) {
962 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
963 bool VerboseAsm = Streamer.isVerboseAsm();
965 switch (Instr.getOperation()) {
966 case MCCFIInstruction::OpRegister: {
967 unsigned Reg1 = Instr.getRegister();
968 unsigned Reg2 = Instr.getRegister2();
970 Streamer.AddComment("DW_CFA_register");
971 Streamer.AddComment(Twine("Reg1 ") + Twine(Reg1));
972 Streamer.AddComment(Twine("Reg2 ") + Twine(Reg2));
974 Streamer.EmitIntValue(dwarf::DW_CFA_register, 1);
975 Streamer.EmitULEB128IntValue(Reg1);
976 Streamer.EmitULEB128IntValue(Reg2);
979 case MCCFIInstruction::OpWindowSave: {
980 Streamer.EmitIntValue(dwarf::DW_CFA_GNU_window_save, 1);
983 case MCCFIInstruction::OpUndefined: {
984 unsigned Reg = Instr.getRegister();
986 Streamer.AddComment("DW_CFA_undefined");
987 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
989 Streamer.EmitIntValue(dwarf::DW_CFA_undefined, 1);
990 Streamer.EmitULEB128IntValue(Reg);
993 case MCCFIInstruction::OpAdjustCfaOffset:
994 case MCCFIInstruction::OpDefCfaOffset: {
995 const bool IsRelative =
996 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
999 Streamer.AddComment("DW_CFA_def_cfa_offset");
1000 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
1003 CFAOffset += Instr.getOffset();
1005 CFAOffset = -Instr.getOffset();
1008 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1009 Streamer.EmitULEB128IntValue(CFAOffset);
1013 case MCCFIInstruction::OpDefCfa: {
1015 Streamer.AddComment("DW_CFA_def_cfa");
1016 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
1019 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1020 Streamer.EmitULEB128IntValue(Instr.getRegister());
1022 CFAOffset = -Instr.getOffset();
1025 Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
1026 Streamer.EmitULEB128IntValue(CFAOffset);
1031 case MCCFIInstruction::OpDefCfaRegister: {
1033 Streamer.AddComment("DW_CFA_def_cfa_register");
1034 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
1037 Streamer.AddComment(Twine("Reg ") + Twine(Instr.getRegister()));
1038 Streamer.EmitULEB128IntValue(Instr.getRegister());
1043 case MCCFIInstruction::OpOffset:
1044 case MCCFIInstruction::OpRelOffset: {
1045 const bool IsRelative =
1046 Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1048 unsigned Reg = Instr.getRegister();
1049 int Offset = Instr.getOffset();
1051 Offset -= CFAOffset;
1052 Offset = Offset / dataAlignmentFactor;
1055 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
1056 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
1057 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1058 Streamer.EmitULEB128IntValue(Reg);
1059 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1060 Streamer.EmitSLEB128IntValue(Offset);
1061 } else if (Reg < 64) {
1062 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
1064 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
1065 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1066 Streamer.EmitULEB128IntValue(Offset);
1068 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
1069 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
1070 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1071 Streamer.EmitULEB128IntValue(Reg);
1072 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
1073 Streamer.EmitULEB128IntValue(Offset);
1077 case MCCFIInstruction::OpRememberState:
1078 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
1079 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
1081 case MCCFIInstruction::OpRestoreState:
1082 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
1083 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
1085 case MCCFIInstruction::OpSameValue: {
1086 unsigned Reg = Instr.getRegister();
1087 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
1088 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
1089 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1090 Streamer.EmitULEB128IntValue(Reg);
1093 case MCCFIInstruction::OpRestore: {
1094 unsigned Reg = Instr.getRegister();
1096 Streamer.AddComment("DW_CFA_restore");
1097 Streamer.AddComment(Twine("Reg ") + Twine(Reg));
1099 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
1102 case MCCFIInstruction::OpEscape:
1103 if (VerboseAsm) Streamer.AddComment("Escape bytes");
1104 Streamer.EmitBytes(Instr.getValues());
1107 llvm_unreachable("Unhandled case in switch");
1110 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1112 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
1113 ArrayRef<MCCFIInstruction> Instrs,
1114 MCSymbol *BaseLabel) {
1115 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
1116 const MCCFIInstruction &Instr = Instrs[i];
1117 MCSymbol *Label = Instr.getLabel();
1118 // Throw out move if the label is invalid.
1119 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1121 // Advance row if new location.
1122 if (BaseLabel && Label) {
1123 MCSymbol *ThisSym = Label;
1124 if (ThisSym != BaseLabel) {
1125 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
1126 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1127 BaseLabel = ThisSym;
1131 EmitCFIInstruction(streamer, Instr);
1135 /// EmitCompactUnwind - Emit the unwind information in a compact way.
1136 void FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
1137 const MCDwarfFrameInfo &Frame) {
1138 MCContext &Context = Streamer.getContext();
1139 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1140 bool VerboseAsm = Streamer.isVerboseAsm();
1142 // range-start range-length compact-unwind-enc personality-func lsda
1143 // _foo LfooEnd-_foo 0x00000023 0 0
1144 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
1146 // .section __LD,__compact_unwind,regular,debug
1148 // # compact unwind for _foo
1150 // .set L1,LfooEnd-_foo
1156 // # compact unwind for _bar
1158 // .set L2,LbarEnd-_bar
1161 // .quad __gxx_personality
1162 // .quad except_tab1
1164 uint32_t Encoding = Frame.CompactUnwindEncoding;
1165 if (!Encoding) return;
1166 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1168 // The encoding needs to know we have an LSDA.
1169 if (!DwarfEHFrameOnly && Frame.Lsda)
1170 Encoding |= 0x40000000;
1173 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
1174 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1175 if (VerboseAsm) Streamer.AddComment("Range Start");
1176 Streamer.EmitSymbolValue(Frame.Function, Size);
1179 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
1181 if (VerboseAsm) Streamer.AddComment("Range Length");
1182 Streamer.EmitAbsValue(Range, 4);
1185 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1186 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
1187 Twine::utohexstr(Encoding));
1188 Streamer.EmitIntValue(Encoding, Size);
1190 // Personality Function
1191 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1192 if (VerboseAsm) Streamer.AddComment("Personality Function");
1193 if (!DwarfEHFrameOnly && Frame.Personality)
1194 Streamer.EmitSymbolValue(Frame.Personality, Size);
1196 Streamer.EmitIntValue(0, Size); // No personality fn
1199 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1200 if (VerboseAsm) Streamer.AddComment("LSDA");
1201 if (!DwarfEHFrameOnly && Frame.Lsda)
1202 Streamer.EmitSymbolValue(Frame.Lsda, Size);
1204 Streamer.EmitIntValue(0, Size); // No LSDA
1207 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
1208 const MCSymbol *personality,
1209 unsigned personalityEncoding,
1210 const MCSymbol *lsda,
1212 unsigned lsdaEncoding,
1214 MCContext &context = streamer.getContext();
1215 const MCRegisterInfo *MRI = context.getRegisterInfo();
1216 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1217 bool verboseAsm = streamer.isVerboseAsm();
1219 MCSymbol *sectionStart;
1220 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
1221 sectionStart = context.CreateTempSymbol();
1223 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
1225 streamer.EmitLabel(sectionStart);
1228 MCSymbol *sectionEnd = context.CreateTempSymbol();
1231 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
1233 if (verboseAsm) streamer.AddComment("CIE Length");
1234 streamer.EmitAbsValue(Length, 4);
1237 unsigned CIE_ID = IsEH ? 0 : -1;
1238 if (verboseAsm) streamer.AddComment("CIE ID Tag");
1239 streamer.EmitIntValue(CIE_ID, 4);
1242 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
1243 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
1245 // Augmentation String
1246 SmallString<8> Augmentation;
1248 if (verboseAsm) streamer.AddComment("CIE Augmentation");
1249 Augmentation += "z";
1251 Augmentation += "P";
1253 Augmentation += "L";
1254 Augmentation += "R";
1256 Augmentation += "S";
1257 streamer.EmitBytes(Augmentation.str());
1259 streamer.EmitIntValue(0, 1);
1261 // Code Alignment Factor
1262 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
1263 streamer.EmitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1265 // Data Alignment Factor
1266 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
1267 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
1269 // Return Address Register
1270 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
1271 streamer.EmitULEB128IntValue(MRI->getDwarfRegNum(MRI->getRARegister(), true));
1273 // Augmentation Data Length (optional)
1275 unsigned augmentationLength = 0;
1278 // Personality Encoding
1279 augmentationLength += 1;
1281 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
1284 augmentationLength += 1;
1285 // Encoding of the FDE pointers
1286 augmentationLength += 1;
1288 if (verboseAsm) streamer.AddComment("Augmentation Size");
1289 streamer.EmitULEB128IntValue(augmentationLength);
1291 // Augmentation Data (optional)
1293 // Personality Encoding
1294 EmitEncodingByte(streamer, personalityEncoding,
1295 "Personality Encoding");
1297 if (verboseAsm) streamer.AddComment("Personality");
1298 EmitPersonality(streamer, *personality, personalityEncoding);
1302 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
1304 // Encoding of the FDE pointers
1305 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
1309 // Initial Instructions
1311 const MCAsmInfo *MAI = context.getAsmInfo();
1313 const std::vector<MCCFIInstruction> &Instructions =
1314 MAI->getInitialFrameState();
1315 EmitCFIInstructions(streamer, Instructions, NULL);
1319 streamer.EmitValueToAlignment(IsEH ? 4 : MAI->getPointerSize());
1321 streamer.EmitLabel(sectionEnd);
1322 return *sectionStart;
1325 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
1326 const MCSymbol &cieStart,
1327 const MCDwarfFrameInfo &frame) {
1328 MCContext &context = streamer.getContext();
1329 MCSymbol *fdeStart = context.CreateTempSymbol();
1330 MCSymbol *fdeEnd = context.CreateTempSymbol();
1331 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1332 bool verboseAsm = streamer.isVerboseAsm();
1334 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
1336 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
1337 streamer.EmitEHSymAttributes(frame.Function, EHSym);
1338 streamer.EmitLabel(EHSym);
1342 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
1343 if (verboseAsm) streamer.AddComment("FDE Length");
1344 streamer.EmitAbsValue(Length, 4);
1346 streamer.EmitLabel(fdeStart);
1349 const MCAsmInfo *asmInfo = context.getAsmInfo();
1351 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
1353 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
1354 streamer.EmitAbsValue(offset, 4);
1355 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1356 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
1358 streamer.EmitAbsValue(offset, 4);
1360 streamer.EmitSymbolValue(&cieStart, 4);
1364 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI)
1365 : (unsigned)dwarf::DW_EH_PE_absptr;
1366 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding);
1367 EmitFDESymbol(streamer, *frame.Begin, PCEncoding, IsEH, "FDE initial location");
1370 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
1372 if (verboseAsm) streamer.AddComment("FDE address range");
1373 streamer.EmitAbsValue(Range, PCSize);
1376 // Augmentation Data Length
1377 unsigned augmentationLength = 0;
1380 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
1382 if (verboseAsm) streamer.AddComment("Augmentation size");
1383 streamer.EmitULEB128IntValue(augmentationLength);
1385 // Augmentation Data
1387 EmitFDESymbol(streamer, *frame.Lsda, frame.LsdaEncoding, true,
1388 "Language Specific Data Area");
1391 // Call Frame Instructions
1392 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
1395 streamer.EmitValueToAlignment(PCSize);
1402 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false, false); }
1403 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false, false); }
1405 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
1406 unsigned LsdaEncoding_, bool IsSignalFrame_, bool IsSimple_) :
1407 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
1408 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_),
1409 IsSimple(IsSimple_) {
1411 const MCSymbol* Personality;
1412 unsigned PersonalityEncoding;
1413 unsigned LsdaEncoding;
1421 struct DenseMapInfo<CIEKey> {
1422 static CIEKey getEmptyKey() {
1423 return CIEKey::getEmptyKey();
1425 static CIEKey getTombstoneKey() {
1426 return CIEKey::getTombstoneKey();
1428 static unsigned getHashValue(const CIEKey &Key) {
1429 return static_cast<unsigned>(hash_combine(Key.Personality,
1430 Key.PersonalityEncoding,
1435 static bool isEqual(const CIEKey &LHS,
1436 const CIEKey &RHS) {
1437 return LHS.Personality == RHS.Personality &&
1438 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1439 LHS.LsdaEncoding == RHS.LsdaEncoding &&
1440 LHS.IsSignalFrame == RHS.IsSignalFrame &&
1441 LHS.IsSimple == RHS.IsSimple;
1446 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, MCAsmBackend *MAB,
1447 bool UsingCFI, bool IsEH) {
1448 Streamer.generateCompactUnwindEncodings(MAB);
1450 MCContext &Context = Streamer.getContext();
1451 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1452 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1453 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1455 // Emit the compact unwind info if available.
1456 if (IsEH && MOFI->getCompactUnwindSection()) {
1457 bool SectionEmitted = false;
1458 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1459 const MCDwarfFrameInfo &Frame = FrameArray[i];
1460 if (Frame.CompactUnwindEncoding == 0) continue;
1461 if (!SectionEmitted) {
1462 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1463 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1464 SectionEmitted = true;
1466 Emitter.EmitCompactUnwind(Streamer, Frame);
1470 const MCSection &Section =
1471 IsEH ? *const_cast<MCObjectFileInfo*>(MOFI)->getEHFrameSection() :
1472 *MOFI->getDwarfFrameSection();
1473 Streamer.SwitchSection(&Section);
1474 MCSymbol *SectionStart = Context.CreateTempSymbol();
1475 Streamer.EmitLabel(SectionStart);
1476 Emitter.setSectionStart(SectionStart);
1478 MCSymbol *FDEEnd = NULL;
1479 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1481 const MCSymbol *DummyDebugKey = NULL;
1482 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1483 const MCDwarfFrameInfo &Frame = FrameArray[i];
1484 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1485 Frame.LsdaEncoding, Frame.IsSignalFrame, Frame.IsSimple);
1486 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1488 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1489 Frame.PersonalityEncoding, Frame.Lsda,
1490 Frame.IsSignalFrame,
1494 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1497 Streamer.EmitLabel(FDEEnd);
1500 Streamer.EmitValueToAlignment(Context.getAsmInfo()->getPointerSize());
1502 Streamer.EmitLabel(FDEEnd);
1505 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1506 uint64_t AddrDelta) {
1507 MCContext &Context = Streamer.getContext();
1508 SmallString<256> Tmp;
1509 raw_svector_ostream OS(Tmp);
1510 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1511 Streamer.EmitBytes(OS.str());
1514 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1517 // Scale the address delta by the minimum instruction length.
1518 AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1520 if (AddrDelta == 0) {
1521 } else if (isUIntN(6, AddrDelta)) {
1522 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1524 } else if (isUInt<8>(AddrDelta)) {
1525 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1526 OS << uint8_t(AddrDelta);
1527 } else if (isUInt<16>(AddrDelta)) {
1528 // FIXME: check what is the correct behavior on a big endian machine.
1529 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1530 OS << uint8_t( AddrDelta & 0xff);
1531 OS << uint8_t((AddrDelta >> 8) & 0xff);
1533 // FIXME: check what is the correct behavior on a big endian machine.
1534 assert(isUInt<32>(AddrDelta));
1535 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1536 OS << uint8_t( AddrDelta & 0xff);
1537 OS << uint8_t((AddrDelta >> 8) & 0xff);
1538 OS << uint8_t((AddrDelta >> 16) & 0xff);
1539 OS << uint8_t((AddrDelta >> 24) & 0xff);