1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/MC/MCDwarf.h" 10 #include "llvm/ADT/ArrayRef.h" 11 #include "llvm/ADT/DenseMap.h" 12 #include "llvm/ADT/Hashing.h" 13 #include "llvm/ADT/Optional.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/BinaryFormat/Dwarf.h" 20 #include "llvm/Config/config.h" 21 #include "llvm/MC/MCAsmInfo.h" 22 #include "llvm/MC/MCContext.h" 23 #include "llvm/MC/MCExpr.h" 24 #include "llvm/MC/MCObjectFileInfo.h" 25 #include "llvm/MC/MCObjectStreamer.h" 26 #include "llvm/MC/MCRegisterInfo.h" 27 #include "llvm/MC/MCSection.h" 28 #include "llvm/MC/MCStreamer.h" 29 #include "llvm/MC/MCSymbol.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/Endian.h" 32 #include "llvm/Support/EndianStream.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/LEB128.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/Path.h" 37 #include "llvm/Support/SourceMgr.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include <cassert> 40 #include <cstdint> 41 #include <string> 42 #include <utility> 43 #include <vector> 44 45 using namespace llvm; 46 47 MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) { 48 MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start"); 49 MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end"); 50 auto DwarfFormat = S.getContext().getDwarfFormat(); 51 if (DwarfFormat == dwarf::DWARF64) { 52 S.AddComment("DWARF64 mark"); 53 S.emitInt32(dwarf::DW_LENGTH_DWARF64); 54 } 55 S.AddComment("Length"); 56 S.emitAbsoluteSymbolDiff(End, Start, 57 dwarf::getDwarfOffsetByteSize(DwarfFormat)); 58 S.emitLabel(Start); 59 S.AddComment("Version"); 60 S.emitInt16(S.getContext().getDwarfVersion()); 61 S.AddComment("Address size"); 62 S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize()); 63 S.AddComment("Segment selector size"); 64 S.emitInt8(0); 65 return End; 66 } 67 68 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) { 69 unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment(); 70 if (MinInsnLength == 1) 71 return AddrDelta; 72 if (AddrDelta % MinInsnLength != 0) { 73 // TODO: report this error, but really only once. 74 ; 75 } 76 return AddrDelta / MinInsnLength; 77 } 78 79 MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) { 80 UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections(); 81 if (UseRelocs) 82 LineStrLabel = 83 Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol(); 84 } 85 86 // 87 // This is called when an instruction is assembled into the specified section 88 // and if there is information from the last .loc directive that has yet to have 89 // a line entry made for it is made. 90 // 91 void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) { 92 if (!MCOS->getContext().getDwarfLocSeen()) 93 return; 94 95 // Create a symbol at in the current section for use in the line entry. 96 MCSymbol *LineSym = MCOS->getContext().createTempSymbol(); 97 // Set the value of the symbol to use for the MCDwarfLineEntry. 98 MCOS->emitLabel(LineSym); 99 100 // Get the current .loc info saved in the context. 101 const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc(); 102 103 // Create a (local) line entry with the symbol and the current .loc info. 104 MCDwarfLineEntry LineEntry(LineSym, DwarfLoc); 105 106 // clear DwarfLocSeen saying the current .loc info is now used. 107 MCOS->getContext().clearDwarfLocSeen(); 108 109 // Add the line entry to this section's entries. 110 MCOS->getContext() 111 .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID()) 112 .getMCLineSections() 113 .addLineEntry(LineEntry, Section); 114 } 115 116 // 117 // This helper routine returns an expression of End - Start + IntVal . 118 // 119 static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx, 120 const MCSymbol &Start, 121 const MCSymbol &End, 122 int IntVal) { 123 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 124 const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx); 125 const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx); 126 const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx); 127 const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx); 128 const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx); 129 return Res3; 130 } 131 132 // 133 // This helper routine returns an expression of Start + IntVal . 134 // 135 static inline const MCExpr * 136 makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) { 137 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 138 const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx); 139 const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx); 140 const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx); 141 return Res; 142 } 143 144 void MCLineSection::addEndEntry(MCSymbol *EndLabel) { 145 auto *Sec = &EndLabel->getSection(); 146 // The line table may be empty, which we should skip adding an end entry. 147 // There are two cases: 148 // (1) MCAsmStreamer - emitDwarfLocDirective emits a location directive in 149 // place instead of adding a line entry if the target has 150 // usesDwarfFileAndLocDirectives. 151 // (2) MCObjectStreamer - if a function has incomplete debug info where 152 // instructions don't have DILocations, the line entries are missing. 153 auto I = MCLineDivisions.find(Sec); 154 if (I != MCLineDivisions.end()) { 155 auto &Entries = I->second; 156 auto EndEntry = Entries.back(); 157 EndEntry.setEndLabel(EndLabel); 158 Entries.push_back(EndEntry); 159 } 160 } 161 162 // 163 // This emits the Dwarf line table for the specified section from the entries 164 // in the LineSection. 165 // 166 void MCDwarfLineTable::emitOne( 167 MCStreamer *MCOS, MCSection *Section, 168 const MCLineSection::MCDwarfLineEntryCollection &LineEntries) { 169 170 unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator; 171 MCSymbol *LastLabel; 172 auto init = [&]() { 173 FileNum = 1; 174 LastLine = 1; 175 Column = 0; 176 Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 177 Isa = 0; 178 Discriminator = 0; 179 LastLabel = nullptr; 180 }; 181 init(); 182 183 // Loop through each MCDwarfLineEntry and encode the dwarf line number table. 184 bool EndEntryEmitted = false; 185 for (const MCDwarfLineEntry &LineEntry : LineEntries) { 186 MCSymbol *Label = LineEntry.getLabel(); 187 const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo(); 188 if (LineEntry.IsEndEntry) { 189 MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label, 190 asmInfo->getCodePointerSize()); 191 init(); 192 EndEntryEmitted = true; 193 continue; 194 } 195 196 int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine; 197 198 if (FileNum != LineEntry.getFileNum()) { 199 FileNum = LineEntry.getFileNum(); 200 MCOS->emitInt8(dwarf::DW_LNS_set_file); 201 MCOS->emitULEB128IntValue(FileNum); 202 } 203 if (Column != LineEntry.getColumn()) { 204 Column = LineEntry.getColumn(); 205 MCOS->emitInt8(dwarf::DW_LNS_set_column); 206 MCOS->emitULEB128IntValue(Column); 207 } 208 if (Discriminator != LineEntry.getDiscriminator() && 209 MCOS->getContext().getDwarfVersion() >= 4) { 210 Discriminator = LineEntry.getDiscriminator(); 211 unsigned Size = getULEB128Size(Discriminator); 212 MCOS->emitInt8(dwarf::DW_LNS_extended_op); 213 MCOS->emitULEB128IntValue(Size + 1); 214 MCOS->emitInt8(dwarf::DW_LNE_set_discriminator); 215 MCOS->emitULEB128IntValue(Discriminator); 216 } 217 if (Isa != LineEntry.getIsa()) { 218 Isa = LineEntry.getIsa(); 219 MCOS->emitInt8(dwarf::DW_LNS_set_isa); 220 MCOS->emitULEB128IntValue(Isa); 221 } 222 if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) { 223 Flags = LineEntry.getFlags(); 224 MCOS->emitInt8(dwarf::DW_LNS_negate_stmt); 225 } 226 if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK) 227 MCOS->emitInt8(dwarf::DW_LNS_set_basic_block); 228 if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END) 229 MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end); 230 if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN) 231 MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin); 232 233 // At this point we want to emit/create the sequence to encode the delta in 234 // line numbers and the increment of the address from the previous Label 235 // and the current Label. 236 MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label, 237 asmInfo->getCodePointerSize()); 238 239 Discriminator = 0; 240 LastLine = LineEntry.getLine(); 241 LastLabel = Label; 242 } 243 244 // Generate DWARF line end entry. 245 // We do not need this for DwarfDebug that explicitly terminates the line 246 // table using ranges whenever CU or section changes. However, the MC path 247 // does not track ranges nor terminate the line table. In that case, 248 // conservatively use the section end symbol to end the line table. 249 if (!EndEntryEmitted) 250 MCOS->emitDwarfLineEndEntry(Section, LastLabel); 251 } 252 253 // 254 // This emits the Dwarf file and the line tables. 255 // 256 void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) { 257 MCContext &context = MCOS->getContext(); 258 259 auto &LineTables = context.getMCDwarfLineTables(); 260 261 // Bail out early so we don't switch to the debug_line section needlessly and 262 // in doing so create an unnecessary (if empty) section. 263 if (LineTables.empty()) 264 return; 265 266 // In a v5 non-split line table, put the strings in a separate section. 267 Optional<MCDwarfLineStr> LineStr; 268 if (context.getDwarfVersion() >= 5) 269 LineStr.emplace(context); 270 271 // Switch to the section where the table will be emitted into. 272 MCOS->switchSection(context.getObjectFileInfo()->getDwarfLineSection()); 273 274 // Handle the rest of the Compile Units. 275 for (const auto &CUIDTablePair : LineTables) { 276 CUIDTablePair.second.emitCU(MCOS, Params, LineStr); 277 } 278 279 if (LineStr) 280 LineStr->emitSection(MCOS); 281 } 282 283 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params, 284 MCSection *Section) const { 285 if (!HasSplitLineTable) 286 return; 287 Optional<MCDwarfLineStr> NoLineStr(None); 288 MCOS.switchSection(Section); 289 MCOS.emitLabel(Header.Emit(&MCOS, Params, None, NoLineStr).second); 290 } 291 292 std::pair<MCSymbol *, MCSymbol *> 293 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 294 Optional<MCDwarfLineStr> &LineStr) const { 295 static const char StandardOpcodeLengths[] = { 296 0, // length of DW_LNS_copy 297 1, // length of DW_LNS_advance_pc 298 1, // length of DW_LNS_advance_line 299 1, // length of DW_LNS_set_file 300 1, // length of DW_LNS_set_column 301 0, // length of DW_LNS_negate_stmt 302 0, // length of DW_LNS_set_basic_block 303 0, // length of DW_LNS_const_add_pc 304 1, // length of DW_LNS_fixed_advance_pc 305 0, // length of DW_LNS_set_prologue_end 306 0, // length of DW_LNS_set_epilogue_begin 307 1 // DW_LNS_set_isa 308 }; 309 assert(array_lengthof(StandardOpcodeLengths) >= 310 (Params.DWARF2LineOpcodeBase - 1U)); 311 return Emit( 312 MCOS, Params, 313 makeArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1), 314 LineStr); 315 } 316 317 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) { 318 MCContext &Context = OS.getContext(); 319 assert(!isa<MCSymbolRefExpr>(Expr)); 320 if (Context.getAsmInfo()->hasAggressiveSymbolFolding()) 321 return Expr; 322 323 MCSymbol *ABS = Context.createTempSymbol(); 324 OS.emitAssignment(ABS, Expr); 325 return MCSymbolRefExpr::create(ABS, Context); 326 } 327 328 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) { 329 const MCExpr *ABS = forceExpAbs(OS, Value); 330 OS.emitValue(ABS, Size); 331 } 332 333 void MCDwarfLineStr::emitSection(MCStreamer *MCOS) { 334 // Switch to the .debug_line_str section. 335 MCOS->switchSection( 336 MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection()); 337 SmallString<0> Data = getFinalizedData(); 338 MCOS->emitBinaryData(Data.str()); 339 } 340 341 SmallString<0> MCDwarfLineStr::getFinalizedData() { 342 // Emit the strings without perturbing the offsets we used. 343 if (!LineStrings.isFinalized()) 344 LineStrings.finalizeInOrder(); 345 SmallString<0> Data; 346 Data.resize(LineStrings.getSize()); 347 LineStrings.write((uint8_t *)Data.data()); 348 return Data; 349 } 350 351 void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) { 352 int RefSize = 353 dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat()); 354 size_t Offset = LineStrings.add(Path); 355 if (UseRelocs) { 356 MCContext &Ctx = MCOS->getContext(); 357 MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize); 358 } else 359 MCOS->emitIntValue(Offset, RefSize); 360 } 361 362 void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const { 363 // First the directory table. 364 for (auto &Dir : MCDwarfDirs) { 365 MCOS->emitBytes(Dir); // The DirectoryName, and... 366 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 367 } 368 MCOS->emitInt8(0); // Terminate the directory list. 369 370 // Second the file table. 371 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) { 372 assert(!MCDwarfFiles[i].Name.empty()); 373 MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and... 374 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 375 MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number. 376 MCOS->emitInt8(0); // Last modification timestamp (always 0). 377 MCOS->emitInt8(0); // File size (always 0). 378 } 379 MCOS->emitInt8(0); // Terminate the file list. 380 } 381 382 static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile, 383 bool EmitMD5, bool HasSource, 384 Optional<MCDwarfLineStr> &LineStr) { 385 assert(!DwarfFile.Name.empty()); 386 if (LineStr) 387 LineStr->emitRef(MCOS, DwarfFile.Name); 388 else { 389 MCOS->emitBytes(DwarfFile.Name); // FileName and... 390 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 391 } 392 MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number. 393 if (EmitMD5) { 394 const MD5::MD5Result &Cksum = *DwarfFile.Checksum; 395 MCOS->emitBinaryData( 396 StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size())); 397 } 398 if (HasSource) { 399 if (LineStr) 400 LineStr->emitRef(MCOS, DwarfFile.Source.value_or(StringRef())); 401 else { 402 MCOS->emitBytes(DwarfFile.Source.value_or(StringRef())); // Source and... 403 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 404 } 405 } 406 } 407 408 void MCDwarfLineTableHeader::emitV5FileDirTables( 409 MCStreamer *MCOS, Optional<MCDwarfLineStr> &LineStr) const { 410 // The directory format, which is just a list of the directory paths. In a 411 // non-split object, these are references to .debug_line_str; in a split 412 // object, they are inline strings. 413 MCOS->emitInt8(1); 414 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path); 415 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 416 : dwarf::DW_FORM_string); 417 MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1); 418 // Try not to emit an empty compilation directory. 419 SmallString<256> Dir; 420 StringRef CompDir = MCOS->getContext().getCompilationDir(); 421 if (!CompilationDir.empty()) { 422 Dir = CompilationDir; 423 MCOS->getContext().remapDebugPath(Dir); 424 CompDir = Dir.str(); 425 if (LineStr) 426 CompDir = LineStr->getSaver().save(CompDir); 427 } 428 if (LineStr) { 429 // Record path strings, emit references here. 430 LineStr->emitRef(MCOS, CompDir); 431 for (const auto &Dir : MCDwarfDirs) 432 LineStr->emitRef(MCOS, Dir); 433 } else { 434 // The list of directory paths. Compilation directory comes first. 435 MCOS->emitBytes(CompDir); 436 MCOS->emitBytes(StringRef("\0", 1)); 437 for (const auto &Dir : MCDwarfDirs) { 438 MCOS->emitBytes(Dir); // The DirectoryName, and... 439 MCOS->emitBytes(StringRef("\0", 1)); // its null terminator. 440 } 441 } 442 443 // The file format, which is the inline null-terminated filename and a 444 // directory index. We don't track file size/timestamp so don't emit them 445 // in the v5 table. Emit MD5 checksums and source if we have them. 446 uint64_t Entries = 2; 447 if (HasAllMD5) 448 Entries += 1; 449 if (HasSource) 450 Entries += 1; 451 MCOS->emitInt8(Entries); 452 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path); 453 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 454 : dwarf::DW_FORM_string); 455 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index); 456 MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata); 457 if (HasAllMD5) { 458 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5); 459 MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16); 460 } 461 if (HasSource) { 462 MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source); 463 MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp 464 : dwarf::DW_FORM_string); 465 } 466 // Then the counted list of files. The root file is file #0, then emit the 467 // files as provide by .file directives. 468 // MCDwarfFiles has an unused element [0] so use size() not size()+1. 469 // But sometimes MCDwarfFiles is empty, in which case we still emit one file. 470 MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size()); 471 // To accommodate assembler source written for DWARF v4 but trying to emit 472 // v5: If we didn't see a root file explicitly, replicate file #1. 473 assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) && 474 "No root file and no .file directives"); 475 emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile, 476 HasAllMD5, HasSource, LineStr); 477 for (unsigned i = 1; i < MCDwarfFiles.size(); ++i) 478 emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr); 479 } 480 481 std::pair<MCSymbol *, MCSymbol *> 482 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 483 ArrayRef<char> StandardOpcodeLengths, 484 Optional<MCDwarfLineStr> &LineStr) const { 485 MCContext &context = MCOS->getContext(); 486 487 // Create a symbol at the beginning of the line table. 488 MCSymbol *LineStartSym = Label; 489 if (!LineStartSym) 490 LineStartSym = context.createTempSymbol(); 491 492 // Set the value of the symbol, as we are at the start of the line table. 493 MCOS->emitDwarfLineStartLabel(LineStartSym); 494 495 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 496 497 MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length"); 498 499 // Next 2 bytes is the Version. 500 unsigned LineTableVersion = context.getDwarfVersion(); 501 MCOS->emitInt16(LineTableVersion); 502 503 // In v5, we get address info next. 504 if (LineTableVersion >= 5) { 505 MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize()); 506 MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges. 507 } 508 509 // Create symbols for the start/end of the prologue. 510 MCSymbol *ProStartSym = context.createTempSymbol("prologue_start"); 511 MCSymbol *ProEndSym = context.createTempSymbol("prologue_end"); 512 513 // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is 514 // actually the length from after the length word, to the end of the prologue. 515 MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize); 516 517 MCOS->emitLabel(ProStartSym); 518 519 // Parameters of the state machine, are next. 520 MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment()); 521 // maximum_operations_per_instruction 522 // For non-VLIW architectures this field is always 1. 523 // FIXME: VLIW architectures need to update this field accordingly. 524 if (LineTableVersion >= 4) 525 MCOS->emitInt8(1); 526 MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT); 527 MCOS->emitInt8(Params.DWARF2LineBase); 528 MCOS->emitInt8(Params.DWARF2LineRange); 529 MCOS->emitInt8(StandardOpcodeLengths.size() + 1); 530 531 // Standard opcode lengths 532 for (char Length : StandardOpcodeLengths) 533 MCOS->emitInt8(Length); 534 535 // Put out the directory and file tables. The formats vary depending on 536 // the version. 537 if (LineTableVersion >= 5) 538 emitV5FileDirTables(MCOS, LineStr); 539 else 540 emitV2FileDirTables(MCOS); 541 542 // This is the end of the prologue, so set the value of the symbol at the 543 // end of the prologue (that was used in a previous expression). 544 MCOS->emitLabel(ProEndSym); 545 546 return std::make_pair(LineStartSym, LineEndSym); 547 } 548 549 void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params, 550 Optional<MCDwarfLineStr> &LineStr) const { 551 MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second; 552 553 // Put out the line tables. 554 for (const auto &LineSec : MCLineSections.getMCLineEntries()) 555 emitOne(MCOS, LineSec.first, LineSec.second); 556 557 // This is the end of the section, so set the value of the symbol at the end 558 // of this section (that was used in a previous expression). 559 MCOS->emitLabel(LineEndSym); 560 } 561 562 Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory, 563 StringRef &FileName, 564 Optional<MD5::MD5Result> Checksum, 565 Optional<StringRef> Source, 566 uint16_t DwarfVersion, 567 unsigned FileNumber) { 568 return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion, 569 FileNumber); 570 } 571 572 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory, 573 StringRef &FileName, Optional<MD5::MD5Result> Checksum) { 574 if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName) 575 return false; 576 return RootFile.Checksum == Checksum; 577 } 578 579 Expected<unsigned> 580 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, 581 StringRef &FileName, 582 Optional<MD5::MD5Result> Checksum, 583 Optional<StringRef> Source, 584 uint16_t DwarfVersion, 585 unsigned FileNumber) { 586 if (Directory == CompilationDir) 587 Directory = ""; 588 if (FileName.empty()) { 589 FileName = "<stdin>"; 590 Directory = ""; 591 } 592 assert(!FileName.empty()); 593 // Keep track of whether any or all files have an MD5 checksum. 594 // If any files have embedded source, they all must. 595 if (MCDwarfFiles.empty()) { 596 trackMD5Usage(Checksum.has_value()); 597 HasSource = (Source != None); 598 } 599 if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum)) 600 return 0; 601 if (FileNumber == 0) { 602 // File numbers start with 1 and/or after any file numbers 603 // allocated by inline-assembler .file directives. 604 FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size(); 605 SmallString<256> Buffer; 606 auto IterBool = SourceIdMap.insert( 607 std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer), 608 FileNumber)); 609 if (!IterBool.second) 610 return IterBool.first->second; 611 } 612 // Make space for this FileNumber in the MCDwarfFiles vector if needed. 613 if (FileNumber >= MCDwarfFiles.size()) 614 MCDwarfFiles.resize(FileNumber + 1); 615 616 // Get the new MCDwarfFile slot for this FileNumber. 617 MCDwarfFile &File = MCDwarfFiles[FileNumber]; 618 619 // It is an error to see the same number more than once. 620 if (!File.Name.empty()) 621 return make_error<StringError>("file number already allocated", 622 inconvertibleErrorCode()); 623 624 // If any files have embedded source, they all must. 625 if (HasSource != (Source != None)) 626 return make_error<StringError>("inconsistent use of embedded source", 627 inconvertibleErrorCode()); 628 629 if (Directory.empty()) { 630 // Separate the directory part from the basename of the FileName. 631 StringRef tFileName = sys::path::filename(FileName); 632 if (!tFileName.empty()) { 633 Directory = sys::path::parent_path(FileName); 634 if (!Directory.empty()) 635 FileName = tFileName; 636 } 637 } 638 639 // Find or make an entry in the MCDwarfDirs vector for this Directory. 640 // Capture directory name. 641 unsigned DirIndex; 642 if (Directory.empty()) { 643 // For FileNames with no directories a DirIndex of 0 is used. 644 DirIndex = 0; 645 } else { 646 DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin(); 647 if (DirIndex >= MCDwarfDirs.size()) 648 MCDwarfDirs.push_back(std::string(Directory)); 649 // The DirIndex is one based, as DirIndex of 0 is used for FileNames with 650 // no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the 651 // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames 652 // are stored at MCDwarfFiles[FileNumber].Name . 653 DirIndex++; 654 } 655 656 File.Name = std::string(FileName); 657 File.DirIndex = DirIndex; 658 File.Checksum = Checksum; 659 trackMD5Usage(Checksum.has_value()); 660 File.Source = Source; 661 if (Source) 662 HasSource = true; 663 664 // return the allocated FileNumber. 665 return FileNumber; 666 } 667 668 /// Utility function to emit the encoding to a streamer. 669 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params, 670 int64_t LineDelta, uint64_t AddrDelta) { 671 MCContext &Context = MCOS->getContext(); 672 SmallString<256> Tmp; 673 raw_svector_ostream OS(Tmp); 674 MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS); 675 MCOS->emitBytes(OS.str()); 676 } 677 678 /// Given a special op, return the address skip amount (in units of 679 /// DWARF2_LINE_MIN_INSN_LENGTH). 680 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) { 681 return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange; 682 } 683 684 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas. 685 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params, 686 int64_t LineDelta, uint64_t AddrDelta, 687 raw_ostream &OS) { 688 uint64_t Temp, Opcode; 689 bool NeedCopy = false; 690 691 // The maximum address skip amount that can be encoded with a special op. 692 uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255); 693 694 // Scale the address delta by the minimum instruction length. 695 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 696 697 // A LineDelta of INT64_MAX is a signal that this is actually a 698 // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 699 // end_sequence to emit the matrix entry. 700 if (LineDelta == INT64_MAX) { 701 if (AddrDelta == MaxSpecialAddrDelta) 702 OS << char(dwarf::DW_LNS_const_add_pc); 703 else if (AddrDelta) { 704 OS << char(dwarf::DW_LNS_advance_pc); 705 encodeULEB128(AddrDelta, OS); 706 } 707 OS << char(dwarf::DW_LNS_extended_op); 708 OS << char(1); 709 OS << char(dwarf::DW_LNE_end_sequence); 710 return; 711 } 712 713 // Bias the line delta by the base. 714 Temp = LineDelta - Params.DWARF2LineBase; 715 716 // If the line increment is out of range of a special opcode, we must encode 717 // it with DW_LNS_advance_line. 718 if (Temp >= Params.DWARF2LineRange || 719 Temp + Params.DWARF2LineOpcodeBase > 255) { 720 OS << char(dwarf::DW_LNS_advance_line); 721 encodeSLEB128(LineDelta, OS); 722 723 LineDelta = 0; 724 Temp = 0 - Params.DWARF2LineBase; 725 NeedCopy = true; 726 } 727 728 // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode. 729 if (LineDelta == 0 && AddrDelta == 0) { 730 OS << char(dwarf::DW_LNS_copy); 731 return; 732 } 733 734 // Bias the opcode by the special opcode base. 735 Temp += Params.DWARF2LineOpcodeBase; 736 737 // Avoid overflow when addr_delta is large. 738 if (AddrDelta < 256 + MaxSpecialAddrDelta) { 739 // Try using a special opcode. 740 Opcode = Temp + AddrDelta * Params.DWARF2LineRange; 741 if (Opcode <= 255) { 742 OS << char(Opcode); 743 return; 744 } 745 746 // Try using DW_LNS_const_add_pc followed by special op. 747 Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange; 748 if (Opcode <= 255) { 749 OS << char(dwarf::DW_LNS_const_add_pc); 750 OS << char(Opcode); 751 return; 752 } 753 } 754 755 // Otherwise use DW_LNS_advance_pc. 756 OS << char(dwarf::DW_LNS_advance_pc); 757 encodeULEB128(AddrDelta, OS); 758 759 if (NeedCopy) 760 OS << char(dwarf::DW_LNS_copy); 761 else { 762 assert(Temp <= 255 && "Buggy special opcode encoding."); 763 OS << char(Temp); 764 } 765 } 766 767 // Utility function to write a tuple for .debug_abbrev. 768 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) { 769 MCOS->emitULEB128IntValue(Name); 770 MCOS->emitULEB128IntValue(Form); 771 } 772 773 // When generating dwarf for assembly source files this emits 774 // the data for .debug_abbrev section which contains three DIEs. 775 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) { 776 MCContext &context = MCOS->getContext(); 777 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 778 779 // DW_TAG_compile_unit DIE abbrev (1). 780 MCOS->emitULEB128IntValue(1); 781 MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit); 782 MCOS->emitInt8(dwarf::DW_CHILDREN_yes); 783 dwarf::Form SecOffsetForm = 784 context.getDwarfVersion() >= 4 785 ? dwarf::DW_FORM_sec_offset 786 : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8 787 : dwarf::DW_FORM_data4); 788 EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm); 789 if (context.getGenDwarfSectionSyms().size() > 1 && 790 context.getDwarfVersion() >= 3) { 791 EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm); 792 } else { 793 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 794 EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr); 795 } 796 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 797 if (!context.getCompilationDir().empty()) 798 EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string); 799 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 800 if (!DwarfDebugFlags.empty()) 801 EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string); 802 EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string); 803 EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2); 804 EmitAbbrev(MCOS, 0, 0); 805 806 // DW_TAG_label DIE abbrev (2). 807 MCOS->emitULEB128IntValue(2); 808 MCOS->emitULEB128IntValue(dwarf::DW_TAG_label); 809 MCOS->emitInt8(dwarf::DW_CHILDREN_no); 810 EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string); 811 EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4); 812 EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4); 813 EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr); 814 EmitAbbrev(MCOS, 0, 0); 815 816 // Terminate the abbreviations for this compilation unit. 817 MCOS->emitInt8(0); 818 } 819 820 // When generating dwarf for assembly source files this emits the data for 821 // .debug_aranges section. This section contains a header and a table of pairs 822 // of PointerSize'ed values for the address and size of section(s) with line 823 // table entries. 824 static void EmitGenDwarfAranges(MCStreamer *MCOS, 825 const MCSymbol *InfoSectionSymbol) { 826 MCContext &context = MCOS->getContext(); 827 828 auto &Sections = context.getGenDwarfSectionSyms(); 829 830 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 831 832 unsigned UnitLengthBytes = 833 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat()); 834 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 835 836 // This will be the length of the .debug_aranges section, first account for 837 // the size of each item in the header (see below where we emit these items). 838 int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1; 839 840 // Figure the padding after the header before the table of address and size 841 // pairs who's values are PointerSize'ed. 842 const MCAsmInfo *asmInfo = context.getAsmInfo(); 843 int AddrSize = asmInfo->getCodePointerSize(); 844 int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1)); 845 if (Pad == 2 * AddrSize) 846 Pad = 0; 847 Length += Pad; 848 849 // Add the size of the pair of PointerSize'ed values for the address and size 850 // of each section we have in the table. 851 Length += 2 * AddrSize * Sections.size(); 852 // And the pair of terminating zeros. 853 Length += 2 * AddrSize; 854 855 // Emit the header for this section. 856 if (context.getDwarfFormat() == dwarf::DWARF64) 857 // The DWARF64 mark. 858 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64); 859 // The 4 (8 for DWARF64) byte length not including the length of the unit 860 // length field itself. 861 MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize); 862 // The 2 byte version, which is 2. 863 MCOS->emitInt16(2); 864 // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info 865 // from the start of the .debug_info. 866 if (InfoSectionSymbol) 867 MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize, 868 asmInfo->needsDwarfSectionOffsetDirective()); 869 else 870 MCOS->emitIntValue(0, OffsetSize); 871 // The 1 byte size of an address. 872 MCOS->emitInt8(AddrSize); 873 // The 1 byte size of a segment descriptor, we use a value of zero. 874 MCOS->emitInt8(0); 875 // Align the header with the padding if needed, before we put out the table. 876 for(int i = 0; i < Pad; i++) 877 MCOS->emitInt8(0); 878 879 // Now emit the table of pairs of PointerSize'ed values for the section 880 // addresses and sizes. 881 for (MCSection *Sec : Sections) { 882 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 883 MCSymbol *EndSymbol = Sec->getEndSymbol(context); 884 assert(StartSymbol && "StartSymbol must not be NULL"); 885 assert(EndSymbol && "EndSymbol must not be NULL"); 886 887 const MCExpr *Addr = MCSymbolRefExpr::create( 888 StartSymbol, MCSymbolRefExpr::VK_None, context); 889 const MCExpr *Size = 890 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 891 MCOS->emitValue(Addr, AddrSize); 892 emitAbsValue(*MCOS, Size, AddrSize); 893 } 894 895 // And finally the pair of terminating zeros. 896 MCOS->emitIntValue(0, AddrSize); 897 MCOS->emitIntValue(0, AddrSize); 898 } 899 900 // When generating dwarf for assembly source files this emits the data for 901 // .debug_info section which contains three parts. The header, the compile_unit 902 // DIE and a list of label DIEs. 903 static void EmitGenDwarfInfo(MCStreamer *MCOS, 904 const MCSymbol *AbbrevSectionSymbol, 905 const MCSymbol *LineSectionSymbol, 906 const MCSymbol *RangesSymbol) { 907 MCContext &context = MCOS->getContext(); 908 909 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 910 911 // Create a symbol at the start and end of this section used in here for the 912 // expression to calculate the length in the header. 913 MCSymbol *InfoStart = context.createTempSymbol(); 914 MCOS->emitLabel(InfoStart); 915 MCSymbol *InfoEnd = context.createTempSymbol(); 916 917 // First part: the header. 918 919 unsigned UnitLengthBytes = 920 dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat()); 921 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat()); 922 923 if (context.getDwarfFormat() == dwarf::DWARF64) 924 // Emit DWARF64 mark. 925 MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64); 926 927 // The 4 (8 for DWARF64) byte total length of the information for this 928 // compilation unit, not including the unit length field itself. 929 const MCExpr *Length = 930 makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes); 931 emitAbsValue(*MCOS, Length, OffsetSize); 932 933 // The 2 byte DWARF version. 934 MCOS->emitInt16(context.getDwarfVersion()); 935 936 // The DWARF v5 header has unit type, address size, abbrev offset. 937 // Earlier versions have abbrev offset, address size. 938 const MCAsmInfo &AsmInfo = *context.getAsmInfo(); 939 int AddrSize = AsmInfo.getCodePointerSize(); 940 if (context.getDwarfVersion() >= 5) { 941 MCOS->emitInt8(dwarf::DW_UT_compile); 942 MCOS->emitInt8(AddrSize); 943 } 944 // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of 945 // the .debug_abbrev. 946 if (AbbrevSectionSymbol) 947 MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize, 948 AsmInfo.needsDwarfSectionOffsetDirective()); 949 else 950 // Since the abbrevs are at the start of the section, the offset is zero. 951 MCOS->emitIntValue(0, OffsetSize); 952 if (context.getDwarfVersion() <= 4) 953 MCOS->emitInt8(AddrSize); 954 955 // Second part: the compile_unit DIE. 956 957 // The DW_TAG_compile_unit DIE abbrev (1). 958 MCOS->emitULEB128IntValue(1); 959 960 // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the 961 // .debug_line section. 962 if (LineSectionSymbol) 963 MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize, 964 AsmInfo.needsDwarfSectionOffsetDirective()); 965 else 966 // The line table is at the start of the section, so the offset is zero. 967 MCOS->emitIntValue(0, OffsetSize); 968 969 if (RangesSymbol) { 970 // There are multiple sections containing code, so we must use 971 // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the 972 // start of the .debug_ranges/.debug_rnglists. 973 MCOS->emitSymbolValue(RangesSymbol, OffsetSize); 974 } else { 975 // If we only have one non-empty code section, we can use the simpler 976 // AT_low_pc and AT_high_pc attributes. 977 978 // Find the first (and only) non-empty text section 979 auto &Sections = context.getGenDwarfSectionSyms(); 980 const auto TextSection = Sections.begin(); 981 assert(TextSection != Sections.end() && "No text section found"); 982 983 MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol(); 984 MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context); 985 assert(StartSymbol && "StartSymbol must not be NULL"); 986 assert(EndSymbol && "EndSymbol must not be NULL"); 987 988 // AT_low_pc, the first address of the default .text section. 989 const MCExpr *Start = MCSymbolRefExpr::create( 990 StartSymbol, MCSymbolRefExpr::VK_None, context); 991 MCOS->emitValue(Start, AddrSize); 992 993 // AT_high_pc, the last address of the default .text section. 994 const MCExpr *End = MCSymbolRefExpr::create( 995 EndSymbol, MCSymbolRefExpr::VK_None, context); 996 MCOS->emitValue(End, AddrSize); 997 } 998 999 // AT_name, the name of the source file. Reconstruct from the first directory 1000 // and file table entries. 1001 const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs(); 1002 if (MCDwarfDirs.size() > 0) { 1003 MCOS->emitBytes(MCDwarfDirs[0]); 1004 MCOS->emitBytes(sys::path::get_separator()); 1005 } 1006 const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles(); 1007 // MCDwarfFiles might be empty if we have an empty source file. 1008 // If it's not empty, [0] is unused and [1] is the first actual file. 1009 assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2); 1010 const MCDwarfFile &RootFile = 1011 MCDwarfFiles.empty() 1012 ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile() 1013 : MCDwarfFiles[1]; 1014 MCOS->emitBytes(RootFile.Name); 1015 MCOS->emitInt8(0); // NULL byte to terminate the string. 1016 1017 // AT_comp_dir, the working directory the assembly was done in. 1018 if (!context.getCompilationDir().empty()) { 1019 MCOS->emitBytes(context.getCompilationDir()); 1020 MCOS->emitInt8(0); // NULL byte to terminate the string. 1021 } 1022 1023 // AT_APPLE_flags, the command line arguments of the assembler tool. 1024 StringRef DwarfDebugFlags = context.getDwarfDebugFlags(); 1025 if (!DwarfDebugFlags.empty()){ 1026 MCOS->emitBytes(DwarfDebugFlags); 1027 MCOS->emitInt8(0); // NULL byte to terminate the string. 1028 } 1029 1030 // AT_producer, the version of the assembler tool. 1031 StringRef DwarfDebugProducer = context.getDwarfDebugProducer(); 1032 if (!DwarfDebugProducer.empty()) 1033 MCOS->emitBytes(DwarfDebugProducer); 1034 else 1035 MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")")); 1036 MCOS->emitInt8(0); // NULL byte to terminate the string. 1037 1038 // AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf2 1039 // draft has no standard code for assembler. 1040 MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler); 1041 1042 // Third part: the list of label DIEs. 1043 1044 // Loop on saved info for dwarf labels and create the DIEs for them. 1045 const std::vector<MCGenDwarfLabelEntry> &Entries = 1046 MCOS->getContext().getMCGenDwarfLabelEntries(); 1047 for (const auto &Entry : Entries) { 1048 // The DW_TAG_label DIE abbrev (2). 1049 MCOS->emitULEB128IntValue(2); 1050 1051 // AT_name, of the label without any leading underbar. 1052 MCOS->emitBytes(Entry.getName()); 1053 MCOS->emitInt8(0); // NULL byte to terminate the string. 1054 1055 // AT_decl_file, index into the file table. 1056 MCOS->emitInt32(Entry.getFileNumber()); 1057 1058 // AT_decl_line, source line number. 1059 MCOS->emitInt32(Entry.getLineNumber()); 1060 1061 // AT_low_pc, start address of the label. 1062 const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(), 1063 MCSymbolRefExpr::VK_None, context); 1064 MCOS->emitValue(AT_low_pc, AddrSize); 1065 } 1066 1067 // Add the NULL DIE terminating the Compile Unit DIE's. 1068 MCOS->emitInt8(0); 1069 1070 // Now set the value of the symbol at the end of the info section. 1071 MCOS->emitLabel(InfoEnd); 1072 } 1073 1074 // When generating dwarf for assembly source files this emits the data for 1075 // .debug_ranges section. We only emit one range list, which spans all of the 1076 // executable sections of this file. 1077 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) { 1078 MCContext &context = MCOS->getContext(); 1079 auto &Sections = context.getGenDwarfSectionSyms(); 1080 1081 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 1082 int AddrSize = AsmInfo->getCodePointerSize(); 1083 MCSymbol *RangesSymbol; 1084 1085 if (MCOS->getContext().getDwarfVersion() >= 5) { 1086 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRnglistsSection()); 1087 MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS); 1088 MCOS->AddComment("Offset entry count"); 1089 MCOS->emitInt32(0); 1090 RangesSymbol = context.createTempSymbol("debug_rnglist0_start"); 1091 MCOS->emitLabel(RangesSymbol); 1092 for (MCSection *Sec : Sections) { 1093 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 1094 const MCSymbol *EndSymbol = Sec->getEndSymbol(context); 1095 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create( 1096 StartSymbol, MCSymbolRefExpr::VK_None, context); 1097 const MCExpr *SectionSize = 1098 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 1099 MCOS->emitInt8(dwarf::DW_RLE_start_length); 1100 MCOS->emitValue(SectionStartAddr, AddrSize); 1101 MCOS->emitULEB128Value(SectionSize); 1102 } 1103 MCOS->emitInt8(dwarf::DW_RLE_end_of_list); 1104 MCOS->emitLabel(EndSymbol); 1105 } else { 1106 MCOS->switchSection(context.getObjectFileInfo()->getDwarfRangesSection()); 1107 RangesSymbol = context.createTempSymbol("debug_ranges_start"); 1108 MCOS->emitLabel(RangesSymbol); 1109 for (MCSection *Sec : Sections) { 1110 const MCSymbol *StartSymbol = Sec->getBeginSymbol(); 1111 const MCSymbol *EndSymbol = Sec->getEndSymbol(context); 1112 1113 // Emit a base address selection entry for the section start. 1114 const MCExpr *SectionStartAddr = MCSymbolRefExpr::create( 1115 StartSymbol, MCSymbolRefExpr::VK_None, context); 1116 MCOS->emitFill(AddrSize, 0xFF); 1117 MCOS->emitValue(SectionStartAddr, AddrSize); 1118 1119 // Emit a range list entry spanning this section. 1120 const MCExpr *SectionSize = 1121 makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0); 1122 MCOS->emitIntValue(0, AddrSize); 1123 emitAbsValue(*MCOS, SectionSize, AddrSize); 1124 } 1125 1126 // Emit end of list entry 1127 MCOS->emitIntValue(0, AddrSize); 1128 MCOS->emitIntValue(0, AddrSize); 1129 } 1130 1131 return RangesSymbol; 1132 } 1133 1134 // 1135 // When generating dwarf for assembly source files this emits the Dwarf 1136 // sections. 1137 // 1138 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) { 1139 MCContext &context = MCOS->getContext(); 1140 1141 // Create the dwarf sections in this order (.debug_line already created). 1142 const MCAsmInfo *AsmInfo = context.getAsmInfo(); 1143 bool CreateDwarfSectionSymbols = 1144 AsmInfo->doesDwarfUseRelocationsAcrossSections(); 1145 MCSymbol *LineSectionSymbol = nullptr; 1146 if (CreateDwarfSectionSymbols) 1147 LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0); 1148 MCSymbol *AbbrevSectionSymbol = nullptr; 1149 MCSymbol *InfoSectionSymbol = nullptr; 1150 MCSymbol *RangesSymbol = nullptr; 1151 1152 // Create end symbols for each section, and remove empty sections 1153 MCOS->getContext().finalizeDwarfSections(*MCOS); 1154 1155 // If there are no sections to generate debug info for, we don't need 1156 // to do anything 1157 if (MCOS->getContext().getGenDwarfSectionSyms().empty()) 1158 return; 1159 1160 // We only use the .debug_ranges section if we have multiple code sections, 1161 // and we are emitting a DWARF version which supports it. 1162 const bool UseRangesSection = 1163 MCOS->getContext().getGenDwarfSectionSyms().size() > 1 && 1164 MCOS->getContext().getDwarfVersion() >= 3; 1165 CreateDwarfSectionSymbols |= UseRangesSection; 1166 1167 MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection()); 1168 if (CreateDwarfSectionSymbols) { 1169 InfoSectionSymbol = context.createTempSymbol(); 1170 MCOS->emitLabel(InfoSectionSymbol); 1171 } 1172 MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()); 1173 if (CreateDwarfSectionSymbols) { 1174 AbbrevSectionSymbol = context.createTempSymbol(); 1175 MCOS->emitLabel(AbbrevSectionSymbol); 1176 } 1177 1178 MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection()); 1179 1180 // Output the data for .debug_aranges section. 1181 EmitGenDwarfAranges(MCOS, InfoSectionSymbol); 1182 1183 if (UseRangesSection) { 1184 RangesSymbol = emitGenDwarfRanges(MCOS); 1185 assert(RangesSymbol); 1186 } 1187 1188 // Output the data for .debug_abbrev section. 1189 EmitGenDwarfAbbrev(MCOS); 1190 1191 // Output the data for .debug_info section. 1192 EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol); 1193 } 1194 1195 // 1196 // When generating dwarf for assembly source files this is called when symbol 1197 // for a label is created. If this symbol is not a temporary and is in the 1198 // section that dwarf is being generated for, save the needed info to create 1199 // a dwarf label. 1200 // 1201 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS, 1202 SourceMgr &SrcMgr, SMLoc &Loc) { 1203 // We won't create dwarf labels for temporary symbols. 1204 if (Symbol->isTemporary()) 1205 return; 1206 MCContext &context = MCOS->getContext(); 1207 // We won't create dwarf labels for symbols in sections that we are not 1208 // generating debug info for. 1209 if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly())) 1210 return; 1211 1212 // The dwarf label's name does not have the symbol name's leading 1213 // underbar if any. 1214 StringRef Name = Symbol->getName(); 1215 if (Name.startswith("_")) 1216 Name = Name.substr(1, Name.size()-1); 1217 1218 // Get the dwarf file number to be used for the dwarf label. 1219 unsigned FileNumber = context.getGenDwarfFileNumber(); 1220 1221 // Finding the line number is the expensive part which is why we just don't 1222 // pass it in as for some symbols we won't create a dwarf label. 1223 unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc); 1224 unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer); 1225 1226 // We create a temporary symbol for use for the AT_high_pc and AT_low_pc 1227 // values so that they don't have things like an ARM thumb bit from the 1228 // original symbol. So when used they won't get a low bit set after 1229 // relocation. 1230 MCSymbol *Label = context.createTempSymbol(); 1231 MCOS->emitLabel(Label); 1232 1233 // Create and entry for the info and add it to the other entries. 1234 MCOS->getContext().addMCGenDwarfLabelEntry( 1235 MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label)); 1236 } 1237 1238 static int getDataAlignmentFactor(MCStreamer &streamer) { 1239 MCContext &context = streamer.getContext(); 1240 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1241 int size = asmInfo->getCalleeSaveStackSlotSize(); 1242 if (asmInfo->isStackGrowthDirectionUp()) 1243 return size; 1244 else 1245 return -size; 1246 } 1247 1248 static unsigned getSizeForEncoding(MCStreamer &streamer, 1249 unsigned symbolEncoding) { 1250 MCContext &context = streamer.getContext(); 1251 unsigned format = symbolEncoding & 0x0f; 1252 switch (format) { 1253 default: llvm_unreachable("Unknown Encoding"); 1254 case dwarf::DW_EH_PE_absptr: 1255 case dwarf::DW_EH_PE_signed: 1256 return context.getAsmInfo()->getCodePointerSize(); 1257 case dwarf::DW_EH_PE_udata2: 1258 case dwarf::DW_EH_PE_sdata2: 1259 return 2; 1260 case dwarf::DW_EH_PE_udata4: 1261 case dwarf::DW_EH_PE_sdata4: 1262 return 4; 1263 case dwarf::DW_EH_PE_udata8: 1264 case dwarf::DW_EH_PE_sdata8: 1265 return 8; 1266 } 1267 } 1268 1269 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol, 1270 unsigned symbolEncoding, bool isEH) { 1271 MCContext &context = streamer.getContext(); 1272 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1273 const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol, 1274 symbolEncoding, 1275 streamer); 1276 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 1277 if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH) 1278 emitAbsValue(streamer, v, size); 1279 else 1280 streamer.emitValue(v, size); 1281 } 1282 1283 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol, 1284 unsigned symbolEncoding) { 1285 MCContext &context = streamer.getContext(); 1286 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1287 const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol, 1288 symbolEncoding, 1289 streamer); 1290 unsigned size = getSizeForEncoding(streamer, symbolEncoding); 1291 streamer.emitValue(v, size); 1292 } 1293 1294 namespace { 1295 1296 class FrameEmitterImpl { 1297 int CFAOffset = 0; 1298 int InitialCFAOffset = 0; 1299 bool IsEH; 1300 MCObjectStreamer &Streamer; 1301 1302 public: 1303 FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer) 1304 : IsEH(IsEH), Streamer(Streamer) {} 1305 1306 /// Emit the unwind information in a compact way. 1307 void EmitCompactUnwind(const MCDwarfFrameInfo &frame); 1308 1309 const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F); 1310 void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame, 1311 bool LastInSection, const MCSymbol &SectionStart); 1312 void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1313 MCSymbol *BaseLabel); 1314 void emitCFIInstruction(const MCCFIInstruction &Instr); 1315 }; 1316 1317 } // end anonymous namespace 1318 1319 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) { 1320 Streamer.emitInt8(Encoding); 1321 } 1322 1323 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) { 1324 int dataAlignmentFactor = getDataAlignmentFactor(Streamer); 1325 auto *MRI = Streamer.getContext().getRegisterInfo(); 1326 1327 switch (Instr.getOperation()) { 1328 case MCCFIInstruction::OpRegister: { 1329 unsigned Reg1 = Instr.getRegister(); 1330 unsigned Reg2 = Instr.getRegister2(); 1331 if (!IsEH) { 1332 Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1); 1333 Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2); 1334 } 1335 Streamer.emitInt8(dwarf::DW_CFA_register); 1336 Streamer.emitULEB128IntValue(Reg1); 1337 Streamer.emitULEB128IntValue(Reg2); 1338 return; 1339 } 1340 case MCCFIInstruction::OpWindowSave: 1341 Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save); 1342 return; 1343 1344 case MCCFIInstruction::OpNegateRAState: 1345 Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state); 1346 return; 1347 1348 case MCCFIInstruction::OpUndefined: { 1349 unsigned Reg = Instr.getRegister(); 1350 Streamer.emitInt8(dwarf::DW_CFA_undefined); 1351 Streamer.emitULEB128IntValue(Reg); 1352 return; 1353 } 1354 case MCCFIInstruction::OpAdjustCfaOffset: 1355 case MCCFIInstruction::OpDefCfaOffset: { 1356 const bool IsRelative = 1357 Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset; 1358 1359 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset); 1360 1361 if (IsRelative) 1362 CFAOffset += Instr.getOffset(); 1363 else 1364 CFAOffset = Instr.getOffset(); 1365 1366 Streamer.emitULEB128IntValue(CFAOffset); 1367 1368 return; 1369 } 1370 case MCCFIInstruction::OpDefCfa: { 1371 unsigned Reg = Instr.getRegister(); 1372 if (!IsEH) 1373 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1374 Streamer.emitInt8(dwarf::DW_CFA_def_cfa); 1375 Streamer.emitULEB128IntValue(Reg); 1376 CFAOffset = Instr.getOffset(); 1377 Streamer.emitULEB128IntValue(CFAOffset); 1378 1379 return; 1380 } 1381 case MCCFIInstruction::OpDefCfaRegister: { 1382 unsigned Reg = Instr.getRegister(); 1383 if (!IsEH) 1384 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1385 Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register); 1386 Streamer.emitULEB128IntValue(Reg); 1387 1388 return; 1389 } 1390 // TODO: Implement `_sf` variants if/when they need to be emitted. 1391 case MCCFIInstruction::OpLLVMDefAspaceCfa: { 1392 unsigned Reg = Instr.getRegister(); 1393 if (!IsEH) 1394 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1395 Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1); 1396 Streamer.emitULEB128IntValue(Reg); 1397 CFAOffset = Instr.getOffset(); 1398 Streamer.emitULEB128IntValue(CFAOffset); 1399 Streamer.emitULEB128IntValue(Instr.getAddressSpace()); 1400 1401 return; 1402 } 1403 case MCCFIInstruction::OpOffset: 1404 case MCCFIInstruction::OpRelOffset: { 1405 const bool IsRelative = 1406 Instr.getOperation() == MCCFIInstruction::OpRelOffset; 1407 1408 unsigned Reg = Instr.getRegister(); 1409 if (!IsEH) 1410 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1411 1412 int Offset = Instr.getOffset(); 1413 if (IsRelative) 1414 Offset -= CFAOffset; 1415 Offset = Offset / dataAlignmentFactor; 1416 1417 if (Offset < 0) { 1418 Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf); 1419 Streamer.emitULEB128IntValue(Reg); 1420 Streamer.emitSLEB128IntValue(Offset); 1421 } else if (Reg < 64) { 1422 Streamer.emitInt8(dwarf::DW_CFA_offset + Reg); 1423 Streamer.emitULEB128IntValue(Offset); 1424 } else { 1425 Streamer.emitInt8(dwarf::DW_CFA_offset_extended); 1426 Streamer.emitULEB128IntValue(Reg); 1427 Streamer.emitULEB128IntValue(Offset); 1428 } 1429 return; 1430 } 1431 case MCCFIInstruction::OpRememberState: 1432 Streamer.emitInt8(dwarf::DW_CFA_remember_state); 1433 return; 1434 case MCCFIInstruction::OpRestoreState: 1435 Streamer.emitInt8(dwarf::DW_CFA_restore_state); 1436 return; 1437 case MCCFIInstruction::OpSameValue: { 1438 unsigned Reg = Instr.getRegister(); 1439 Streamer.emitInt8(dwarf::DW_CFA_same_value); 1440 Streamer.emitULEB128IntValue(Reg); 1441 return; 1442 } 1443 case MCCFIInstruction::OpRestore: { 1444 unsigned Reg = Instr.getRegister(); 1445 if (!IsEH) 1446 Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg); 1447 if (Reg < 64) { 1448 Streamer.emitInt8(dwarf::DW_CFA_restore | Reg); 1449 } else { 1450 Streamer.emitInt8(dwarf::DW_CFA_restore_extended); 1451 Streamer.emitULEB128IntValue(Reg); 1452 } 1453 return; 1454 } 1455 case MCCFIInstruction::OpGnuArgsSize: 1456 Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size); 1457 Streamer.emitULEB128IntValue(Instr.getOffset()); 1458 return; 1459 1460 case MCCFIInstruction::OpEscape: 1461 Streamer.emitBytes(Instr.getValues()); 1462 return; 1463 } 1464 llvm_unreachable("Unhandled case in switch"); 1465 } 1466 1467 /// Emit frame instructions to describe the layout of the frame. 1468 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs, 1469 MCSymbol *BaseLabel) { 1470 for (const MCCFIInstruction &Instr : Instrs) { 1471 MCSymbol *Label = Instr.getLabel(); 1472 // Throw out move if the label is invalid. 1473 if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. 1474 1475 // Advance row if new location. 1476 if (BaseLabel && Label) { 1477 MCSymbol *ThisSym = Label; 1478 if (ThisSym != BaseLabel) { 1479 Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym); 1480 BaseLabel = ThisSym; 1481 } 1482 } 1483 1484 emitCFIInstruction(Instr); 1485 } 1486 } 1487 1488 /// Emit the unwind information in a compact way. 1489 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) { 1490 MCContext &Context = Streamer.getContext(); 1491 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1492 1493 // range-start range-length compact-unwind-enc personality-func lsda 1494 // _foo LfooEnd-_foo 0x00000023 0 0 1495 // _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab1 1496 // 1497 // .section __LD,__compact_unwind,regular,debug 1498 // 1499 // # compact unwind for _foo 1500 // .quad _foo 1501 // .set L1,LfooEnd-_foo 1502 // .long L1 1503 // .long 0x01010001 1504 // .quad 0 1505 // .quad 0 1506 // 1507 // # compact unwind for _bar 1508 // .quad _bar 1509 // .set L2,LbarEnd-_bar 1510 // .long L2 1511 // .long 0x01020011 1512 // .quad __gxx_personality 1513 // .quad except_tab1 1514 1515 uint32_t Encoding = Frame.CompactUnwindEncoding; 1516 if (!Encoding) return; 1517 bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly()); 1518 1519 // The encoding needs to know we have an LSDA. 1520 if (!DwarfEHFrameOnly && Frame.Lsda) 1521 Encoding |= 0x40000000; 1522 1523 // Range Start 1524 unsigned FDEEncoding = MOFI->getFDEEncoding(); 1525 unsigned Size = getSizeForEncoding(Streamer, FDEEncoding); 1526 Streamer.emitSymbolValue(Frame.Begin, Size); 1527 1528 // Range Length 1529 const MCExpr *Range = 1530 makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0); 1531 emitAbsValue(Streamer, Range, 4); 1532 1533 // Compact Encoding 1534 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4); 1535 Streamer.emitIntValue(Encoding, Size); 1536 1537 // Personality Function 1538 Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr); 1539 if (!DwarfEHFrameOnly && Frame.Personality) 1540 Streamer.emitSymbolValue(Frame.Personality, Size); 1541 else 1542 Streamer.emitIntValue(0, Size); // No personality fn 1543 1544 // LSDA 1545 Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding); 1546 if (!DwarfEHFrameOnly && Frame.Lsda) 1547 Streamer.emitSymbolValue(Frame.Lsda, Size); 1548 else 1549 Streamer.emitIntValue(0, Size); // No LSDA 1550 } 1551 1552 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) { 1553 if (IsEH) 1554 return 1; 1555 switch (DwarfVersion) { 1556 case 2: 1557 return 1; 1558 case 3: 1559 return 3; 1560 case 4: 1561 case 5: 1562 return 4; 1563 } 1564 llvm_unreachable("Unknown version"); 1565 } 1566 1567 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) { 1568 MCContext &context = Streamer.getContext(); 1569 const MCRegisterInfo *MRI = context.getRegisterInfo(); 1570 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1571 1572 MCSymbol *sectionStart = context.createTempSymbol(); 1573 Streamer.emitLabel(sectionStart); 1574 1575 MCSymbol *sectionEnd = context.createTempSymbol(); 1576 1577 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat(); 1578 unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format); 1579 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format); 1580 bool IsDwarf64 = Format == dwarf::DWARF64; 1581 1582 if (IsDwarf64) 1583 // DWARF64 mark 1584 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64); 1585 1586 // Length 1587 const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart, 1588 *sectionEnd, UnitLengthBytes); 1589 emitAbsValue(Streamer, Length, OffsetSize); 1590 1591 // CIE ID 1592 uint64_t CIE_ID = 1593 IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID); 1594 Streamer.emitIntValue(CIE_ID, OffsetSize); 1595 1596 // Version 1597 uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion()); 1598 Streamer.emitInt8(CIEVersion); 1599 1600 if (IsEH) { 1601 SmallString<8> Augmentation; 1602 Augmentation += "z"; 1603 if (Frame.Personality) 1604 Augmentation += "P"; 1605 if (Frame.Lsda) 1606 Augmentation += "L"; 1607 Augmentation += "R"; 1608 if (Frame.IsSignalFrame) 1609 Augmentation += "S"; 1610 if (Frame.IsBKeyFrame) 1611 Augmentation += "B"; 1612 if (Frame.IsMTETaggedFrame) 1613 Augmentation += "G"; 1614 Streamer.emitBytes(Augmentation); 1615 } 1616 Streamer.emitInt8(0); 1617 1618 if (CIEVersion >= 4) { 1619 // Address Size 1620 Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize()); 1621 1622 // Segment Descriptor Size 1623 Streamer.emitInt8(0); 1624 } 1625 1626 // Code Alignment Factor 1627 Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment()); 1628 1629 // Data Alignment Factor 1630 Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer)); 1631 1632 // Return Address Register 1633 unsigned RAReg = Frame.RAReg; 1634 if (RAReg == static_cast<unsigned>(INT_MAX)) 1635 RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH); 1636 1637 if (CIEVersion == 1) { 1638 assert(RAReg <= 255 && 1639 "DWARF 2 encodes return_address_register in one byte"); 1640 Streamer.emitInt8(RAReg); 1641 } else { 1642 Streamer.emitULEB128IntValue(RAReg); 1643 } 1644 1645 // Augmentation Data Length (optional) 1646 unsigned augmentationLength = 0; 1647 if (IsEH) { 1648 if (Frame.Personality) { 1649 // Personality Encoding 1650 augmentationLength += 1; 1651 // Personality 1652 augmentationLength += 1653 getSizeForEncoding(Streamer, Frame.PersonalityEncoding); 1654 } 1655 if (Frame.Lsda) 1656 augmentationLength += 1; 1657 // Encoding of the FDE pointers 1658 augmentationLength += 1; 1659 1660 Streamer.emitULEB128IntValue(augmentationLength); 1661 1662 // Augmentation Data (optional) 1663 if (Frame.Personality) { 1664 // Personality Encoding 1665 emitEncodingByte(Streamer, Frame.PersonalityEncoding); 1666 // Personality 1667 EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding); 1668 } 1669 1670 if (Frame.Lsda) 1671 emitEncodingByte(Streamer, Frame.LsdaEncoding); 1672 1673 // Encoding of the FDE pointers 1674 emitEncodingByte(Streamer, MOFI->getFDEEncoding()); 1675 } 1676 1677 // Initial Instructions 1678 1679 const MCAsmInfo *MAI = context.getAsmInfo(); 1680 if (!Frame.IsSimple) { 1681 const std::vector<MCCFIInstruction> &Instructions = 1682 MAI->getInitialFrameState(); 1683 emitCFIInstructions(Instructions, nullptr); 1684 } 1685 1686 InitialCFAOffset = CFAOffset; 1687 1688 // Padding 1689 Streamer.emitValueToAlignment(IsEH ? 4 : MAI->getCodePointerSize()); 1690 1691 Streamer.emitLabel(sectionEnd); 1692 return *sectionStart; 1693 } 1694 1695 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart, 1696 const MCDwarfFrameInfo &frame, 1697 bool LastInSection, 1698 const MCSymbol &SectionStart) { 1699 MCContext &context = Streamer.getContext(); 1700 MCSymbol *fdeStart = context.createTempSymbol(); 1701 MCSymbol *fdeEnd = context.createTempSymbol(); 1702 const MCObjectFileInfo *MOFI = context.getObjectFileInfo(); 1703 1704 CFAOffset = InitialCFAOffset; 1705 1706 dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat(); 1707 unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format); 1708 1709 if (Format == dwarf::DWARF64) 1710 // DWARF64 mark 1711 Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64); 1712 1713 // Length 1714 const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0); 1715 emitAbsValue(Streamer, Length, OffsetSize); 1716 1717 Streamer.emitLabel(fdeStart); 1718 1719 // CIE Pointer 1720 const MCAsmInfo *asmInfo = context.getAsmInfo(); 1721 if (IsEH) { 1722 const MCExpr *offset = 1723 makeEndMinusStartExpr(context, cieStart, *fdeStart, 0); 1724 emitAbsValue(Streamer, offset, OffsetSize); 1725 } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) { 1726 const MCExpr *offset = 1727 makeEndMinusStartExpr(context, SectionStart, cieStart, 0); 1728 emitAbsValue(Streamer, offset, OffsetSize); 1729 } else { 1730 Streamer.emitSymbolValue(&cieStart, OffsetSize, 1731 asmInfo->needsDwarfSectionOffsetDirective()); 1732 } 1733 1734 // PC Begin 1735 unsigned PCEncoding = 1736 IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr; 1737 unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding); 1738 emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH); 1739 1740 // PC Range 1741 const MCExpr *Range = 1742 makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0); 1743 emitAbsValue(Streamer, Range, PCSize); 1744 1745 if (IsEH) { 1746 // Augmentation Data Length 1747 unsigned augmentationLength = 0; 1748 1749 if (frame.Lsda) 1750 augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding); 1751 1752 Streamer.emitULEB128IntValue(augmentationLength); 1753 1754 // Augmentation Data 1755 if (frame.Lsda) 1756 emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true); 1757 } 1758 1759 // Call Frame Instructions 1760 emitCFIInstructions(frame.Instructions, frame.Begin); 1761 1762 // Padding 1763 // The size of a .eh_frame section has to be a multiple of the alignment 1764 // since a null CIE is interpreted as the end. Old systems overaligned 1765 // .eh_frame, so we do too and account for it in the last FDE. 1766 unsigned Align = LastInSection ? asmInfo->getCodePointerSize() : PCSize; 1767 Streamer.emitValueToAlignment(Align); 1768 1769 Streamer.emitLabel(fdeEnd); 1770 } 1771 1772 namespace { 1773 1774 struct CIEKey { 1775 static const CIEKey getEmptyKey() { 1776 return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX), 1777 false); 1778 } 1779 1780 static const CIEKey getTombstoneKey() { 1781 return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX), 1782 false); 1783 } 1784 1785 CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding, 1786 unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple, 1787 unsigned RAReg, bool IsBKeyFrame) 1788 : Personality(Personality), PersonalityEncoding(PersonalityEncoding), 1789 LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame), 1790 IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame) {} 1791 1792 explicit CIEKey(const MCDwarfFrameInfo &Frame) 1793 : Personality(Frame.Personality), 1794 PersonalityEncoding(Frame.PersonalityEncoding), 1795 LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame), 1796 IsSimple(Frame.IsSimple), RAReg(Frame.RAReg), 1797 IsBKeyFrame(Frame.IsBKeyFrame) {} 1798 1799 StringRef PersonalityName() const { 1800 if (!Personality) 1801 return StringRef(); 1802 return Personality->getName(); 1803 } 1804 1805 bool operator<(const CIEKey &Other) const { 1806 return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding, 1807 IsSignalFrame, IsSimple, RAReg) < 1808 std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding, 1809 Other.LsdaEncoding, Other.IsSignalFrame, 1810 Other.IsSimple, Other.RAReg); 1811 } 1812 1813 const MCSymbol *Personality; 1814 unsigned PersonalityEncoding; 1815 unsigned LsdaEncoding; 1816 bool IsSignalFrame; 1817 bool IsSimple; 1818 unsigned RAReg; 1819 bool IsBKeyFrame; 1820 }; 1821 1822 } // end anonymous namespace 1823 1824 namespace llvm { 1825 1826 template <> struct DenseMapInfo<CIEKey> { 1827 static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); } 1828 static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); } 1829 1830 static unsigned getHashValue(const CIEKey &Key) { 1831 return static_cast<unsigned>(hash_combine( 1832 Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding, 1833 Key.IsSignalFrame, Key.IsSimple, Key.RAReg, Key.IsBKeyFrame)); 1834 } 1835 1836 static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) { 1837 return LHS.Personality == RHS.Personality && 1838 LHS.PersonalityEncoding == RHS.PersonalityEncoding && 1839 LHS.LsdaEncoding == RHS.LsdaEncoding && 1840 LHS.IsSignalFrame == RHS.IsSignalFrame && 1841 LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg && 1842 LHS.IsBKeyFrame == RHS.IsBKeyFrame; 1843 } 1844 }; 1845 1846 } // end namespace llvm 1847 1848 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB, 1849 bool IsEH) { 1850 MCContext &Context = Streamer.getContext(); 1851 const MCObjectFileInfo *MOFI = Context.getObjectFileInfo(); 1852 const MCAsmInfo *AsmInfo = Context.getAsmInfo(); 1853 FrameEmitterImpl Emitter(IsEH, Streamer); 1854 ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos(); 1855 1856 // Emit the compact unwind info if available. 1857 bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame(); 1858 if (IsEH && MOFI->getCompactUnwindSection()) { 1859 Streamer.generateCompactUnwindEncodings(MAB); 1860 bool SectionEmitted = false; 1861 for (const MCDwarfFrameInfo &Frame : FrameArray) { 1862 if (Frame.CompactUnwindEncoding == 0) continue; 1863 if (!SectionEmitted) { 1864 Streamer.switchSection(MOFI->getCompactUnwindSection()); 1865 Streamer.emitValueToAlignment(AsmInfo->getCodePointerSize()); 1866 SectionEmitted = true; 1867 } 1868 NeedsEHFrameSection |= 1869 Frame.CompactUnwindEncoding == 1870 MOFI->getCompactUnwindDwarfEHFrameOnly(); 1871 Emitter.EmitCompactUnwind(Frame); 1872 } 1873 } 1874 1875 if (!NeedsEHFrameSection) return; 1876 1877 MCSection &Section = 1878 IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection() 1879 : *MOFI->getDwarfFrameSection(); 1880 1881 Streamer.switchSection(&Section); 1882 MCSymbol *SectionStart = Context.createTempSymbol(); 1883 Streamer.emitLabel(SectionStart); 1884 1885 DenseMap<CIEKey, const MCSymbol *> CIEStarts; 1886 1887 const MCSymbol *DummyDebugKey = nullptr; 1888 bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind(); 1889 // Sort the FDEs by their corresponding CIE before we emit them. 1890 // This isn't technically necessary according to the DWARF standard, 1891 // but the Android libunwindstack rejects eh_frame sections where 1892 // an FDE refers to a CIE other than the closest previous CIE. 1893 std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end()); 1894 llvm::stable_sort(FrameArrayX, 1895 [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) { 1896 return CIEKey(X) < CIEKey(Y); 1897 }); 1898 for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) { 1899 const MCDwarfFrameInfo &Frame = *I; 1900 ++I; 1901 if (CanOmitDwarf && Frame.CompactUnwindEncoding != 1902 MOFI->getCompactUnwindDwarfEHFrameOnly()) 1903 // Don't generate an EH frame if we don't need one. I.e., it's taken care 1904 // of by the compact unwind encoding. 1905 continue; 1906 1907 CIEKey Key(Frame); 1908 const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey; 1909 if (!CIEStart) 1910 CIEStart = &Emitter.EmitCIE(Frame); 1911 1912 Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart); 1913 } 1914 } 1915 1916 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer, 1917 uint64_t AddrDelta) { 1918 MCContext &Context = Streamer.getContext(); 1919 SmallString<256> Tmp; 1920 raw_svector_ostream OS(Tmp); 1921 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS); 1922 Streamer.emitBytes(OS.str()); 1923 } 1924 1925 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context, 1926 uint64_t AddrDelta, 1927 raw_ostream &OS) { 1928 // Scale the address delta by the minimum instruction length. 1929 AddrDelta = ScaleAddrDelta(Context, AddrDelta); 1930 if (AddrDelta == 0) 1931 return; 1932 1933 support::endianness E = 1934 Context.getAsmInfo()->isLittleEndian() ? support::little : support::big; 1935 1936 if (isUIntN(6, AddrDelta)) { 1937 uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta; 1938 OS << Opcode; 1939 } else if (isUInt<8>(AddrDelta)) { 1940 OS << uint8_t(dwarf::DW_CFA_advance_loc1); 1941 OS << uint8_t(AddrDelta); 1942 } else if (isUInt<16>(AddrDelta)) { 1943 OS << uint8_t(dwarf::DW_CFA_advance_loc2); 1944 support::endian::write<uint16_t>(OS, AddrDelta, E); 1945 } else { 1946 assert(isUInt<32>(AddrDelta)); 1947 OS << uint8_t(dwarf::DW_CFA_advance_loc4); 1948 support::endian::write<uint32_t>(OS, AddrDelta, E); 1949 } 1950 } 1951