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