1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/MC/MCDwarf.h" 11 #include "llvm/MC/MCAsmInfo.h" 12 #include "llvm/MC/MCContext.h" 13 #include "llvm/MC/MCObjectFileInfo.h" 14 #include "llvm/MC/MCObjectWriter.h" 15 #include "llvm/MC/MCRegisterInfo.h" 16 #include "llvm/MC/MCStreamer.h" 17 #include "llvm/MC/MCSymbol.h" 18 #include "llvm/MC/MCExpr.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/ErrorHandling.h" 21 #include "llvm/Support/raw_ostream.h" 22 #include "llvm/Support/LEB128.h" 23 #include "llvm/Support/Path.h" 24 #include "llvm/Support/SourceMgr.h" 25 #include "llvm/ADT/Hashing.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/Twine.h" 28 #include "llvm/Config/config.h" 29 using namespace llvm; 30 31 // Given a special op, return the address skip amount (in units of 32 // DWARF2_LINE_MIN_INSN_LENGTH. 33 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE) 34 35 // The maximum address skip amount that can be encoded with a special op. 36 #define MAX_SPECIAL_ADDR_DELTA SPECIAL_ADDR(255) 37 38 // First special line opcode - leave room for the standard opcodes. 39 // Note: If you want to change this, you'll have to update the 40 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit(). 41 #define DWARF2_LINE_OPCODE_BASE 13 42 43 // Minimum line offset in a special line info. opcode. This value 44 // was chosen to give a reasonable range of values. 45 #define DWARF2_LINE_BASE -5 46 47 // Range of line offsets in a special line info. opcode. 48 #define DWARF2_LINE_RANGE 14 49 50 // Define the architecture-dependent minimum instruction length (in bytes). 51 // This value should be rather too small than too big. 52 #define DWARF2_LINE_MIN_INSN_LENGTH 1 53 54 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting, 55 // this routine is a nop and will be optimized away. 56 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta) { 57 if (DWARF2_LINE_MIN_INSN_LENGTH == 1) 58 return AddrDelta; 59 if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) { 60 // TODO: report this error, but really only once. 61 ; 62 } 63 return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH; 64 } 65 66 // 67 // This is called when an instruction is assembled into the specified section 68 // and if there is information from the last .loc directive that has yet to have 69 // a line entry made for it is made. 70 // 71 void MCLineEntry::Make(MCStreamer *MCOS, const MCSection *Section) { 72 if (!MCOS->getContext().getDwarfLocSeen()) 73 return; 74 75 // Create a symbol at in the current section for use in the line entry. 76 MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol(); 77 // Set the value of the symbol to use for the MCLineEntry. 78 MCOS->EmitLabel(LineSym); 79 80 // Get the current .loc info saved in the context. 81 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc(); 82 83 // Create a (local) line entry with the symbol and the current .loc info. 84 MCLineEntry LineEntry(LineSym, DwarfLoc); 85 86 // clear DwarfLocSeen saying the current .loc info is now used. 87 MCOS->getContext().ClearDwarfLocSeen(); 88 89 // Get the MCLineSection for this section, if one does not exist for this 90 // section create it. 91 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections = 92 MCOS->getContext().getMCLineSections(); 93 MCLineSection *LineSection = MCLineSections.lookup(Section); 94 if (!LineSection) { 95 // Create a new MCLineSection. This will be deleted after the dwarf line 96 // table is created using it by iterating through the MCLineSections 97 // DenseMap. 98 LineSection = new MCLineSection; 99 // Save a pointer to the new LineSection into the MCLineSections DenseMap. 100 MCOS->getContext().addMCLineSection(Section, LineSection); 101 } 102 103 // Add the line entry to this section's entries. 104 LineSection->addLineEntry(LineEntry); 105 } 106 107 // 108 // This helper routine returns an expression of End - Start + IntVal . 109 // 110 static inline const MCExpr *MakeStartMinusEndExpr(const MCStreamer &MCOS, 111 const MCSymbol &Start, 112 const MCSymbol &End, 113 int IntVal) { 114 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 115 const MCExpr *Res = 116 MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext()); 117 const MCExpr *RHS = 118 MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext()); 119 const MCExpr *Res1 = 120 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext()); 121 const MCExpr *Res2 = 122 MCConstantExpr::Create(IntVal, MCOS.getContext()); 123 const MCExpr *Res3 = 124 MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext()); 125 return Res3; 126 } 127 128 // 129 // This emits the Dwarf line table for the specified section from the entries 130 // in the LineSection. 131 // 132 static inline void EmitDwarfLineTable(MCStreamer *MCOS, 133 const MCSection *Section, 134 const MCLineSection *LineSection) { 135 unsigned FileNum = 1; 136 unsigned LastLine = 1; 137 unsigned Column = 0; 138 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 139 unsigned Isa = 0; 140 MCSymbol *LastLabel = NULL; 141 142 // Loop through each MCLineEntry and encode the dwarf line number table. 143 for (MCLineSection::const_iterator 144 it = LineSection->getMCLineEntries()->begin(), 145 ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) { 146 147 if (FileNum != it->getFileNum()) { 148 FileNum = it->getFileNum(); 149 MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1); 150 MCOS->EmitULEB128IntValue(FileNum); 151 } 152 if (Column != it->getColumn()) { 153 Column = it->getColumn(); 154 MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1); 155 MCOS->EmitULEB128IntValue(Column); 156 } 157 if (Isa != it->getIsa()) { 158 Isa = it->getIsa(); 159 MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1); 160 MCOS->EmitULEB128IntValue(Isa); 161 } 162 if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { 163 Flags = it->getFlags(); 164 MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1); 165 } 166 if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK) 167 MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1); 168 if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END) 169 MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1); 170 if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) 171 MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1); 172 173 int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine; 174 MCSymbol *Label = it->getLabel(); 175 176 // At this point we want to emit/create the sequence to encode the delta in 177 // line numbers and the increment of the address from the previous Label 178 // and the current Label. 179 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo(); 180 MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, 181 asmInfo.getPointerSize()); 182 183 LastLine = it->getLine(); 184 LastLabel = Label; 185 } 186 187 // Emit a DW_LNE_end_sequence for the end of the section. 188 // Using the pointer Section create a temporary label at the end of the 189 // section and use that and the LastLabel to compute the address delta 190 // and use INT64_MAX as the line delta which is the signal that this is 191 // actually a DW_LNE_end_sequence. 192 193 // Switch to the section to be able to create a symbol at its end. 194 MCOS->SwitchSection(Section); 195 196 MCContext &context = MCOS->getContext(); 197 // Create a symbol at the end of the section. 198 MCSymbol *SectionEnd = context.CreateTempSymbol(); 199 // Set the value of the symbol, as we are at the end of the section. 200 MCOS->EmitLabel(SectionEnd); 201 202 // Switch back the dwarf line section. 203 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); 204 205 const MCAsmInfo &asmInfo = MCOS->getContext().getAsmInfo(); 206 MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd, 207 asmInfo.getPointerSize()); 208 } 209 210 // 211 // This emits the Dwarf file and the line tables. 212 // 213 const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) { 214 MCContext &context = MCOS->getContext(); 215 // Switch to the section where the table will be emitted into. 216 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection()); 217 218 // Create a symbol at the beginning of this section. 219 MCSymbol *LineStartSym = context.CreateTempSymbol(); 220 // Set the value of the symbol, as we are at the start of the section. 221 MCOS->EmitLabel(LineStartSym); 222 223 // Create a symbol for the end of the section (to be set when we get there). 224 MCSymbol *LineEndSym = context.CreateTempSymbol(); 225 226 // The first 4 bytes is the total length of the information for this 227 // compilation unit (not including these 4 bytes for the length). 228 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4), 229 4); 230 231 // Next 2 bytes is the Version, which is Dwarf 2. 232 MCOS->EmitIntValue(2, 2); 233 234 // Create a symbol for the end of the prologue (to be set when we get there). 235 MCSymbol *ProEndSym = context.CreateTempSymbol(); // Lprologue_end 236 237 // Length of the prologue, is the next 4 bytes. Which is the start of the 238 // section to the end of the prologue. Not including the 4 bytes for the 239 // total length, the 2 bytes for the version, and these 4 bytes for the 240 // length of the prologue. 241 MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym, 242 (4 + 2 + 4)), 243 4, 0); 244 245 // Parameters of the state machine, are next. 246 MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1); 247 MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1); 248 MCOS->EmitIntValue(DWARF2_LINE_BASE, 1); 249 MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1); 250 MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1); 251 252 // Standard opcode lengths 253 MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy 254 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc 255 MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line 256 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file 257 MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column 258 MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt 259 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block 260 MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc 261 MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc 262 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end 263 MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin 264 MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa 265 266 // Put out the directory and file tables. 267 268 // First the directory table. 269 const std::vector<StringRef> &MCDwarfDirs = 270 context.getMCDwarfDirs(); 271 for (unsigned i = 0; i < MCDwarfDirs.size(); i++) { 272 MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName 273 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string 274 } 275 MCOS->EmitIntValue(0, 1); // Terminate the directory list 276 277 // Second the file table. 278 const std::vector<MCDwarfFile *> &MCDwarfFiles = 279 MCOS->getContext().getMCDwarfFiles(); 280 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) { 281 MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName 282 MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string 283 // the Directory num 284 MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex()); 285 MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0) 286 MCOS->EmitIntValue(0, 1); // filesize (always 0) 287 } 288 MCOS->EmitIntValue(0, 1); // Terminate the file list 289 290 // This is the end of the prologue, so set the value of the symbol at the 291 // end of the prologue (that was used in a previous expression). 292 MCOS->EmitLabel(ProEndSym); 293 294 // Put out the line tables. 295 const DenseMap<const MCSection *, MCLineSection *> &MCLineSections = 296 MCOS->getContext().getMCLineSections(); 297 const std::vector<const MCSection *> &MCLineSectionOrder = 298 MCOS->getContext().getMCLineSectionOrder(); 299 for (std::vector<const MCSection*>::const_iterator it = 300 MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie; 301 ++it) { 302 const MCSection *Sec = *it; 303 const MCLineSection *Line = MCLineSections.lookup(Sec); 304 EmitDwarfLineTable(MCOS, Sec, Line); 305 306 // Now delete the MCLineSections that were created in MCLineEntry::Make() 307 // and used to emit the line table. 308 delete Line; 309 } 310 311 if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines() 312 && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) { 313 // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures 314 // it requires: 315 // total_length >= prologue_length + 10 316 // We are 4 bytes short, since we have total_length = 51 and 317 // prologue_length = 45 318 319 // The regular end_sequence should be sufficient. 320 MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0); 321 } 322 323 // This is the end of the section, so set the value of the symbol at the end 324 // of this section (that was used in a previous expression). 325 MCOS->EmitLabel(LineEndSym); 326 327 return LineStartSym; 328 } 329 330 /// Utility function to write the encoding to an object writer. 331 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta, 332 uint64_t AddrDelta) { 333 SmallString<256> Tmp; 334 raw_svector_ostream OS(Tmp); 335 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS); 336 OW->WriteBytes(OS.str()); 337 } 338 339 /// Utility function to emit the encoding to a streamer. 340 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta, 341 uint64_t AddrDelta) { 342 SmallString<256> Tmp; 343 raw_svector_ostream OS(Tmp); 344 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS); 345 MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0); 346 } 347 348 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas. 349 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta, 350 raw_ostream &OS) { 351 uint64_t Temp, Opcode; 352 bool NeedCopy = false; 353 354 // Scale the address delta by the minimum instruction length. 355 AddrDelta = ScaleAddrDelta(AddrDelta); 356 357 // A LineDelta of INT64_MAX is a signal that this is actually a 358 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 359 // end_sequence to emit the matrix entry. 360 if (LineDelta == INT64_MAX) { 361 if (AddrDelta == MAX_SPECIAL_ADDR_DELTA) 362 OS << char(dwarf::DW_LNS_const_add_pc); 363 else { 364 OS << char(dwarf::DW_LNS_advance_pc); 365 encodeULEB128(AddrDelta, OS); 366 } 367 OS << char(dwarf::DW_LNS_extended_op); 368 OS << char(1); 369 OS << char(dwarf::DW_LNE_end_sequence); 370 return; 371 } 372 373 // Bias the line delta by the base. 374 Temp = LineDelta - DWARF2_LINE_BASE; 375 376 // If the line increment is out of range of a special opcode, we must encode 377 // it with DW_LNS_advance_line. 378 if (Temp >= DWARF2_LINE_RANGE) { 379 OS << char(dwarf::DW_LNS_advance_line); 380 encodeSLEB128(LineDelta, OS); 381 382 LineDelta = 0; 383 Temp = 0 - DWARF2_LINE_BASE; 384 NeedCopy = true; 385 } 386 387 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode. 388 if (LineDelta == 0 && AddrDelta == 0) { 389 OS << char(dwarf::DW_LNS_copy); 390 return; 391 } 392 393 // Bias the opcode by the special opcode base. 394 Temp += DWARF2_LINE_OPCODE_BASE; 395 396 // Avoid overflow when addr_delta is large. 397 if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) { 398 // Try using a special opcode. 399 Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE; 400 if (Opcode <= 255) { 401 OS << char(Opcode); 402 return; 403 } 404 405 // Try using DW_LNS_const_add_pc followed by special op. 406 Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE; 407 if (Opcode <= 255) { 408 OS << char(dwarf::DW_LNS_const_add_pc); 409 OS << char(Opcode); 410 return; 411 } 412 } 413 414 // Otherwise use DW_LNS_advance_pc. 415 OS << char(dwarf::DW_LNS_advance_pc); 416 encodeULEB128(AddrDelta, OS); 417 418 if (NeedCopy) 419 OS << char(dwarf::DW_LNS_copy); 420 else 421 OS << char(Temp); 422 } 423 424 void MCDwarfFile::print(raw_ostream &OS) const { 425 OS << '"' << getName() << '"'; 426 } 427 428 void MCDwarfFile::dump() const { 429 print(dbgs()); 430 } 431 432 // Utility function to write a tuple for .debug_abbrev. 433 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) { 434 MCOS->EmitULEB128IntValue(Name); 435 MCOS->EmitULEB128IntValue(Form); 436 } 437 438 // When generating dwarf for assembly source files this emits 439 // the data for .debug_abbrev section which contains three DIEs. 440 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) { 441 MCContext &context = MCOS->getContext(); 442 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 443 444 // DW_TAG_compile_unit DIE abbrev (1). 445 MCOS->EmitULEB128IntValue(1); 446 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit); 447 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); 448 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4); 449 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 450 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr); 451 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 452 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string); 453 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 454 if (!DwarfDebugFlags.empty()) 455 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string); 456 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string); 457 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2); 458 EmitAbbrev(MCOS, 0, 0); 459 460 // DW_TAG_label DIE abbrev (2). 461 MCOS->EmitULEB128IntValue(2); 462 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label); 463 MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1); 464 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 465 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4); 466 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4); 467 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 468 EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag); 469 EmitAbbrev(MCOS, 0, 0); 470 471 // DW_TAG_unspecified_parameters DIE abbrev (3). 472 MCOS->EmitULEB128IntValue(3); 473 MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters); 474 MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1); 475 EmitAbbrev(MCOS, 0, 0); 476 477 // Terminate the abbreviations for this compilation unit. 478 MCOS->EmitIntValue(0, 1); 479 } 480 481 // When generating dwarf for assembly source files this emits the data for 482 // .debug_aranges section. Which contains a header and a table of pairs of 483 // PointerSize'ed values for the address and size of section(s) with line table 484 // entries (just the default .text in our case) and a terminating pair of zeros. 485 static void EmitGenDwarfAranges(MCStreamer *MCOS) { 486 MCContext &context = MCOS->getContext(); 487 488 // Create a symbol at the end of the section that we are creating the dwarf 489 // debugging info to use later in here as part of the expression to calculate 490 // the size of the section for the table. 491 MCOS->SwitchSection(context.getGenDwarfSection()); 492 MCSymbol *SectionEndSym = context.CreateTempSymbol(); 493 MCOS->EmitLabel(SectionEndSym); 494 context.setGenDwarfSectionEndSym(SectionEndSym); 495 496 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 497 498 // This will be the length of the .debug_aranges section, first account for 499 // the size of each item in the header (see below where we emit these items). 500 int Length = 4 + 2 + 4 + 1 + 1; 501 502 // Figure the padding after the header before the table of address and size 503 // pairs who's values are PointerSize'ed. 504 const MCAsmInfo &asmInfo = context.getAsmInfo(); 505 int AddrSize = asmInfo.getPointerSize(); 506 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); 507 if (Pad == 2 * AddrSize) 508 Pad = 0; 509 Length += Pad; 510 511 // Add the size of the pair of PointerSize'ed values for the address and size 512 // of the one default .text section we have in the table. 513 Length += 2 * AddrSize; 514 // And the pair of terminating zeros. 515 Length += 2 * AddrSize; 516 517 518 // Emit the header for this section. 519 // The 4 byte length not including the 4 byte value for the length. 520 MCOS->EmitIntValue(Length - 4, 4); 521 // The 2 byte version, which is 2. 522 MCOS->EmitIntValue(2, 2); 523 // The 4 byte offset to the compile unit in the .debug_info from the start 524 // of the .debug_info, it is at the start of that section so this is zero. 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); 533 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); 542 543 // And finally the pair of terminating zeros. 544 MCOS->EmitIntValue(0, AddrSize); 545 MCOS->EmitIntValue(0, AddrSize); 546 } 547 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(); 555 556 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 557 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(); 563 564 // First part: the header. 565 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); 570 571 // The 2 byte DWARF version, which is 2. 572 MCOS->EmitIntValue(2, 2); 573 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); 578 } else { 579 MCOS->EmitIntValue(0, 4); 580 } 581 582 const MCAsmInfo &asmInfo = context.getAsmInfo(); 583 int AddrSize = asmInfo.getPointerSize(); 584 // The 1 byte size of an address. 585 MCOS->EmitIntValue(AddrSize, 1); 586 587 // Second part: the compile_unit DIE. 588 589 // The DW_TAG_compile_unit DIE abbrev (1). 590 MCOS->EmitULEB128IntValue(1); 591 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); 596 } else { 597 MCOS->EmitIntValue(0, 4); 598 } 599 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); 604 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); 609 610 // AT_name, the name of the source file. Reconstruct from the first directory 611 // and file table entries. 612 const std::vector<StringRef> &MCDwarfDirs = 613 context.getMCDwarfDirs(); 614 if (MCDwarfDirs.size() > 0) { 615 MCOS->EmitBytes(MCDwarfDirs[0], 0); 616 MCOS->EmitBytes("/", 0); 617 } 618 const std::vector<MCDwarfFile *> &MCDwarfFiles = 619 MCOS->getContext().getMCDwarfFiles(); 620 MCOS->EmitBytes(MCDwarfFiles[1]->getName(), 0); 621 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 622 623 // AT_comp_dir, the working directory the assembly was done in. 624 llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory(); 625 MCOS->EmitBytes(StringRef(CWD.c_str()), 0); 626 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 627 628 // AT_APPLE_flags, the command line arguments of the assembler tool. 629 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 630 if (!DwarfDebugFlags.empty()){ 631 MCOS->EmitBytes(DwarfDebugFlags, 0); 632 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 633 } 634 635 // AT_producer, the version of the assembler tool. 636 MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "), 0); 637 MCOS->EmitBytes(StringRef(PACKAGE_VERSION), 0); 638 MCOS->EmitBytes(StringRef(")"), 0); 639 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 640 641 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2 642 // draft has no standard code for assembler. 643 MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2); 644 645 // Third part: the list of label DIEs. 646 647 // Loop on saved info for dwarf labels and create the DIEs for them. 648 const std::vector<const MCGenDwarfLabelEntry *> &Entries = 649 MCOS->getContext().getMCGenDwarfLabelEntries(); 650 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it = 651 Entries.begin(), ie = Entries.end(); it != ie; 652 ++it) { 653 const MCGenDwarfLabelEntry *Entry = *it; 654 655 // The DW_TAG_label DIE abbrev (2). 656 MCOS->EmitULEB128IntValue(2); 657 658 // AT_name, of the label without any leading underbar. 659 MCOS->EmitBytes(Entry->getName(), 0); 660 MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string. 661 662 // AT_decl_file, index into the file table. 663 MCOS->EmitIntValue(Entry->getFileNumber(), 4); 664 665 // AT_decl_line, source line number. 666 MCOS->EmitIntValue(Entry->getLineNumber(), 4); 667 668 // AT_low_pc, start address of the label. 669 const MCExpr *AT_low_pc = MCSymbolRefExpr::Create(Entry->getLabel(), 670 MCSymbolRefExpr::VK_None, context); 671 MCOS->EmitAbsValue(AT_low_pc, AddrSize); 672 673 // DW_AT_prototyped, a one byte flag value of 0 saying we have no prototype. 674 MCOS->EmitIntValue(0, 1); 675 676 // The DW_TAG_unspecified_parameters DIE abbrev (3). 677 MCOS->EmitULEB128IntValue(3); 678 679 // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE's. 680 MCOS->EmitIntValue(0, 1); 681 } 682 // Deallocate the MCGenDwarfLabelEntry classes that saved away the info 683 // for the dwarf labels. 684 for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it = 685 Entries.begin(), ie = Entries.end(); it != ie; 686 ++it) { 687 const MCGenDwarfLabelEntry *Entry = *it; 688 delete Entry; 689 } 690 691 // Add the NULL DIE terminating the Compile Unit DIE's. 692 MCOS->EmitIntValue(0, 1); 693 694 // Now set the value of the symbol at the end of the info section. 695 MCOS->EmitLabel(InfoEnd); 696 } 697 698 // 699 // When generating dwarf for assembly source files this emits the Dwarf 700 // sections. 701 // 702 void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol) { 703 // Create the dwarf sections in this order (.debug_line already created). 704 MCContext &context = MCOS->getContext(); 705 const MCAsmInfo &AsmInfo = context.getAsmInfo(); 706 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 707 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 708 MCSymbol *AbbrevSectionSymbol; 709 if (AsmInfo.doesDwarfUseRelocationsAcrossSections()) { 710 AbbrevSectionSymbol = context.CreateTempSymbol(); 711 MCOS->EmitLabel(AbbrevSectionSymbol); 712 } else { 713 AbbrevSectionSymbol = NULL; 714 LineSectionSymbol = NULL; 715 } 716 MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 717 718 // If there are no line table entries then do not emit any section contents. 719 if (context.getMCLineSections().empty()) 720 return; 721 722 // Output the data for .debug_aranges section. 723 EmitGenDwarfAranges(MCOS); 724 725 // Output the data for .debug_abbrev section. 726 EmitGenDwarfAbbrev(MCOS); 727 728 // Output the data for .debug_info section. 729 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol); 730 } 731 732 // 733 // When generating dwarf for assembly source files this is called when symbol 734 // for a label is created. If this symbol is not a temporary and is in the 735 // section that dwarf is being generated for, save the needed info to create 736 // a dwarf label. 737 // 738 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS, 739 SourceMgr &SrcMgr, SMLoc &Loc) { 740 // We won't create dwarf labels for temporary symbols or symbols not in 741 // the default text. 742 if (Symbol->isTemporary()) 743 return; 744 MCContext &context = MCOS->getContext(); 745 if (context.getGenDwarfSection() != MCOS->getCurrentSection()) 746 return; 747 748 // The dwarf label's name does not have the symbol name's leading 749 // underbar if any. 750 StringRef Name = Symbol->getName(); 751 if (Name.startswith("_")) 752 Name = Name.substr(1, Name.size()-1); 753 754 // Get the dwarf file number to be used for the dwarf label. 755 unsigned FileNumber = context.getGenDwarfFileNumber(); 756 757 // Finding the line number is the expensive part which is why we just don't 758 // pass it in as for some symbols we won't create a dwarf label. 759 int CurBuffer = SrcMgr.FindBufferContainingLoc(Loc); 760 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer); 761 762 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc 763 // values so that they don't have things like an ARM thumb bit from the 764 // original symbol. So when used they won't get a low bit set after 765 // relocation. 766 MCSymbol *Label = context.CreateTempSymbol(); 767 MCOS->EmitLabel(Label); 768 769 // Create and entry for the info and add it to the other entries. 770 MCGenDwarfLabelEntry *Entry = 771 new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label); 772 MCOS->getContext().addMCGenDwarfLabelEntry(Entry); 773 } 774 775 static int getDataAlignmentFactor(MCStreamer &streamer) { 776 MCContext &context = streamer.getContext(); 777 const MCAsmInfo &asmInfo = context.getAsmInfo(); 778 int size = asmInfo.getPointerSize(); 779 if (asmInfo.isStackGrowthDirectionUp()) 780 return size; 781 else 782 return -size; 783 } 784 785 static unsigned getSizeForEncoding(MCStreamer &streamer, 786 unsigned symbolEncoding) { 787 MCContext &context = streamer.getContext(); 788 unsigned format = symbolEncoding & 0x0f; 789 switch (format) { 790 default: llvm_unreachable("Unknown Encoding"); 791 case dwarf::DW_EH_PE_absptr: 792 case dwarf::DW_EH_PE_signed: 793 return context.getAsmInfo().getPointerSize(); 794 case dwarf::DW_EH_PE_udata2: 795 case dwarf::DW_EH_PE_sdata2: 796 return 2; 797 case dwarf::DW_EH_PE_udata4: 798 case dwarf::DW_EH_PE_sdata4: 799 return 4; 800 case dwarf::DW_EH_PE_udata8: 801 case dwarf::DW_EH_PE_sdata8: 802 return 8; 803 } 804 } 805 806 static void EmitSymbol(MCStreamer &streamer, const MCSymbol &symbol, 807 unsigned symbolEncoding, const char *comment = 0) { 808 MCContext &context = streamer.getContext(); 809 const MCAsmInfo &asmInfo = context.getAsmInfo(); 810 const MCExpr *v = asmInfo.getExprForFDESymbol(&symbol, 811 symbolEncoding, 812 streamer); 813 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 814 if (streamer.isVerboseAsm() && comment) streamer.AddComment(comment); 815 streamer.EmitAbsValue(v, size); 816 } 817 818 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol, 819 unsigned symbolEncoding) { 820 MCContext &context = streamer.getContext(); 821 const MCAsmInfo &asmInfo = context.getAsmInfo(); 822 const MCExpr *v = asmInfo.getExprForPersonalitySymbol(&symbol, 823 symbolEncoding, 824 streamer); 825 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 826 streamer.EmitValue(v, size); 827 } 828 829 static const MachineLocation TranslateMachineLocation( 830 const MCRegisterInfo &MRI, 831 const MachineLocation &Loc) { 832 unsigned Reg = Loc.getReg() == MachineLocation::VirtualFP ? 833 MachineLocation::VirtualFP : 834 unsigned(MRI.getDwarfRegNum(Loc.getReg(), true)); 835 const MachineLocation &NewLoc = Loc.isReg() ? 836 MachineLocation(Reg) : MachineLocation(Reg, Loc.getOffset()); 837 return NewLoc; 838 } 839 840 namespace { 841 class FrameEmitterImpl { 842 int CFAOffset; 843 int CIENum; 844 bool UsingCFI; 845 bool IsEH; 846 const MCSymbol *SectionStart; 847 public: 848 FrameEmitterImpl(bool usingCFI, bool isEH) 849 : CFAOffset(0), CIENum(0), UsingCFI(usingCFI), IsEH(isEH), 850 SectionStart(0) {} 851 852 void setSectionStart(const MCSymbol *Label) { SectionStart = Label; } 853 854 /// EmitCompactUnwind - Emit the unwind information in a compact way. If 855 /// we're successful, return 'true'. Otherwise, return 'false' and it will 856 /// emit the normal CIE and FDE. 857 bool EmitCompactUnwind(MCStreamer &streamer, 858 const MCDwarfFrameInfo &frame); 859 860 const MCSymbol &EmitCIE(MCStreamer &streamer, 861 const MCSymbol *personality, 862 unsigned personalityEncoding, 863 const MCSymbol *lsda, 864 bool IsSignalFrame, 865 unsigned lsdaEncoding); 866 MCSymbol *EmitFDE(MCStreamer &streamer, 867 const MCSymbol &cieStart, 868 const MCDwarfFrameInfo &frame); 869 void EmitCFIInstructions(MCStreamer &streamer, 870 const std::vector<MCCFIInstruction> &Instrs, 871 MCSymbol *BaseLabel); 872 void EmitCFIInstruction(MCStreamer &Streamer, 873 const MCCFIInstruction &Instr); 874 }; 875 876 } // end anonymous namespace 877 878 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding, 879 StringRef Prefix) { 880 if (Streamer.isVerboseAsm()) { 881 const char *EncStr; 882 switch (Encoding) { 883 default: EncStr = "<unknown encoding>"; break; 884 case dwarf::DW_EH_PE_absptr: EncStr = "absptr"; break; 885 case dwarf::DW_EH_PE_omit: EncStr = "omit"; break; 886 case dwarf::DW_EH_PE_pcrel: EncStr = "pcrel"; break; 887 case dwarf::DW_EH_PE_udata4: EncStr = "udata4"; break; 888 case dwarf::DW_EH_PE_udata8: EncStr = "udata8"; break; 889 case dwarf::DW_EH_PE_sdata4: EncStr = "sdata4"; break; 890 case dwarf::DW_EH_PE_sdata8: EncStr = "sdata8"; break; 891 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: 892 EncStr = "pcrel udata4"; 893 break; 894 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: 895 EncStr = "pcrel sdata4"; 896 break; 897 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: 898 EncStr = "pcrel udata8"; 899 break; 900 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: 901 EncStr = "screl sdata8"; 902 break; 903 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata4: 904 EncStr = "indirect pcrel udata4"; 905 break; 906 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata4: 907 EncStr = "indirect pcrel sdata4"; 908 break; 909 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_udata8: 910 EncStr = "indirect pcrel udata8"; 911 break; 912 case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_sdata8: 913 EncStr = "indirect pcrel sdata8"; 914 break; 915 } 916 917 Streamer.AddComment(Twine(Prefix) + " = " + EncStr); 918 } 919 920 Streamer.EmitIntValue(Encoding, 1); 921 } 922 923 void FrameEmitterImpl::EmitCFIInstruction(MCStreamer &Streamer, 924 const MCCFIInstruction &Instr) { 925 int dataAlignmentFactor = getDataAlignmentFactor(Streamer); 926 bool VerboseAsm = Streamer.isVerboseAsm(); 927 928 switch (Instr.getOperation()) { 929 case MCCFIInstruction::Move: 930 case MCCFIInstruction::RelMove: { 931 const MachineLocation &Dst = Instr.getDestination(); 932 const MachineLocation &Src = Instr.getSource(); 933 const bool IsRelative = Instr.getOperation() == MCCFIInstruction::RelMove; 934 935 // If advancing cfa. 936 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { 937 if (Src.getReg() == MachineLocation::VirtualFP) { 938 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_offset"); 939 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_offset, 1); 940 } else { 941 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa"); 942 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa, 1); 943 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + 944 Twine(Src.getReg())); 945 Streamer.EmitULEB128IntValue(Src.getReg()); 946 } 947 948 if (IsRelative) 949 CFAOffset += Src.getOffset(); 950 else 951 CFAOffset = -Src.getOffset(); 952 953 if (VerboseAsm) Streamer.AddComment(Twine("Offset " + Twine(CFAOffset))); 954 Streamer.EmitULEB128IntValue(CFAOffset); 955 return; 956 } 957 958 if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { 959 assert(Dst.isReg() && "Machine move not supported yet."); 960 if (VerboseAsm) Streamer.AddComment("DW_CFA_def_cfa_register"); 961 Streamer.EmitIntValue(dwarf::DW_CFA_def_cfa_register, 1); 962 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Dst.getReg())); 963 Streamer.EmitULEB128IntValue(Dst.getReg()); 964 return; 965 } 966 967 unsigned Reg = Src.getReg(); 968 int Offset = Dst.getOffset(); 969 if (IsRelative) 970 Offset -= CFAOffset; 971 Offset = Offset / dataAlignmentFactor; 972 973 if (Offset < 0) { 974 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended_sf"); 975 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended_sf, 1); 976 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 977 Streamer.EmitULEB128IntValue(Reg); 978 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); 979 Streamer.EmitSLEB128IntValue(Offset); 980 } else if (Reg < 64) { 981 if (VerboseAsm) Streamer.AddComment(Twine("DW_CFA_offset + Reg(") + 982 Twine(Reg) + ")"); 983 Streamer.EmitIntValue(dwarf::DW_CFA_offset + Reg, 1); 984 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); 985 Streamer.EmitULEB128IntValue(Offset); 986 } else { 987 if (VerboseAsm) Streamer.AddComment("DW_CFA_offset_extended"); 988 Streamer.EmitIntValue(dwarf::DW_CFA_offset_extended, 1); 989 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 990 Streamer.EmitULEB128IntValue(Reg); 991 if (VerboseAsm) Streamer.AddComment(Twine("Offset ") + Twine(Offset)); 992 Streamer.EmitULEB128IntValue(Offset); 993 } 994 return; 995 } 996 case MCCFIInstruction::RememberState: 997 if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state"); 998 Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1); 999 return; 1000 case MCCFIInstruction::RestoreState: 1001 if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state"); 1002 Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1); 1003 return; 1004 case MCCFIInstruction::SameValue: { 1005 unsigned Reg = Instr.getDestination().getReg(); 1006 if (VerboseAsm) Streamer.AddComment("DW_CFA_same_value"); 1007 Streamer.EmitIntValue(dwarf::DW_CFA_same_value, 1); 1008 if (VerboseAsm) Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 1009 Streamer.EmitULEB128IntValue(Reg); 1010 return; 1011 } 1012 case MCCFIInstruction::Restore: { 1013 unsigned Reg = Instr.getDestination().getReg(); 1014 if (VerboseAsm) { 1015 Streamer.AddComment("DW_CFA_restore"); 1016 Streamer.AddComment(Twine("Reg ") + Twine(Reg)); 1017 } 1018 Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1); 1019 return; 1020 } 1021 case MCCFIInstruction::Escape: 1022 if (VerboseAsm) Streamer.AddComment("Escape bytes"); 1023 Streamer.EmitBytes(Instr.getValues(), 0); 1024 return; 1025 } 1026 llvm_unreachable("Unhandled case in switch"); 1027 } 1028 1029 /// EmitFrameMoves - Emit frame instructions to describe the layout of the 1030 /// frame. 1031 void FrameEmitterImpl::EmitCFIInstructions(MCStreamer &streamer, 1032 const std::vector<MCCFIInstruction> &Instrs, 1033 MCSymbol *BaseLabel) { 1034 for (unsigned i = 0, N = Instrs.size(); i < N; ++i) { 1035 const MCCFIInstruction &Instr = Instrs[i]; 1036 MCSymbol *Label = Instr.getLabel(); 1037 // Throw out move if the label is invalid. 1038 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. 1039 1040 // Advance row if new location. 1041 if (BaseLabel && Label) { 1042 MCSymbol *ThisSym = Label; 1043 if (ThisSym != BaseLabel) { 1044 if (streamer.isVerboseAsm()) streamer.AddComment("DW_CFA_advance_loc4"); 1045 streamer.EmitDwarfAdvanceFrameAddr(BaseLabel, ThisSym); 1046 BaseLabel = ThisSym; 1047 } 1048 } 1049 1050 EmitCFIInstruction(streamer, Instr); 1051 } 1052 } 1053 1054 /// EmitCompactUnwind - Emit the unwind information in a compact way. If we're 1055 /// successful, return 'true'. Otherwise, return 'false' and it will emit the 1056 /// normal CIE and FDE. 1057 bool FrameEmitterImpl::EmitCompactUnwind(MCStreamer &Streamer, 1058 const MCDwarfFrameInfo &Frame) { 1059 MCContext &Context = Streamer.getContext(); 1060 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1061 bool VerboseAsm = Streamer.isVerboseAsm(); 1062 1063 // range-start range-length compact-unwind-enc personality-func lsda 1064 // _foo LfooEnd-_foo 0x00000023 0 0 1065 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1 1066 // 1067 // .section __LD,__compact_unwind,regular,debug 1068 // 1069 // # compact unwind for _foo 1070 // .quad _foo 1071 // .set L1,LfooEnd-_foo 1072 // .long L1 1073 // .long 0x01010001 1074 // .quad 0 1075 // .quad 0 1076 // 1077 // # compact unwind for _bar 1078 // .quad _bar 1079 // .set L2,LbarEnd-_bar 1080 // .long L2 1081 // .long 0x01020011 1082 // .quad __gxx_personality 1083 // .quad except_tab1 1084 1085 uint32_t Encoding = Frame.CompactUnwindEncoding; 1086 if (!Encoding) return false; 1087 1088 // The encoding needs to know we have an LSDA. 1089 if (Frame.Lsda) 1090 Encoding |= 0x40000000; 1091 1092 Streamer.SwitchSection(MOFI->getCompactUnwindSection()); 1093 1094 // Range Start 1095 unsigned FDEEncoding = MOFI->getFDEEncoding(UsingCFI); 1096 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding); 1097 if (VerboseAsm) Streamer.AddComment("Range Start"); 1098 Streamer.EmitSymbolValue(Frame.Function, Size); 1099 1100 // Range Length 1101 const MCExpr *Range = MakeStartMinusEndExpr(Streamer, *Frame.Begin, 1102 *Frame.End, 0); 1103 if (VerboseAsm) Streamer.AddComment("Range Length"); 1104 Streamer.EmitAbsValue(Range, 4); 1105 1106 // Compact Encoding 1107 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4); 1108 if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" + 1109 Twine::utohexstr(Encoding)); 1110 Streamer.EmitIntValue(Encoding, Size); 1111 1112 1113 // Personality Function 1114 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr); 1115 if (VerboseAsm) Streamer.AddComment("Personality Function"); 1116 if (Frame.Personality) 1117 Streamer.EmitSymbolValue(Frame.Personality, Size); 1118 else 1119 Streamer.EmitIntValue(0, Size); // No personality fn 1120 1121 // LSDA 1122 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding); 1123 if (VerboseAsm) Streamer.AddComment("LSDA"); 1124 if (Frame.Lsda) 1125 Streamer.EmitSymbolValue(Frame.Lsda, Size); 1126 else 1127 Streamer.EmitIntValue(0, Size); // No LSDA 1128 1129 return true; 1130 } 1131 1132 const MCSymbol &FrameEmitterImpl::EmitCIE(MCStreamer &streamer, 1133 const MCSymbol *personality, 1134 unsigned personalityEncoding, 1135 const MCSymbol *lsda, 1136 bool IsSignalFrame, 1137 unsigned lsdaEncoding) { 1138 MCContext &context = streamer.getContext(); 1139 const MCRegisterInfo &MRI = context.getRegisterInfo(); 1140 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1141 bool verboseAsm = streamer.isVerboseAsm(); 1142 1143 MCSymbol *sectionStart; 1144 if (MOFI->isFunctionEHFrameSymbolPrivate() || !IsEH) 1145 sectionStart = context.CreateTempSymbol(); 1146 else 1147 sectionStart = context.GetOrCreateSymbol(Twine("EH_frame") + Twine(CIENum)); 1148 1149 streamer.EmitLabel(sectionStart); 1150 CIENum++; 1151 1152 MCSymbol *sectionEnd = context.CreateTempSymbol(); 1153 1154 // Length 1155 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *sectionStart, 1156 *sectionEnd, 4); 1157 if (verboseAsm) streamer.AddComment("CIE Length"); 1158 streamer.EmitAbsValue(Length, 4); 1159 1160 // CIE ID 1161 unsigned CIE_ID = IsEH ? 0 : -1; 1162 if (verboseAsm) streamer.AddComment("CIE ID Tag"); 1163 streamer.EmitIntValue(CIE_ID, 4); 1164 1165 // Version 1166 if (verboseAsm) streamer.AddComment("DW_CIE_VERSION"); 1167 streamer.EmitIntValue(dwarf::DW_CIE_VERSION, 1); 1168 1169 // Augmentation String 1170 SmallString<8> Augmentation; 1171 if (IsEH) { 1172 if (verboseAsm) streamer.AddComment("CIE Augmentation"); 1173 Augmentation += "z"; 1174 if (personality) 1175 Augmentation += "P"; 1176 if (lsda) 1177 Augmentation += "L"; 1178 Augmentation += "R"; 1179 if (IsSignalFrame) 1180 Augmentation += "S"; 1181 streamer.EmitBytes(Augmentation.str(), 0); 1182 } 1183 streamer.EmitIntValue(0, 1); 1184 1185 // Code Alignment Factor 1186 if (verboseAsm) streamer.AddComment("CIE Code Alignment Factor"); 1187 streamer.EmitULEB128IntValue(1); 1188 1189 // Data Alignment Factor 1190 if (verboseAsm) streamer.AddComment("CIE Data Alignment Factor"); 1191 streamer.EmitSLEB128IntValue(getDataAlignmentFactor(streamer)); 1192 1193 // Return Address Register 1194 if (verboseAsm) streamer.AddComment("CIE Return Address Column"); 1195 streamer.EmitULEB128IntValue(MRI.getDwarfRegNum(MRI.getRARegister(), true)); 1196 1197 // Augmentation Data Length (optional) 1198 1199 unsigned augmentationLength = 0; 1200 if (IsEH) { 1201 if (personality) { 1202 // Personality Encoding 1203 augmentationLength += 1; 1204 // Personality 1205 augmentationLength += getSizeForEncoding(streamer, personalityEncoding); 1206 } 1207 if (lsda) 1208 augmentationLength += 1; 1209 // Encoding of the FDE pointers 1210 augmentationLength += 1; 1211 1212 if (verboseAsm) streamer.AddComment("Augmentation Size"); 1213 streamer.EmitULEB128IntValue(augmentationLength); 1214 1215 // Augmentation Data (optional) 1216 if (personality) { 1217 // Personality Encoding 1218 EmitEncodingByte(streamer, personalityEncoding, 1219 "Personality Encoding"); 1220 // Personality 1221 if (verboseAsm) streamer.AddComment("Personality"); 1222 EmitPersonality(streamer, *personality, personalityEncoding); 1223 } 1224 1225 if (lsda) 1226 EmitEncodingByte(streamer, lsdaEncoding, "LSDA Encoding"); 1227 1228 // Encoding of the FDE pointers 1229 EmitEncodingByte(streamer, MOFI->getFDEEncoding(UsingCFI), 1230 "FDE Encoding"); 1231 } 1232 1233 // Initial Instructions 1234 1235 const MCAsmInfo &MAI = context.getAsmInfo(); 1236 const std::vector<MachineMove> &Moves = MAI.getInitialFrameState(); 1237 std::vector<MCCFIInstruction> Instructions; 1238 1239 for (int i = 0, n = Moves.size(); i != n; ++i) { 1240 MCSymbol *Label = Moves[i].getLabel(); 1241 const MachineLocation &Dst = 1242 TranslateMachineLocation(MRI, Moves[i].getDestination()); 1243 const MachineLocation &Src = 1244 TranslateMachineLocation(MRI, Moves[i].getSource()); 1245 MCCFIInstruction Inst(Label, Dst, Src); 1246 Instructions.push_back(Inst); 1247 } 1248 1249 EmitCFIInstructions(streamer, Instructions, NULL); 1250 1251 // Padding 1252 streamer.EmitValueToAlignment(IsEH 1253 ? 4 : context.getAsmInfo().getPointerSize()); 1254 1255 streamer.EmitLabel(sectionEnd); 1256 return *sectionStart; 1257 } 1258 1259 MCSymbol *FrameEmitterImpl::EmitFDE(MCStreamer &streamer, 1260 const MCSymbol &cieStart, 1261 const MCDwarfFrameInfo &frame) { 1262 MCContext &context = streamer.getContext(); 1263 MCSymbol *fdeStart = context.CreateTempSymbol(); 1264 MCSymbol *fdeEnd = context.CreateTempSymbol(); 1265 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1266 bool verboseAsm = streamer.isVerboseAsm(); 1267 1268 if (IsEH && frame.Function && !MOFI->isFunctionEHFrameSymbolPrivate()) { 1269 MCSymbol *EHSym = 1270 context.GetOrCreateSymbol(frame.Function->getName() + Twine(".eh")); 1271 streamer.EmitEHSymAttributes(frame.Function, EHSym); 1272 streamer.EmitLabel(EHSym); 1273 } 1274 1275 // Length 1276 const MCExpr *Length = MakeStartMinusEndExpr(streamer, *fdeStart, *fdeEnd, 0); 1277 if (verboseAsm) streamer.AddComment("FDE Length"); 1278 streamer.EmitAbsValue(Length, 4); 1279 1280 streamer.EmitLabel(fdeStart); 1281 1282 // CIE Pointer 1283 const MCAsmInfo &asmInfo = context.getAsmInfo(); 1284 if (IsEH) { 1285 const MCExpr *offset = MakeStartMinusEndExpr(streamer, cieStart, *fdeStart, 1286 0); 1287 if (verboseAsm) streamer.AddComment("FDE CIE Offset"); 1288 streamer.EmitAbsValue(offset, 4); 1289 } else if (!asmInfo.doesDwarfUseRelocationsAcrossSections()) { 1290 const MCExpr *offset = MakeStartMinusEndExpr(streamer, *SectionStart, 1291 cieStart, 0); 1292 streamer.EmitAbsValue(offset, 4); 1293 } else { 1294 streamer.EmitSymbolValue(&cieStart, 4); 1295 } 1296 1297 // PC Begin 1298 unsigned PCEncoding = IsEH ? MOFI->getFDEEncoding(UsingCFI) 1299 : (unsigned)dwarf::DW_EH_PE_absptr; 1300 unsigned PCSize = getSizeForEncoding(streamer, PCEncoding); 1301 EmitSymbol(streamer, *frame.Begin, PCEncoding, "FDE initial location"); 1302 1303 // PC Range 1304 const MCExpr *Range = MakeStartMinusEndExpr(streamer, *frame.Begin, 1305 *frame.End, 0); 1306 if (verboseAsm) streamer.AddComment("FDE address range"); 1307 streamer.EmitAbsValue(Range, PCSize); 1308 1309 if (IsEH) { 1310 // Augmentation Data Length 1311 unsigned augmentationLength = 0; 1312 1313 if (frame.Lsda) 1314 augmentationLength += getSizeForEncoding(streamer, frame.LsdaEncoding); 1315 1316 if (verboseAsm) streamer.AddComment("Augmentation size"); 1317 streamer.EmitULEB128IntValue(augmentationLength); 1318 1319 // Augmentation Data 1320 if (frame.Lsda) 1321 EmitSymbol(streamer, *frame.Lsda, frame.LsdaEncoding, 1322 "Language Specific Data Area"); 1323 } 1324 1325 // Call Frame Instructions 1326 1327 EmitCFIInstructions(streamer, frame.Instructions, frame.Begin); 1328 1329 // Padding 1330 streamer.EmitValueToAlignment(PCSize); 1331 1332 return fdeEnd; 1333 } 1334 1335 namespace { 1336 struct CIEKey { 1337 static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false); } 1338 static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false); } 1339 1340 CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_, 1341 unsigned LsdaEncoding_, bool IsSignalFrame_) : 1342 Personality(Personality_), PersonalityEncoding(PersonalityEncoding_), 1343 LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_) { 1344 } 1345 const MCSymbol* Personality; 1346 unsigned PersonalityEncoding; 1347 unsigned LsdaEncoding; 1348 bool IsSignalFrame; 1349 }; 1350 } 1351 1352 namespace llvm { 1353 template <> 1354 struct DenseMapInfo<CIEKey> { 1355 static CIEKey getEmptyKey() { 1356 return CIEKey::getEmptyKey(); 1357 } 1358 static CIEKey getTombstoneKey() { 1359 return CIEKey::getTombstoneKey(); 1360 } 1361 static unsigned getHashValue(const CIEKey &Key) { 1362 return static_cast<unsigned>(hash_combine(Key.Personality, 1363 Key.PersonalityEncoding, 1364 Key.LsdaEncoding, 1365 Key.IsSignalFrame)); 1366 } 1367 static bool isEqual(const CIEKey &LHS, 1368 const CIEKey &RHS) { 1369 return LHS.Personality == RHS.Personality && 1370 LHS.PersonalityEncoding == RHS.PersonalityEncoding && 1371 LHS.LsdaEncoding == RHS.LsdaEncoding && 1372 LHS.IsSignalFrame == RHS.IsSignalFrame; 1373 } 1374 }; 1375 } 1376 1377 void MCDwarfFrameEmitter::Emit(MCStreamer &Streamer, 1378 bool UsingCFI, 1379 bool IsEH) { 1380 MCContext &Context = Streamer.getContext(); 1381 MCObjectFileInfo *MOFI = 1382 const_cast<MCObjectFileInfo*>(Context.getObjectFileInfo()); 1383 FrameEmitterImpl Emitter(UsingCFI, IsEH); 1384 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getFrameInfos(); 1385 1386 // Emit the compact unwind info if available. 1387 if (IsEH && MOFI->getCompactUnwindSection()) 1388 for (unsigned i = 0, n = Streamer.getNumFrameInfos(); i < n; ++i) { 1389 const MCDwarfFrameInfo &Frame = Streamer.getFrameInfo(i); 1390 if (Frame.CompactUnwindEncoding) 1391 Emitter.EmitCompactUnwind(Streamer, Frame); 1392 } 1393 1394 const MCSection &Section = IsEH ? *MOFI->getEHFrameSection() : 1395 *MOFI->getDwarfFrameSection(); 1396 Streamer.SwitchSection(&Section); 1397 MCSymbol *SectionStart = Context.CreateTempSymbol(); 1398 Streamer.EmitLabel(SectionStart); 1399 Emitter.setSectionStart(SectionStart); 1400 1401 MCSymbol *FDEEnd = NULL; 1402 DenseMap<CIEKey, const MCSymbol*> CIEStarts; 1403 1404 const MCSymbol *DummyDebugKey = NULL; 1405 for (unsigned i = 0, n = FrameArray.size(); i < n; ++i) { 1406 const MCDwarfFrameInfo &Frame = FrameArray[i]; 1407 CIEKey Key(Frame.Personality, Frame.PersonalityEncoding, 1408 Frame.LsdaEncoding, Frame.IsSignalFrame); 1409 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey; 1410 if (!CIEStart) 1411 CIEStart = &Emitter.EmitCIE(Streamer, Frame.Personality, 1412 Frame.PersonalityEncoding, Frame.Lsda, 1413 Frame.IsSignalFrame, 1414 Frame.LsdaEncoding); 1415 1416 FDEEnd = Emitter.EmitFDE(Streamer, *CIEStart, Frame); 1417 1418 if (i != n - 1) 1419 Streamer.EmitLabel(FDEEnd); 1420 } 1421 1422 Streamer.EmitValueToAlignment(Context.getAsmInfo().getPointerSize()); 1423 if (FDEEnd) 1424 Streamer.EmitLabel(FDEEnd); 1425 } 1426 1427 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCStreamer &Streamer, 1428 uint64_t AddrDelta) { 1429 SmallString<256> Tmp; 1430 raw_svector_ostream OS(Tmp); 1431 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OS); 1432 Streamer.EmitBytes(OS.str(), /*AddrSpace=*/0); 1433 } 1434 1435 void MCDwarfFrameEmitter::EncodeAdvanceLoc(uint64_t AddrDelta, 1436 raw_ostream &OS) { 1437 // FIXME: Assumes the code alignment factor is 1. 1438 if (AddrDelta == 0) { 1439 } else if (isUIntN(6, AddrDelta)) { 1440 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta; 1441 OS << Opcode; 1442 } else if (isUInt<8>(AddrDelta)) { 1443 OS << uint8_t(dwarf::DW_CFA_advance_loc1); 1444 OS << uint8_t(AddrDelta); 1445 } else if (isUInt<16>(AddrDelta)) { 1446 // FIXME: check what is the correct behavior on a big endian machine. 1447 OS << uint8_t(dwarf::DW_CFA_advance_loc2); 1448 OS << uint8_t( AddrDelta & 0xff); 1449 OS << uint8_t((AddrDelta >> 8) & 0xff); 1450 } else { 1451 // FIXME: check what is the correct behavior on a big endian machine. 1452 assert(isUInt<32>(AddrDelta)); 1453 OS << uint8_t(dwarf::DW_CFA_advance_loc4); 1454 OS << uint8_t( AddrDelta & 0xff); 1455 OS << uint8_t((AddrDelta >> 8) & 0xff); 1456 OS << uint8_t((AddrDelta >> 16) & 0xff); 1457 OS << uint8_t((AddrDelta >> 24) & 0xff); 1458 1459 } 1460 } 1461