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