1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCDwarf.h"
11 #include "llvm/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCObjectFileInfo.h"
14 #include "llvm/MC/MCObjectWriter.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/Twine.h"
27 // Given a special op, return the address skip amount (in units of
28 // DWARF2_LINE_MIN_INSN_LENGTH.
29 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
31 // The maximum address skip amount that can be encoded with a special op.
32 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255)
34 // First special line opcode - leave room for the standard opcodes.
35 // Note: If you want to change this, you'll have to update the
36 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().
37 #define DWARF2_LINE_OPCODE_BASE 13
39 // Minimum line offset in a special line info. opcode. This value
40 // was chosen to give a reasonable range of values.
41 #define DWARF2_LINE_BASE -5
43 // Range of line offsets in a special line info. opcode.
44 #define DWARF2_LINE_RANGE 14
46 // Define the architecture-dependent minimum instruction length (in bytes).
47 // This value should be rather too small than too big.
48 #define DWARF2_LINE_MIN_INSN_LENGTH 1
50 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
51 // this routine is a nop and will be optimized away.
52 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) {
53 if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
55 if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
56 // TODO: report this error, but really only once.
59 return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
63 // This is called when an instruction is assembled into the specified section
64 // and if there is information from the last .loc directive that has yet to have
65 // a line entry made for it is made.
67 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) {
68 if (!MCOS->getContext().getDwarfLocSeen())
71 // Create a symbol at in the current section for use in the line entry.
72 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
73 // Set the value of the symbol to use for the MCLineEntry.
74 MCOS->EmitLabel(LineSym);
76 // Get the current .loc info saved in the context.
77 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
79 // Create a (local) line entry with the symbol and the current .loc info.
80 MCLineEntry LineEntry(LineSym, DwarfLoc);
82 // clear DwarfLocSeen saying the current .loc info is now used.
83 MCOS->getContext().ClearDwarfLocSeen();
85 // Get the MCLineSection for this section, if one does not exist for this
87 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
88 MCOS->getContext().getMCLineSections();
89 MCLineSection *LineSection = MCLineSections.lookup(Section);
91 // Create a new MCLineSection. This will be deleted after the dwarf line
92 // table is created using it by iterating through the MCLineSections
94 LineSection = new MCLineSection;
95 // Save a pointer to the new LineSection into the MCLineSections DenseMap.
96 MCOS->getContext().addMCLineSection(Section, LineSection);
99 // Add the line entry to this section's entries.
100 LineSection->addLineEntry(LineEntry);
104 // This helper routine returns an expression of End - Start + IntVal .
106 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS,
107 const MCSymbol &Start,
110 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
112 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
114 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
116 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
118 MCConstantExpr::Create(IntVal, MCOS.getContext());
120 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
125 // This emits the Dwarf line table for the specified section from the entries
126 // in the LineSection.
128 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
129 const MCSection *Section,
130 const MCLineSection *LineSection) {
131 unsigned FileNum = 1;
132 unsigned LastLine = 1;
134 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
136 MCSymbol *LastLabel = NULL;
138 // Loop through each MCLineEntry and encode the dwarf line number table.
139 for (MCLineSection::const_iterator
140 it = LineSection->getMCLineEntries()->begin(),
141 ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
143 if (FileNum != it->getFileNum()) {
144 FileNum = it->getFileNum();
145 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
146 MCOS->EmitULEB128IntValue(FileNum);
148 if (Column != it->getColumn()) {
149 Column = it->getColumn();
150 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
151 MCOS->EmitULEB128IntValue(Column);
153 if (Isa != it->getIsa()) {
155 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
156 MCOS->EmitULEB128IntValue(Isa);
158 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
159 Flags = it->getFlags();
160 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
162 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
163 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
164 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
165 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
166 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
167 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
169 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
170 MCSymbol *Label = it->getLabel();
172 // At this point we want to emit/create the sequence to encode the delta in
173 // line numbers and the increment of the address from the previous Label
174 // and the current Label.
175 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
176 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
177 asmInfo.getPointerSize());
179 LastLine = it->getLine();
183 // Emit a DW_LNE_end_sequence for the end of the section.
184 // Using the pointer Section create a temporary label at the end of the
185 // section and use that and the LastLabel to compute the address delta
186 // and use INT64_MAX as the line delta which is the signal that this is
187 // actually a DW_LNE_end_sequence.
189 // Switch to the section to be able to create a symbol at its end.
190 MCOS->SwitchSection(Section);
192 MCContext &context = MCOS->getContext();
193 // Create a symbol at the end of the section.
194 MCSymbol *SectionEnd = context.CreateTempSymbol();
195 // Set the value of the symbol, as we are at the end of the section.
196 MCOS->EmitLabel(SectionEnd);
198 // Switch back the the dwarf line section.
199 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
201 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo();
202 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
203 asmInfo.getPointerSize());
207 // This emits the Dwarf file and the line tables.
209 void MCDwarfFileTable::Emit(MCStreamer *MCOS) {
210 MCContext &context = MCOS->getContext();
211 // Switch to the section where the table will be emitted into.
212 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
214 // Create a symbol at the beginning of this section.
215 MCSymbol *LineStartSym = context.CreateTempSymbol();
216 // Set the value of the symbol, as we are at the start of the section.
217 MCOS->EmitLabel(LineStartSym);
219 // Create a symbol for the end of the section (to be set when we get there).
220 MCSymbol *LineEndSym = context.CreateTempSymbol();
222 // The first 4 bytes is the total length of the information for this
223 // compilation unit (not including these 4 bytes for the length).
224 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
227 // Next 2 bytes is the Version, which is Dwarf 2.
228 MCOS->EmitIntValue(2, 2);
230 // Create a symbol for the end of the prologue (to be set when we get there).
231 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end
233 // Length of the prologue, is the next 4 bytes. Which is the start of the
234 // section to the end of the prologue. Not including the 4 bytes for the
235 // total length, the 2 bytes for the version, and these 4 bytes for the
236 // length of the prologue.
237 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
241 // Parameters of the state machine, are next.
242 MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
243 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
244 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
245 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
246 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
248 // Standard opcode lengths
249 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
250 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
251 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
252 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
253 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
254 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
255 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
256 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
257 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
258 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
259 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
260 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
262 // Put out the directory and file tables.
264 // First the directory table.
265 const std::vector<StringRef> &MCDwarfDirs =
266 context.getMCDwarfDirs();
267 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
268 MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
269 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
271 MCOS->EmitIntValue(0, 1); // Terminate the directory list
273 // Second the file table.
274 const std::vector<MCDwarfFile *> &MCDwarfFiles =
275 MCOS->getContext().getMCDwarfFiles();
276 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
277 MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
278 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
280 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
281 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
282 MCOS->EmitIntValue(0, 1); // filesize (always 0)
284 MCOS->EmitIntValue(0, 1); // Terminate the file list
286 // This is the end of the prologue, so set the value of the symbol at the
287 // end of the prologue (that was used in a previous expression).
288 MCOS->EmitLabel(ProEndSym);
290 // Put out the line tables.
291 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
292 MCOS->getContext().getMCLineSections();
293 const std::vector<const MCSection *> &MCLineSectionOrder =
294 MCOS->getContext().getMCLineSectionOrder();
295 for (std::vector<const MCSection*>::const_iterator it =
296 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
298 const MCSection *Sec = *it;
299 const MCLineSection *Line = MCLineSections.lookup(Sec);
300 EmitDwarfLineTable(MCOS, Sec, Line);
302 // Now delete the MCLineSections that were created in MCLineEntry::Make()
303 // and used to emit the line table.
307 if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
308 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
309 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
311 // total_length >= prologue_length + 10
312 // We are 4 bytes short, since we have total_length = 51 and
313 // prologue_length = 45
315 // The regular end_sequence should be sufficient.
316 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
319 // This is the end of the section, so set the value of the symbol at the end
320 // of this section (that was used in a previous expression).
321 MCOS->EmitLabel(LineEndSym);
324 /// Utility function to write the encoding to an object writer.
325 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
326 uint64_t AddrDelta) {
327 SmallString<256> Tmp;
328 raw_svector_ostream OS(Tmp);
329 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
330 OW->WriteBytes(OS.str());
333 /// Utility function to emit the encoding to a streamer.
334 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
335 uint64_t AddrDelta) {
336 SmallString<256> Tmp;
337 raw_svector_ostream OS(Tmp);
338 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
339 MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
342 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
343 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
345 uint64_t Temp, Opcode;
346 bool NeedCopy = false;
348 // Scale the address delta by the minimum instruction length.
349 AddrDelta = ScaleAddrDelta(AddrDelta);
351 // A LineDelta of INT64_MAX is a signal that this is actually a
352 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
353 // end_sequence to emit the matrix entry.
354 if (LineDelta == INT64_MAX) {
355 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
356 OS << char(dwarf::DW_LNS_const_add_pc);
358 OS << char(dwarf::DW_LNS_advance_pc);
359 MCObjectWriter::EncodeULEB128(AddrDelta, OS);
361 OS << char(dwarf::DW_LNS_extended_op);
363 OS << char(dwarf::DW_LNE_end_sequence);
367 // Bias the line delta by the base.
368 Temp = LineDelta - DWARF2_LINE_BASE;
370 // If the line increment is out of range of a special opcode, we must encode
371 // it with DW_LNS_advance_line.
372 if (Temp >= DWARF2_LINE_RANGE) {
373 OS << char(dwarf::DW_LNS_advance_line);
374 MCObjectWriter::EncodeSLEB128(LineDelta, OS);
377 Temp = 0 - DWARF2_LINE_BASE;
381 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
382 if (LineDelta == 0 && AddrDelta == 0) {
383 OS << char(dwarf::DW_LNS_copy);
387 // Bias the opcode by the special opcode base.
388 Temp += DWARF2_LINE_OPCODE_BASE;
390 // Avoid overflow when addr_delta is large.
391 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
392 // Try using a special opcode.
393 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
399 // Try using DW_LNS_const_add_pc followed by special op.
400 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
402 OS << char(dwarf::DW_LNS_const_add_pc);
408 // Otherwise use DW_LNS_advance_pc.
409 OS << char(dwarf::DW_LNS_advance_pc);
410 MCObjectWriter::EncodeULEB128(AddrDelta, OS);
413 OS << char(dwarf::DW_LNS_copy);
418 void MCDwarfFile::print(raw_ostream &OS) const {
419 OS << '"' << getName() << '"';
422 void MCDwarfFile::dump() const {
426 static int getDataAlignmentFactor(MCStreamer &streamer) {
427 MCContext &context = streamer.getContext();
428 const MCAsmInfo &asmInfo = context.getAsmInfo();
429 int size = asmInfo.getPointerSize();
430 if (asmInfo.isStackGrowthDirectionUp())
436 static unsigned getSizeForEncoding(MCStreamer &streamer,
437 unsigned symbolEncoding) {
438 MCContext &context = streamer.getContext();
439 unsigned format = symbolEncoding & 0x0f;
442 assert(0 && "Unknown Encoding");
443 case dwarf::DW_EH_PE_absptr:
444 case dwarf::DW_EH_PE_signed:
445 return context.getAsmInfo().getPointerSize();
446 case dwarf::DW_EH_PE_udata2:
447 case dwarf::DW_EH_PE_sdata2:
449 case dwarf::DW_EH_PE_udata4:
450 case dwarf::DW_EH_PE_sdata4:
452 case dwarf::DW_EH_PE_udata8:
453 case dwarf::DW_EH_PE_sdata8:
458 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol,
459 unsigned symbolEncoding, const char *comment = 0) {
460 MCContext &context = streamer.getContext();
461 const MCAsmInfo &asmInfo = context.getAsmInfo();
462 const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol,
465 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
466 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment);
467 streamer.EmitAbsValue(v, size);
470 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
471 unsigned symbolEncoding) {
472 MCContext &context = streamer.getContext();
473 const MCAsmInfo &asmInfo = context.getAsmInfo();
474 const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol,
477 unsigned size = getSizeForEncoding(streamer, symbolEncoding);
478 streamer.EmitValue(v, size);
481 static const MachineLocation TranslateMachineLocation(
482 const MCRegisterInfo &MRI,
483 const MachineLocation &Loc) {
484 unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ?
485 MachineLocation::VirtualFP :
486 unsigned(MRI.getDwarfRegNum(Loc.getReg(), true));
487 const MachineLocation &NewLoc = Loc.isReg() ?
488 MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset());
493 class FrameEmitterImpl {
498 const MCSymbol *SectionStart;
500 FrameEmitterImpl(bool usingCFI, bool isEH)
501 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH),
504 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; }
506 /// EmitCompactUnwind - Emit the unwind information in a compact way. If
507 /// we're successful, return 'true'. Otherwise, return 'false' and it will
508 /// emit the normal CIE and FDE.
509 bool EmitCompactUnwind(MCStreamer &streamer,
510 const MCDwarfFrameInfo &frame);
512 const MCSymbol &EmitCIE(MCStreamer &streamer,
513 const MCSymbol *personality,
514 unsigned personalityEncoding,
515 const MCSymbol *lsda,
516 unsigned lsdaEncoding);
517 MCSymbol *EmitFDE(MCStreamer &streamer,
518 const MCSymbol &cieStart,
519 const MCDwarfFrameInfo &frame);
520 void EmitCFIInstructions(MCStreamer &streamer,
521 const std::vector<MCCFIInstruction> &Instrs,
522 MCSymbol *BaseLabel);
523 void EmitCFIInstruction(MCStreamer &Streamer,
524 const MCCFIInstruction &Instr);
527 } // end anonymous namespace
529 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
531 if (Streamer.isVerboseAsm()) {
532 const char *EncStr = 0;
534 default: EncStr = "<unknown encoding>";
535 case dwarf::DW_EH_PE_absptr: EncStr = "absptr";
536 case dwarf::DW_EH_PE_omit: EncStr = "omit";
537 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel";
538 case dwarf::DW_EH_PE_udata4: EncStr = "udata4";
539 case dwarf::DW_EH_PE_udata8: EncStr = "udata8";
540 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4";
541 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8";
542 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: EncStr = "pcrel udata4";
543 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: EncStr = "pcrel sdata4";
544 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: EncStr = "pcrel udata8";
545 case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: EncStr = "pcrel sdata8";
546 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4:
547 EncStr = "indirect pcrel udata4";
548 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4:
549 EncStr = "indirect pcrel sdata4";
550 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8:
551 EncStr = "indirect pcrel udata8";
552 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8:
553 EncStr = "indirect pcrel sdata8";
556 Streamer.AddComment(Twine(Prefix) + " = " + EncStr);
559 Streamer.EmitIntValue(Encoding, 1);
562 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer,
563 const MCCFIInstruction &Instr) {
564 int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
565 bool VerboseAsm = Streamer.isVerboseAsm();
567 switch (Instr.getOperation()) {
568 case MCCFIInstruction::Move:
569 case MCCFIInstruction::RelMove: {
570 const MachineLocation &Dst = Instr.getDestination();
571 const MachineLocation &Src = Instr.getSource();
572 const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove;
575 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
576 if (Src.getReg() == MachineLocation::VirtualFP) {
577 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset");
578 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1);
580 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa");
581 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1);
582 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") +
583 Twine(Src.getReg()));
584 Streamer.EmitULEB128IntValue(Src.getReg());
588 CFAOffset += Src.getOffset();
590 CFAOffset = -Src.getOffset();
592 if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset)));
593 Streamer.EmitULEB128IntValue(CFAOffset);
597 if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) {
598 assert(Dst.isReg() && "Machine move not supported yet.");
599 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register");
600 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1);
601 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg()));
602 Streamer.EmitULEB128IntValue(Dst.getReg());
606 unsigned Reg = Src.getReg();
607 int Offset = Dst.getOffset();
610 Offset = Offset / dataAlignmentFactor;
613 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf");
614 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1);
615 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
616 Streamer.EmitULEB128IntValue(Reg);
617 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
618 Streamer.EmitSLEB128IntValue(Offset);
619 } else if (Reg < 64) {
620 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") +
622 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1);
623 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
624 Streamer.EmitULEB128IntValue(Offset);
626 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended");
627 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1);
628 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
629 Streamer.EmitULEB128IntValue(Reg);
630 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset));
631 Streamer.EmitULEB128IntValue(Offset);
635 case MCCFIInstruction::Remember:
636 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
637 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
639 case MCCFIInstruction::Restore:
640 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
641 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
643 case MCCFIInstruction::SameValue: {
644 unsigned Reg = Instr.getDestination().getReg();
645 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value");
646 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1);
647 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg));
648 Streamer.EmitULEB128IntValue(Reg);
652 llvm_unreachable("Unhandled case in switch");
655 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
657 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer,
658 const std::vector<MCCFIInstruction> &Instrs,
659 MCSymbol *BaseLabel) {
660 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) {
661 const MCCFIInstruction &Instr = Instrs[i];
662 MCSymbol *Label = Instr.getLabel();
663 // Throw out move if the label is invalid.
664 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
666 // Advance row if new location.
667 if (BaseLabel && Label) {
668 MCSymbol *ThisSym = Label;
669 if (ThisSym != BaseLabel) {
670 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4");
671 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
676 EmitCFIInstruction(streamer, Instr);
680 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're
681 /// successful, return 'true'. Otherwise, return 'false' and it will emit the
682 /// normal CIE and FDE.
683 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer,
684 const MCDwarfFrameInfo &Frame) {
685 MCContext &Context = Streamer.getContext();
686 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
687 bool VerboseAsm = Streamer.isVerboseAsm();
689 // range-start range-length compact-unwind-enc personality-func lsda
690 // _foo LfooEnd-_foo 0x00000023 0 0
691 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1
693 // .section __LD,__compact_unwind,regular,debug
695 // # compact unwind for _foo
697 // .set L1,LfooEnd-_foo
703 // # compact unwind for _bar
705 // .set L2,LbarEnd-_bar
708 // .quad __gxx_personality
711 uint32_t Encoding = Frame.CompactUnwindEncoding;
712 if (!Encoding) return false;
714 // The encoding needs to know we have an LSDA.
716 Encoding |= 0x40000000;
718 Streamer.SwitchSection(MOFI->getCompactUnwindSection());
721 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI);
722 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
723 if (VerboseAsm) Streamer.AddComment("Range Start");
724 Streamer.EmitSymbolValue(Frame.Function, Size);
727 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin,
729 if (VerboseAsm) Streamer.AddComment("Range Length");
730 Streamer.EmitAbsValue(Range, 4);
733 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
734 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
735 Twine::utohexstr(Encoding));
736 Streamer.EmitIntValue(Encoding, Size);
739 // Personality Function
740 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
741 if (VerboseAsm) Streamer.AddComment("Personality Function");
742 if (Frame.Personality)
743 Streamer.EmitSymbolValue(Frame.Personality, Size);
745 Streamer.EmitIntValue(0, Size); // No personality fn
748 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
749 if (VerboseAsm) Streamer.AddComment("LSDA");
751 Streamer.EmitSymbolValue(Frame.Lsda, Size);
753 Streamer.EmitIntValue(0, Size); // No LSDA
758 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer,
759 const MCSymbol *personality,
760 unsigned personalityEncoding,
761 const MCSymbol *lsda,
762 unsigned lsdaEncoding) {
763 MCContext &context = streamer.getContext();
764 const MCRegisterInfo &MRI = context.getRegisterInfo();
765 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
766 bool verboseAsm = streamer.isVerboseAsm();
768 MCSymbol *sectionStart;
769 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH)
770 sectionStart = context.CreateTempSymbol();
772 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum));
774 streamer.EmitLabel(sectionStart);
777 MCSymbol *sectionEnd = context.CreateTempSymbol();
780 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart,
782 if (verboseAsm) streamer.AddComment("CIE Length");
783 streamer.EmitAbsValue(Length, 4);
786 unsigned CIE_ID = IsEH ? 0 : -1;
787 if (verboseAsm) streamer.AddComment("CIE ID Tag");
788 streamer.EmitIntValue(CIE_ID, 4);
791 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION");
792 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1);
794 // Augmentation String
795 SmallString<8> Augmentation;
797 if (verboseAsm) streamer.AddComment("CIE Augmentation");
804 streamer.EmitBytes(Augmentation.str(), 0);
806 streamer.EmitIntValue(0, 1);
808 // Code Alignment Factor
809 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor");
810 streamer.EmitULEB128IntValue(1);
812 // Data Alignment Factor
813 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor");
814 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer));
816 // Return Address Register
817 if (verboseAsm) streamer.AddComment("CIE Return Address Column");
818 streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true));
820 // Augmentation Data Length (optional)
822 unsigned augmentationLength = 0;
825 // Personality Encoding
826 augmentationLength += 1;
828 augmentationLength += getSizeForEncoding(streamer, personalityEncoding);
831 augmentationLength += 1;
832 // Encoding of the FDE pointers
833 augmentationLength += 1;
835 if (verboseAsm) streamer.AddComment("Augmentation Size");
836 streamer.EmitULEB128IntValue(augmentationLength);
838 // Augmentation Data (optional)
840 // Personality Encoding
841 EmitEncodingByte(streamer, personalityEncoding,
842 "Personality Encoding");
844 if (verboseAsm) streamer.AddComment("Personality");
845 EmitPersonality(streamer, *personality, personalityEncoding);
849 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding");
851 // Encoding of the FDE pointers
852 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI),
856 // Initial Instructions
858 const MCAsmInfo &MAI = context.getAsmInfo();
859 const std::vector<MachineMove> &Moves = MAI.getInitialFrameState();
860 std::vector<MCCFIInstruction> Instructions;
862 for (int i = 0, n = Moves.size(); i != n; ++i) {
863 MCSymbol *Label = Moves[i].getLabel();
864 const MachineLocation &Dst =
865 TranslateMachineLocation(MRI, Moves[i].getDestination());
866 const MachineLocation &Src =
867 TranslateMachineLocation(MRI, Moves[i].getSource());
868 MCCFIInstruction Inst(Label, Dst, Src);
869 Instructions.push_back(Inst);
872 EmitCFIInstructions(streamer, Instructions, NULL);
875 streamer.EmitValueToAlignment(IsEH
876 ? 4 : context.getAsmInfo().getPointerSize());
878 streamer.EmitLabel(sectionEnd);
879 return *sectionStart;
882 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer,
883 const MCSymbol &cieStart,
884 const MCDwarfFrameInfo &frame) {
885 MCContext &context = streamer.getContext();
886 MCSymbol *fdeStart = context.CreateTempSymbol();
887 MCSymbol *fdeEnd = context.CreateTempSymbol();
888 const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
889 bool verboseAsm = streamer.isVerboseAsm();
891 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) {
893 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh"));
894 streamer.EmitEHSymAttributes(frame.Function, EHSym);
895 streamer.EmitLabel(EHSym);
899 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0);
900 if (verboseAsm) streamer.AddComment("FDE Length");
901 streamer.EmitAbsValue(Length, 4);
903 streamer.EmitLabel(fdeStart);
906 const MCAsmInfo &asmInfo = context.getAsmInfo();
908 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart,
910 if (verboseAsm) streamer.AddComment("FDE CIE Offset");
911 streamer.EmitAbsValue(offset, 4);
912 } else if (!asmInfo.doesDwarfRequireRelocationForSectionOffset()) {
913 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart,
915 streamer.EmitAbsValue(offset, 4);
917 streamer.EmitSymbolValue(&cieStart, 4);
920 unsigned fdeEncoding = MOFI->getFDEEncoding(UsingCFI);
921 unsigned size = getSizeForEncoding(streamer, fdeEncoding);
924 unsigned PCBeginEncoding = IsEH ? fdeEncoding :
925 (unsigned)dwarf::DW_EH_PE_absptr;
926 unsigned PCBeginSize = getSizeForEncoding(streamer, PCBeginEncoding);
927 EmitSymbol(streamer, *frame.Begin, PCBeginEncoding, "FDE initial location");
930 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin,
932 if (verboseAsm) streamer.AddComment("FDE address range");
933 streamer.EmitAbsValue(Range, size);
936 // Augmentation Data Length
937 unsigned augmentationLength = 0;
940 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding);
942 if (verboseAsm) streamer.AddComment("Augmentation size");
943 streamer.EmitULEB128IntValue(augmentationLength);
947 EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding,
948 "Language Specific Data Area");
951 // Call Frame Instructions
953 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin);
956 streamer.EmitValueToAlignment(PCBeginSize);
963 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1); }
964 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0); }
966 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
967 unsigned LsdaEncoding_) : Personality(Personality_),
968 PersonalityEncoding(PersonalityEncoding_),
969 LsdaEncoding(LsdaEncoding_) {
971 const MCSymbol* Personality;
972 unsigned PersonalityEncoding;
973 unsigned LsdaEncoding;
979 struct DenseMapInfo<CIEKey> {
980 static CIEKey getEmptyKey() {
981 return CIEKey::getEmptyKey();
983 static CIEKey getTombstoneKey() {
984 return CIEKey::getTombstoneKey();
986 static unsigned getHashValue(const CIEKey &Key) {
988 ID.AddPointer(Key.Personality);
989 ID.AddInteger(Key.PersonalityEncoding);
990 ID.AddInteger(Key.LsdaEncoding);
991 return ID.ComputeHash();
993 static bool isEqual(const CIEKey &LHS,
995 return LHS.Personality == RHS.Personality &&
996 LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
997 LHS.LsdaEncoding == RHS.LsdaEncoding;
1002 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer,
1005 MCContext &Context = Streamer.getContext();
1006 MCObjectFileInfo *MOFI =
1007 const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo());
1008 FrameEmitterImpl Emitter(UsingCFI, IsEH);
1009 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos();
1011 // Emit the compact unwind info if available.
1012 // FIXME: This emits both the compact unwind and the old CIE/FDE
1013 // information. Only one of those is needed.
1014 if (IsEH && MOFI->getCompactUnwindSection())
1015 for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) {
1016 const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i);
1017 if (Frame.CompactUnwindEncoding)
1018 Emitter.EmitCompactUnwind(Streamer, Frame);
1021 const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() :
1022 *MOFI->getDwarfFrameSection();
1023 Streamer.SwitchSection(&Section);
1024 MCSymbol *SectionStart = Context.CreateTempSymbol();
1025 Streamer.EmitLabel(SectionStart);
1026 Emitter.setSectionStart(SectionStart);
1028 MCSymbol *FDEEnd = NULL;
1029 DenseMap<CIEKey, const MCSymbol*> CIEStarts;
1031 const MCSymbol *DummyDebugKey = NULL;
1032 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) {
1033 const MCDwarfFrameInfo &Frame = FrameArray[i];
1034 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
1035 Frame.LsdaEncoding);
1036 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1038 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality,
1039 Frame.PersonalityEncoding, Frame.Lsda,
1040 Frame.LsdaEncoding);
1042 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame);
1045 Streamer.EmitLabel(FDEEnd);
1048 Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize());
1050 Streamer.EmitLabel(FDEEnd);
1053 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer,
1054 uint64_t AddrDelta) {
1055 SmallString<256> Tmp;
1056 raw_svector_ostream OS(Tmp);
1057 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS);
1058 Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0);
1061 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta,
1063 // FIXME: Assumes the code alignment factor is 1.
1064 if (AddrDelta == 0) {
1065 } else if (isUIntN(6, AddrDelta)) {
1066 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1068 } else if (isUInt<8>(AddrDelta)) {
1069 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1070 OS << uint8_t(AddrDelta);
1071 } else if (isUInt<16>(AddrDelta)) {
1072 // FIXME: check what is the correct behavior on a big endian machine.
1073 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1074 OS << uint8_t( AddrDelta & 0xff);
1075 OS << uint8_t((AddrDelta >> 8) & 0xff);
1077 // FIXME: check what is the correct behavior on a big endian machine.
1078 assert(isUInt<32>(AddrDelta));
1079 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1080 OS << uint8_t( AddrDelta & 0xff);
1081 OS << uint8_t((AddrDelta >> 8) & 0xff);
1082 OS << uint8_t((AddrDelta >> 16) & 0xff);
1083 OS << uint8_t((AddrDelta >> 24) & 0xff);