Path: blob/main/contrib/llvm-project/llvm/lib/MC/MCDwarf.cpp
35233 views
//===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/MC/MCDwarf.h"9#include "llvm/ADT/ArrayRef.h"10#include "llvm/ADT/DenseMap.h"11#include "llvm/ADT/Hashing.h"12#include "llvm/ADT/STLExtras.h"13#include "llvm/ADT/ScopeExit.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>4445using namespace llvm;4647MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {48MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start");49MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end");50auto DwarfFormat = S.getContext().getDwarfFormat();51if (DwarfFormat == dwarf::DWARF64) {52S.AddComment("DWARF64 mark");53S.emitInt32(dwarf::DW_LENGTH_DWARF64);54}55S.AddComment("Length");56S.emitAbsoluteSymbolDiff(End, Start,57dwarf::getDwarfOffsetByteSize(DwarfFormat));58S.emitLabel(Start);59S.AddComment("Version");60S.emitInt16(S.getContext().getDwarfVersion());61S.AddComment("Address size");62S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());63S.AddComment("Segment selector size");64S.emitInt8(0);65return End;66}6768static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {69unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();70if (MinInsnLength == 1)71return AddrDelta;72if (AddrDelta % MinInsnLength != 0) {73// TODO: report this error, but really only once.74;75}76return AddrDelta / MinInsnLength;77}7879MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) {80UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();81if (UseRelocs) {82MCSection *DwarfLineStrSection =83Ctx.getObjectFileInfo()->getDwarfLineStrSection();84assert(DwarfLineStrSection && "DwarfLineStrSection must not be NULL");85LineStrLabel = DwarfLineStrSection->getBeginSymbol();86}87}8889//90// This is called when an instruction is assembled into the specified section91// and if there is information from the last .loc directive that has yet to have92// a line entry made for it is made.93//94void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) {95if (!MCOS->getContext().getDwarfLocSeen())96return;9798// Create a symbol at in the current section for use in the line entry.99MCSymbol *LineSym = MCOS->getContext().createTempSymbol();100// Set the value of the symbol to use for the MCDwarfLineEntry.101MCOS->emitLabel(LineSym);102103// Get the current .loc info saved in the context.104const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();105106// Create a (local) line entry with the symbol and the current .loc info.107MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);108109// clear DwarfLocSeen saying the current .loc info is now used.110MCOS->getContext().clearDwarfLocSeen();111112// Add the line entry to this section's entries.113MCOS->getContext()114.getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())115.getMCLineSections()116.addLineEntry(LineEntry, Section);117}118119//120// This helper routine returns an expression of End - Start - IntVal .121//122static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,123const MCSymbol &Start,124const MCSymbol &End,125int IntVal) {126MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;127const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);128const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);129const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);130const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);131const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);132return Res3;133}134135//136// This helper routine returns an expression of Start + IntVal .137//138static inline const MCExpr *139makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {140MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;141const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);142const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);143const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);144return Res;145}146147void MCLineSection::addEndEntry(MCSymbol *EndLabel) {148auto *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 in152// place instead of adding a line entry if the target has153// usesDwarfFileAndLocDirectives.154// (2) MCObjectStreamer - if a function has incomplete debug info where155// instructions don't have DILocations, the line entries are missing.156auto I = MCLineDivisions.find(Sec);157if (I != MCLineDivisions.end()) {158auto &Entries = I->second;159auto EndEntry = Entries.back();160EndEntry.setEndLabel(EndLabel);161Entries.push_back(EndEntry);162}163}164165//166// This emits the Dwarf line table for the specified section from the entries167// in the LineSection.168//169void MCDwarfLineTable::emitOne(170MCStreamer *MCOS, MCSection *Section,171const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {172173unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator;174MCSymbol *LastLabel;175auto init = [&]() {176FileNum = 1;177LastLine = 1;178Column = 0;179Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;180Isa = 0;181Discriminator = 0;182LastLabel = nullptr;183};184init();185186// Loop through each MCDwarfLineEntry and encode the dwarf line number table.187bool EndEntryEmitted = false;188for (const MCDwarfLineEntry &LineEntry : LineEntries) {189MCSymbol *Label = LineEntry.getLabel();190const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();191if (LineEntry.IsEndEntry) {192MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label,193asmInfo->getCodePointerSize());194init();195EndEntryEmitted = true;196continue;197}198199int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;200201if (FileNum != LineEntry.getFileNum()) {202FileNum = LineEntry.getFileNum();203MCOS->emitInt8(dwarf::DW_LNS_set_file);204MCOS->emitULEB128IntValue(FileNum);205}206if (Column != LineEntry.getColumn()) {207Column = LineEntry.getColumn();208MCOS->emitInt8(dwarf::DW_LNS_set_column);209MCOS->emitULEB128IntValue(Column);210}211if (Discriminator != LineEntry.getDiscriminator() &&212MCOS->getContext().getDwarfVersion() >= 4) {213Discriminator = LineEntry.getDiscriminator();214unsigned Size = getULEB128Size(Discriminator);215MCOS->emitInt8(dwarf::DW_LNS_extended_op);216MCOS->emitULEB128IntValue(Size + 1);217MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);218MCOS->emitULEB128IntValue(Discriminator);219}220if (Isa != LineEntry.getIsa()) {221Isa = LineEntry.getIsa();222MCOS->emitInt8(dwarf::DW_LNS_set_isa);223MCOS->emitULEB128IntValue(Isa);224}225if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {226Flags = LineEntry.getFlags();227MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);228}229if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)230MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);231if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)232MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);233if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)234MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);235236// At this point we want to emit/create the sequence to encode the delta in237// line numbers and the increment of the address from the previous Label238// and the current Label.239MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,240asmInfo->getCodePointerSize());241242Discriminator = 0;243LastLine = LineEntry.getLine();244LastLabel = Label;245}246247// Generate DWARF line end entry.248// We do not need this for DwarfDebug that explicitly terminates the line249// table using ranges whenever CU or section changes. However, the MC path250// does not track ranges nor terminate the line table. In that case,251// conservatively use the section end symbol to end the line table.252if (!EndEntryEmitted)253MCOS->emitDwarfLineEndEntry(Section, LastLabel);254}255256//257// This emits the Dwarf file and the line tables.258//259void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) {260MCContext &context = MCOS->getContext();261262auto &LineTables = context.getMCDwarfLineTables();263264// Bail out early so we don't switch to the debug_line section needlessly and265// in doing so create an unnecessary (if empty) section.266if (LineTables.empty())267return;268269// In a v5 non-split line table, put the strings in a separate section.270std::optional<MCDwarfLineStr> LineStr;271if (context.getDwarfVersion() >= 5)272LineStr.emplace(context);273274// Switch to the section where the table will be emitted into.275MCOS->switchSection(context.getObjectFileInfo()->getDwarfLineSection());276277// Handle the rest of the Compile Units.278for (const auto &CUIDTablePair : LineTables) {279CUIDTablePair.second.emitCU(MCOS, Params, LineStr);280}281282if (LineStr)283LineStr->emitSection(MCOS);284}285286void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,287MCSection *Section) const {288if (!HasSplitLineTable)289return;290std::optional<MCDwarfLineStr> NoLineStr(std::nullopt);291MCOS.switchSection(Section);292MCOS.emitLabel(Header.Emit(&MCOS, Params, std::nullopt, NoLineStr).second);293}294295std::pair<MCSymbol *, MCSymbol *>296MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,297std::optional<MCDwarfLineStr> &LineStr) const {298static const char StandardOpcodeLengths[] = {2990, // length of DW_LNS_copy3001, // length of DW_LNS_advance_pc3011, // length of DW_LNS_advance_line3021, // length of DW_LNS_set_file3031, // length of DW_LNS_set_column3040, // length of DW_LNS_negate_stmt3050, // length of DW_LNS_set_basic_block3060, // length of DW_LNS_const_add_pc3071, // length of DW_LNS_fixed_advance_pc3080, // length of DW_LNS_set_prologue_end3090, // length of DW_LNS_set_epilogue_begin3101 // DW_LNS_set_isa311};312assert(std::size(StandardOpcodeLengths) >=313(Params.DWARF2LineOpcodeBase - 1U));314return Emit(MCOS, Params,315ArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),316LineStr);317}318319static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {320MCContext &Context = OS.getContext();321assert(!isa<MCSymbolRefExpr>(Expr));322if (Context.getAsmInfo()->hasAggressiveSymbolFolding())323return Expr;324325MCSymbol *ABS = Context.createTempSymbol();326OS.emitAssignment(ABS, Expr);327return MCSymbolRefExpr::create(ABS, Context);328}329330static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {331const MCExpr *ABS = forceExpAbs(OS, Value);332OS.emitValue(ABS, Size);333}334335void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {336// Switch to the .debug_line_str section.337MCOS->switchSection(338MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());339SmallString<0> Data = getFinalizedData();340MCOS->emitBinaryData(Data.str());341}342343SmallString<0> MCDwarfLineStr::getFinalizedData() {344// Emit the strings without perturbing the offsets we used.345if (!LineStrings.isFinalized())346LineStrings.finalizeInOrder();347SmallString<0> Data;348Data.resize(LineStrings.getSize());349LineStrings.write((uint8_t *)Data.data());350return Data;351}352353size_t MCDwarfLineStr::addString(StringRef Path) {354return LineStrings.add(Path);355}356357void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {358int RefSize =359dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());360size_t Offset = addString(Path);361if (UseRelocs) {362MCContext &Ctx = MCOS->getContext();363if (Ctx.getAsmInfo()->needsDwarfSectionOffsetDirective()) {364MCOS->emitCOFFSecRel32(LineStrLabel, Offset);365} else {366MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset),367RefSize);368}369} else370MCOS->emitIntValue(Offset, RefSize);371}372373void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {374// First the directory table.375for (auto &Dir : MCDwarfDirs) {376MCOS->emitBytes(Dir); // The DirectoryName, and...377MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.378}379MCOS->emitInt8(0); // Terminate the directory list.380381// Second the file table.382for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {383assert(!MCDwarfFiles[i].Name.empty());384MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and...385MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.386MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number.387MCOS->emitInt8(0); // Last modification timestamp (always 0).388MCOS->emitInt8(0); // File size (always 0).389}390MCOS->emitInt8(0); // Terminate the file list.391}392393static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,394bool EmitMD5, bool HasAnySource,395std::optional<MCDwarfLineStr> &LineStr) {396assert(!DwarfFile.Name.empty());397if (LineStr)398LineStr->emitRef(MCOS, DwarfFile.Name);399else {400MCOS->emitBytes(DwarfFile.Name); // FileName and...401MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.402}403MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number.404if (EmitMD5) {405const MD5::MD5Result &Cksum = *DwarfFile.Checksum;406MCOS->emitBinaryData(407StringRef(reinterpret_cast<const char *>(Cksum.data()), Cksum.size()));408}409if (HasAnySource) {410if (LineStr)411LineStr->emitRef(MCOS, DwarfFile.Source.value_or(StringRef()));412else {413MCOS->emitBytes(DwarfFile.Source.value_or(StringRef())); // Source and...414MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.415}416}417}418419void MCDwarfLineTableHeader::emitV5FileDirTables(420MCStreamer *MCOS, std::optional<MCDwarfLineStr> &LineStr) const {421// The directory format, which is just a list of the directory paths. In a422// non-split object, these are references to .debug_line_str; in a split423// object, they are inline strings.424MCOS->emitInt8(1);425MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);426MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp427: dwarf::DW_FORM_string);428MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);429// Try not to emit an empty compilation directory.430SmallString<256> Dir;431StringRef CompDir = MCOS->getContext().getCompilationDir();432if (!CompilationDir.empty()) {433Dir = CompilationDir;434MCOS->getContext().remapDebugPath(Dir);435CompDir = Dir.str();436if (LineStr)437CompDir = LineStr->getSaver().save(CompDir);438}439if (LineStr) {440// Record path strings, emit references here.441LineStr->emitRef(MCOS, CompDir);442for (const auto &Dir : MCDwarfDirs)443LineStr->emitRef(MCOS, Dir);444} else {445// The list of directory paths. Compilation directory comes first.446MCOS->emitBytes(CompDir);447MCOS->emitBytes(StringRef("\0", 1));448for (const auto &Dir : MCDwarfDirs) {449MCOS->emitBytes(Dir); // The DirectoryName, and...450MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.451}452}453454// The file format, which is the inline null-terminated filename and a455// directory index. We don't track file size/timestamp so don't emit them456// in the v5 table. Emit MD5 checksums and source if we have them.457uint64_t Entries = 2;458if (HasAllMD5)459Entries += 1;460if (HasAnySource)461Entries += 1;462MCOS->emitInt8(Entries);463MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);464MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp465: dwarf::DW_FORM_string);466MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);467MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);468if (HasAllMD5) {469MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);470MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);471}472if (HasAnySource) {473MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);474MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp475: dwarf::DW_FORM_string);476}477// Then the counted list of files. The root file is file #0, then emit the478// files as provide by .file directives.479// MCDwarfFiles has an unused element [0] so use size() not size()+1.480// But sometimes MCDwarfFiles is empty, in which case we still emit one file.481MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());482// To accommodate assembler source written for DWARF v4 but trying to emit483// v5: If we didn't see a root file explicitly, replicate file #1.484assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&485"No root file and no .file directives");486emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,487HasAllMD5, HasAnySource, LineStr);488for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)489emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasAnySource, LineStr);490}491492std::pair<MCSymbol *, MCSymbol *>493MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,494ArrayRef<char> StandardOpcodeLengths,495std::optional<MCDwarfLineStr> &LineStr) const {496MCContext &context = MCOS->getContext();497498// Create a symbol at the beginning of the line table.499MCSymbol *LineStartSym = Label;500if (!LineStartSym)501LineStartSym = context.createTempSymbol();502503// Set the value of the symbol, as we are at the start of the line table.504MCOS->emitDwarfLineStartLabel(LineStartSym);505506unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());507508MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length");509510// Next 2 bytes is the Version.511unsigned LineTableVersion = context.getDwarfVersion();512MCOS->emitInt16(LineTableVersion);513514// In v5, we get address info next.515if (LineTableVersion >= 5) {516MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());517MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges.518}519520// Create symbols for the start/end of the prologue.521MCSymbol *ProStartSym = context.createTempSymbol("prologue_start");522MCSymbol *ProEndSym = context.createTempSymbol("prologue_end");523524// Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is525// actually the length from after the length word, to the end of the prologue.526MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize);527528MCOS->emitLabel(ProStartSym);529530// Parameters of the state machine, are next.531MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());532// maximum_operations_per_instruction533// For non-VLIW architectures this field is always 1.534// FIXME: VLIW architectures need to update this field accordingly.535if (LineTableVersion >= 4)536MCOS->emitInt8(1);537MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);538MCOS->emitInt8(Params.DWARF2LineBase);539MCOS->emitInt8(Params.DWARF2LineRange);540MCOS->emitInt8(StandardOpcodeLengths.size() + 1);541542// Standard opcode lengths543for (char Length : StandardOpcodeLengths)544MCOS->emitInt8(Length);545546// Put out the directory and file tables. The formats vary depending on547// the version.548if (LineTableVersion >= 5)549emitV5FileDirTables(MCOS, LineStr);550else551emitV2FileDirTables(MCOS);552553// This is the end of the prologue, so set the value of the symbol at the554// end of the prologue (that was used in a previous expression).555MCOS->emitLabel(ProEndSym);556557return std::make_pair(LineStartSym, LineEndSym);558}559560void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,561std::optional<MCDwarfLineStr> &LineStr) const {562MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;563564// Put out the line tables.565for (const auto &LineSec : MCLineSections.getMCLineEntries())566emitOne(MCOS, LineSec.first, LineSec.second);567568// This is the end of the section, so set the value of the symbol at the end569// of this section (that was used in a previous expression).570MCOS->emitLabel(LineEndSym);571}572573Expected<unsigned>574MCDwarfLineTable::tryGetFile(StringRef &Directory, StringRef &FileName,575std::optional<MD5::MD5Result> Checksum,576std::optional<StringRef> Source,577uint16_t DwarfVersion, unsigned FileNumber) {578return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,579FileNumber);580}581582static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,583StringRef &FileName,584std::optional<MD5::MD5Result> Checksum) {585if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)586return false;587return RootFile.Checksum == Checksum;588}589590Expected<unsigned>591MCDwarfLineTableHeader::tryGetFile(StringRef &Directory, StringRef &FileName,592std::optional<MD5::MD5Result> Checksum,593std::optional<StringRef> Source,594uint16_t DwarfVersion, unsigned FileNumber) {595if (Directory == CompilationDir)596Directory = "";597if (FileName.empty()) {598FileName = "<stdin>";599Directory = "";600}601assert(!FileName.empty());602// Keep track of whether any or all files have an MD5 checksum.603// If any files have embedded source, they all must.604if (MCDwarfFiles.empty()) {605trackMD5Usage(Checksum.has_value());606HasAnySource |= Source.has_value();607}608if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum))609return 0;610if (FileNumber == 0) {611// File numbers start with 1 and/or after any file numbers612// allocated by inline-assembler .file directives.613FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();614SmallString<256> Buffer;615auto IterBool = SourceIdMap.insert(616std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),617FileNumber));618if (!IterBool.second)619return IterBool.first->second;620}621// Make space for this FileNumber in the MCDwarfFiles vector if needed.622if (FileNumber >= MCDwarfFiles.size())623MCDwarfFiles.resize(FileNumber + 1);624625// Get the new MCDwarfFile slot for this FileNumber.626MCDwarfFile &File = MCDwarfFiles[FileNumber];627628// It is an error to see the same number more than once.629if (!File.Name.empty())630return make_error<StringError>("file number already allocated",631inconvertibleErrorCode());632633if (Directory.empty()) {634// Separate the directory part from the basename of the FileName.635StringRef tFileName = sys::path::filename(FileName);636if (!tFileName.empty()) {637Directory = sys::path::parent_path(FileName);638if (!Directory.empty())639FileName = tFileName;640}641}642643// Find or make an entry in the MCDwarfDirs vector for this Directory.644// Capture directory name.645unsigned DirIndex;646if (Directory.empty()) {647// For FileNames with no directories a DirIndex of 0 is used.648DirIndex = 0;649} else {650DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();651if (DirIndex >= MCDwarfDirs.size())652MCDwarfDirs.push_back(std::string(Directory));653// The DirIndex is one based, as DirIndex of 0 is used for FileNames with654// no directories. MCDwarfDirs[] is unlike MCDwarfFiles[] in that the655// directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames656// are stored at MCDwarfFiles[FileNumber].Name .657DirIndex++;658}659660File.Name = std::string(FileName);661File.DirIndex = DirIndex;662File.Checksum = Checksum;663trackMD5Usage(Checksum.has_value());664File.Source = Source;665if (Source.has_value())666HasAnySource = true;667668// return the allocated FileNumber.669return FileNumber;670}671672/// Utility function to emit the encoding to a streamer.673void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,674int64_t LineDelta, uint64_t AddrDelta) {675MCContext &Context = MCOS->getContext();676SmallString<256> Tmp;677MCDwarfLineAddr::encode(Context, Params, LineDelta, AddrDelta, Tmp);678MCOS->emitBytes(Tmp);679}680681/// Given a special op, return the address skip amount (in units of682/// DWARF2_LINE_MIN_INSN_LENGTH).683static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {684return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;685}686687/// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.688void MCDwarfLineAddr::encode(MCContext &Context, MCDwarfLineTableParams Params,689int64_t LineDelta, uint64_t AddrDelta,690SmallVectorImpl<char> &Out) {691uint8_t Buf[16];692uint64_t Temp, Opcode;693bool NeedCopy = false;694695// The maximum address skip amount that can be encoded with a special op.696uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);697698// Scale the address delta by the minimum instruction length.699AddrDelta = ScaleAddrDelta(Context, AddrDelta);700701// A LineDelta of INT64_MAX is a signal that this is actually a702// DW_LNE_end_sequence. We cannot use special opcodes here, since we want the703// end_sequence to emit the matrix entry.704if (LineDelta == INT64_MAX) {705if (AddrDelta == MaxSpecialAddrDelta)706Out.push_back(dwarf::DW_LNS_const_add_pc);707else if (AddrDelta) {708Out.push_back(dwarf::DW_LNS_advance_pc);709Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));710}711Out.push_back(dwarf::DW_LNS_extended_op);712Out.push_back(1);713Out.push_back(dwarf::DW_LNE_end_sequence);714return;715}716717// Bias the line delta by the base.718Temp = LineDelta - Params.DWARF2LineBase;719720// If the line increment is out of range of a special opcode, we must encode721// it with DW_LNS_advance_line.722if (Temp >= Params.DWARF2LineRange ||723Temp + Params.DWARF2LineOpcodeBase > 255) {724Out.push_back(dwarf::DW_LNS_advance_line);725Out.append(Buf, Buf + encodeSLEB128(LineDelta, Buf));726727LineDelta = 0;728Temp = 0 - Params.DWARF2LineBase;729NeedCopy = true;730}731732// Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.733if (LineDelta == 0 && AddrDelta == 0) {734Out.push_back(dwarf::DW_LNS_copy);735return;736}737738// Bias the opcode by the special opcode base.739Temp += Params.DWARF2LineOpcodeBase;740741// Avoid overflow when addr_delta is large.742if (AddrDelta < 256 + MaxSpecialAddrDelta) {743// Try using a special opcode.744Opcode = Temp + AddrDelta * Params.DWARF2LineRange;745if (Opcode <= 255) {746Out.push_back(Opcode);747return;748}749750// Try using DW_LNS_const_add_pc followed by special op.751Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;752if (Opcode <= 255) {753Out.push_back(dwarf::DW_LNS_const_add_pc);754Out.push_back(Opcode);755return;756}757}758759// Otherwise use DW_LNS_advance_pc.760Out.push_back(dwarf::DW_LNS_advance_pc);761Out.append(Buf, Buf + encodeULEB128(AddrDelta, Buf));762763if (NeedCopy)764Out.push_back(dwarf::DW_LNS_copy);765else {766assert(Temp <= 255 && "Buggy special opcode encoding.");767Out.push_back(Temp);768}769}770771// Utility function to write a tuple for .debug_abbrev.772static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {773MCOS->emitULEB128IntValue(Name);774MCOS->emitULEB128IntValue(Form);775}776777// When generating dwarf for assembly source files this emits778// the data for .debug_abbrev section which contains three DIEs.779static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {780MCContext &context = MCOS->getContext();781MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());782783// DW_TAG_compile_unit DIE abbrev (1).784MCOS->emitULEB128IntValue(1);785MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);786MCOS->emitInt8(dwarf::DW_CHILDREN_yes);787dwarf::Form SecOffsetForm =788context.getDwarfVersion() >= 4789? dwarf::DW_FORM_sec_offset790: (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8791: dwarf::DW_FORM_data4);792EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);793if (context.getGenDwarfSectionSyms().size() > 1 &&794context.getDwarfVersion() >= 3) {795EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);796} else {797EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);798EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);799}800EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);801if (!context.getCompilationDir().empty())802EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);803StringRef DwarfDebugFlags = context.getDwarfDebugFlags();804if (!DwarfDebugFlags.empty())805EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);806EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);807EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);808EmitAbbrev(MCOS, 0, 0);809810// DW_TAG_label DIE abbrev (2).811MCOS->emitULEB128IntValue(2);812MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);813MCOS->emitInt8(dwarf::DW_CHILDREN_no);814EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);815EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);816EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);817EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);818EmitAbbrev(MCOS, 0, 0);819820// Terminate the abbreviations for this compilation unit.821MCOS->emitInt8(0);822}823824// When generating dwarf for assembly source files this emits the data for825// .debug_aranges section. This section contains a header and a table of pairs826// of PointerSize'ed values for the address and size of section(s) with line827// table entries.828static void EmitGenDwarfAranges(MCStreamer *MCOS,829const MCSymbol *InfoSectionSymbol) {830MCContext &context = MCOS->getContext();831832auto &Sections = context.getGenDwarfSectionSyms();833834MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());835836unsigned UnitLengthBytes =837dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());838unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());839840// This will be the length of the .debug_aranges section, first account for841// the size of each item in the header (see below where we emit these items).842int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;843844// Figure the padding after the header before the table of address and size845// pairs who's values are PointerSize'ed.846const MCAsmInfo *asmInfo = context.getAsmInfo();847int AddrSize = asmInfo->getCodePointerSize();848int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));849if (Pad == 2 * AddrSize)850Pad = 0;851Length += Pad;852853// Add the size of the pair of PointerSize'ed values for the address and size854// of each section we have in the table.855Length += 2 * AddrSize * Sections.size();856// And the pair of terminating zeros.857Length += 2 * AddrSize;858859// Emit the header for this section.860if (context.getDwarfFormat() == dwarf::DWARF64)861// The DWARF64 mark.862MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);863// The 4 (8 for DWARF64) byte length not including the length of the unit864// length field itself.865MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);866// The 2 byte version, which is 2.867MCOS->emitInt16(2);868// The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info869// from the start of the .debug_info.870if (InfoSectionSymbol)871MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,872asmInfo->needsDwarfSectionOffsetDirective());873else874MCOS->emitIntValue(0, OffsetSize);875// The 1 byte size of an address.876MCOS->emitInt8(AddrSize);877// The 1 byte size of a segment descriptor, we use a value of zero.878MCOS->emitInt8(0);879// Align the header with the padding if needed, before we put out the table.880for(int i = 0; i < Pad; i++)881MCOS->emitInt8(0);882883// Now emit the table of pairs of PointerSize'ed values for the section884// addresses and sizes.885for (MCSection *Sec : Sections) {886const MCSymbol *StartSymbol = Sec->getBeginSymbol();887MCSymbol *EndSymbol = Sec->getEndSymbol(context);888assert(StartSymbol && "StartSymbol must not be NULL");889assert(EndSymbol && "EndSymbol must not be NULL");890891const MCExpr *Addr = MCSymbolRefExpr::create(892StartSymbol, MCSymbolRefExpr::VK_None, context);893const MCExpr *Size =894makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);895MCOS->emitValue(Addr, AddrSize);896emitAbsValue(*MCOS, Size, AddrSize);897}898899// And finally the pair of terminating zeros.900MCOS->emitIntValue(0, AddrSize);901MCOS->emitIntValue(0, AddrSize);902}903904// When generating dwarf for assembly source files this emits the data for905// .debug_info section which contains three parts. The header, the compile_unit906// DIE and a list of label DIEs.907static void EmitGenDwarfInfo(MCStreamer *MCOS,908const MCSymbol *AbbrevSectionSymbol,909const MCSymbol *LineSectionSymbol,910const MCSymbol *RangesSymbol) {911MCContext &context = MCOS->getContext();912913MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());914915// Create a symbol at the start and end of this section used in here for the916// expression to calculate the length in the header.917MCSymbol *InfoStart = context.createTempSymbol();918MCOS->emitLabel(InfoStart);919MCSymbol *InfoEnd = context.createTempSymbol();920921// First part: the header.922923unsigned UnitLengthBytes =924dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());925unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());926927if (context.getDwarfFormat() == dwarf::DWARF64)928// Emit DWARF64 mark.929MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);930931// The 4 (8 for DWARF64) byte total length of the information for this932// compilation unit, not including the unit length field itself.933const MCExpr *Length =934makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);935emitAbsValue(*MCOS, Length, OffsetSize);936937// The 2 byte DWARF version.938MCOS->emitInt16(context.getDwarfVersion());939940// The DWARF v5 header has unit type, address size, abbrev offset.941// Earlier versions have abbrev offset, address size.942const MCAsmInfo &AsmInfo = *context.getAsmInfo();943int AddrSize = AsmInfo.getCodePointerSize();944if (context.getDwarfVersion() >= 5) {945MCOS->emitInt8(dwarf::DW_UT_compile);946MCOS->emitInt8(AddrSize);947}948// The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of949// the .debug_abbrev.950if (AbbrevSectionSymbol)951MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,952AsmInfo.needsDwarfSectionOffsetDirective());953else954// Since the abbrevs are at the start of the section, the offset is zero.955MCOS->emitIntValue(0, OffsetSize);956if (context.getDwarfVersion() <= 4)957MCOS->emitInt8(AddrSize);958959// Second part: the compile_unit DIE.960961// The DW_TAG_compile_unit DIE abbrev (1).962MCOS->emitULEB128IntValue(1);963964// DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the965// .debug_line section.966if (LineSectionSymbol)967MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,968AsmInfo.needsDwarfSectionOffsetDirective());969else970// The line table is at the start of the section, so the offset is zero.971MCOS->emitIntValue(0, OffsetSize);972973if (RangesSymbol) {974// There are multiple sections containing code, so we must use975// .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the976// start of the .debug_ranges/.debug_rnglists.977MCOS->emitSymbolValue(RangesSymbol, OffsetSize);978} else {979// If we only have one non-empty code section, we can use the simpler980// AT_low_pc and AT_high_pc attributes.981982// Find the first (and only) non-empty text section983auto &Sections = context.getGenDwarfSectionSyms();984const auto TextSection = Sections.begin();985assert(TextSection != Sections.end() && "No text section found");986987MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();988MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);989assert(StartSymbol && "StartSymbol must not be NULL");990assert(EndSymbol && "EndSymbol must not be NULL");991992// AT_low_pc, the first address of the default .text section.993const MCExpr *Start = MCSymbolRefExpr::create(994StartSymbol, MCSymbolRefExpr::VK_None, context);995MCOS->emitValue(Start, AddrSize);996997// AT_high_pc, the last address of the default .text section.998const MCExpr *End = MCSymbolRefExpr::create(999EndSymbol, MCSymbolRefExpr::VK_None, context);1000MCOS->emitValue(End, AddrSize);1001}10021003// AT_name, the name of the source file. Reconstruct from the first directory1004// and file table entries.1005const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();1006if (MCDwarfDirs.size() > 0) {1007MCOS->emitBytes(MCDwarfDirs[0]);1008MCOS->emitBytes(sys::path::get_separator());1009}1010const 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.1013assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);1014const MCDwarfFile &RootFile =1015MCDwarfFiles.empty()1016? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()1017: MCDwarfFiles[1];1018MCOS->emitBytes(RootFile.Name);1019MCOS->emitInt8(0); // NULL byte to terminate the string.10201021// AT_comp_dir, the working directory the assembly was done in.1022if (!context.getCompilationDir().empty()) {1023MCOS->emitBytes(context.getCompilationDir());1024MCOS->emitInt8(0); // NULL byte to terminate the string.1025}10261027// AT_APPLE_flags, the command line arguments of the assembler tool.1028StringRef DwarfDebugFlags = context.getDwarfDebugFlags();1029if (!DwarfDebugFlags.empty()){1030MCOS->emitBytes(DwarfDebugFlags);1031MCOS->emitInt8(0); // NULL byte to terminate the string.1032}10331034// AT_producer, the version of the assembler tool.1035StringRef DwarfDebugProducer = context.getDwarfDebugProducer();1036if (!DwarfDebugProducer.empty())1037MCOS->emitBytes(DwarfDebugProducer);1038else1039MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));1040MCOS->emitInt8(0); // NULL byte to terminate the string.10411042// AT_language, a 4 byte value. We use DW_LANG_Mips_Assembler as the dwarf21043// draft has no standard code for assembler.1044MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);10451046// Third part: the list of label DIEs.10471048// Loop on saved info for dwarf labels and create the DIEs for them.1049const std::vector<MCGenDwarfLabelEntry> &Entries =1050MCOS->getContext().getMCGenDwarfLabelEntries();1051for (const auto &Entry : Entries) {1052// The DW_TAG_label DIE abbrev (2).1053MCOS->emitULEB128IntValue(2);10541055// AT_name, of the label without any leading underbar.1056MCOS->emitBytes(Entry.getName());1057MCOS->emitInt8(0); // NULL byte to terminate the string.10581059// AT_decl_file, index into the file table.1060MCOS->emitInt32(Entry.getFileNumber());10611062// AT_decl_line, source line number.1063MCOS->emitInt32(Entry.getLineNumber());10641065// AT_low_pc, start address of the label.1066const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),1067MCSymbolRefExpr::VK_None, context);1068MCOS->emitValue(AT_low_pc, AddrSize);1069}10701071// Add the NULL DIE terminating the Compile Unit DIE's.1072MCOS->emitInt8(0);10731074// Now set the value of the symbol at the end of the info section.1075MCOS->emitLabel(InfoEnd);1076}10771078// When generating dwarf for assembly source files this emits the data for1079// .debug_ranges section. We only emit one range list, which spans all of the1080// executable sections of this file.1081static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {1082MCContext &context = MCOS->getContext();1083auto &Sections = context.getGenDwarfSectionSyms();10841085const MCAsmInfo *AsmInfo = context.getAsmInfo();1086int AddrSize = AsmInfo->getCodePointerSize();1087MCSymbol *RangesSymbol;10881089if (MCOS->getContext().getDwarfVersion() >= 5) {1090MCOS->switchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());1091MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);1092MCOS->AddComment("Offset entry count");1093MCOS->emitInt32(0);1094RangesSymbol = context.createTempSymbol("debug_rnglist0_start");1095MCOS->emitLabel(RangesSymbol);1096for (MCSection *Sec : Sections) {1097const MCSymbol *StartSymbol = Sec->getBeginSymbol();1098const MCSymbol *EndSymbol = Sec->getEndSymbol(context);1099const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(1100StartSymbol, MCSymbolRefExpr::VK_None, context);1101const MCExpr *SectionSize =1102makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);1103MCOS->emitInt8(dwarf::DW_RLE_start_length);1104MCOS->emitValue(SectionStartAddr, AddrSize);1105MCOS->emitULEB128Value(SectionSize);1106}1107MCOS->emitInt8(dwarf::DW_RLE_end_of_list);1108MCOS->emitLabel(EndSymbol);1109} else {1110MCOS->switchSection(context.getObjectFileInfo()->getDwarfRangesSection());1111RangesSymbol = context.createTempSymbol("debug_ranges_start");1112MCOS->emitLabel(RangesSymbol);1113for (MCSection *Sec : Sections) {1114const MCSymbol *StartSymbol = Sec->getBeginSymbol();1115const MCSymbol *EndSymbol = Sec->getEndSymbol(context);11161117// Emit a base address selection entry for the section start.1118const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(1119StartSymbol, MCSymbolRefExpr::VK_None, context);1120MCOS->emitFill(AddrSize, 0xFF);1121MCOS->emitValue(SectionStartAddr, AddrSize);11221123// Emit a range list entry spanning this section.1124const MCExpr *SectionSize =1125makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);1126MCOS->emitIntValue(0, AddrSize);1127emitAbsValue(*MCOS, SectionSize, AddrSize);1128}11291130// Emit end of list entry1131MCOS->emitIntValue(0, AddrSize);1132MCOS->emitIntValue(0, AddrSize);1133}11341135return RangesSymbol;1136}11371138//1139// When generating dwarf for assembly source files this emits the Dwarf1140// sections.1141//1142void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {1143MCContext &context = MCOS->getContext();11441145// Create the dwarf sections in this order (.debug_line already created).1146const MCAsmInfo *AsmInfo = context.getAsmInfo();1147bool CreateDwarfSectionSymbols =1148AsmInfo->doesDwarfUseRelocationsAcrossSections();1149MCSymbol *LineSectionSymbol = nullptr;1150if (CreateDwarfSectionSymbols)1151LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);1152MCSymbol *AbbrevSectionSymbol = nullptr;1153MCSymbol *InfoSectionSymbol = nullptr;1154MCSymbol *RangesSymbol = nullptr;11551156// Create end symbols for each section, and remove empty sections1157MCOS->getContext().finalizeDwarfSections(*MCOS);11581159// If there are no sections to generate debug info for, we don't need1160// to do anything1161if (MCOS->getContext().getGenDwarfSectionSyms().empty())1162return;11631164// We only use the .debug_ranges section if we have multiple code sections,1165// and we are emitting a DWARF version which supports it.1166const bool UseRangesSection =1167MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&1168MCOS->getContext().getDwarfVersion() >= 3;1169CreateDwarfSectionSymbols |= UseRangesSection;11701171MCOS->switchSection(context.getObjectFileInfo()->getDwarfInfoSection());1172if (CreateDwarfSectionSymbols) {1173InfoSectionSymbol = context.createTempSymbol();1174MCOS->emitLabel(InfoSectionSymbol);1175}1176MCOS->switchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());1177if (CreateDwarfSectionSymbols) {1178AbbrevSectionSymbol = context.createTempSymbol();1179MCOS->emitLabel(AbbrevSectionSymbol);1180}11811182MCOS->switchSection(context.getObjectFileInfo()->getDwarfARangesSection());11831184// Output the data for .debug_aranges section.1185EmitGenDwarfAranges(MCOS, InfoSectionSymbol);11861187if (UseRangesSection) {1188RangesSymbol = emitGenDwarfRanges(MCOS);1189assert(RangesSymbol);1190}11911192// Output the data for .debug_abbrev section.1193EmitGenDwarfAbbrev(MCOS);11941195// Output the data for .debug_info section.1196EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);1197}11981199//1200// When generating dwarf for assembly source files this is called when symbol1201// for a label is created. If this symbol is not a temporary and is in the1202// section that dwarf is being generated for, save the needed info to create1203// a dwarf label.1204//1205void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,1206SourceMgr &SrcMgr, SMLoc &Loc) {1207// We won't create dwarf labels for temporary symbols.1208if (Symbol->isTemporary())1209return;1210MCContext &context = MCOS->getContext();1211// We won't create dwarf labels for symbols in sections that we are not1212// generating debug info for.1213if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))1214return;12151216// The dwarf label's name does not have the symbol name's leading1217// underbar if any.1218StringRef Name = Symbol->getName();1219if (Name.starts_with("_"))1220Name = Name.substr(1, Name.size()-1);12211222// Get the dwarf file number to be used for the dwarf label.1223unsigned FileNumber = context.getGenDwarfFileNumber();12241225// Finding the line number is the expensive part which is why we just don't1226// pass it in as for some symbols we won't create a dwarf label.1227unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);1228unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);12291230// We create a temporary symbol for use for the AT_high_pc and AT_low_pc1231// values so that they don't have things like an ARM thumb bit from the1232// original symbol. So when used they won't get a low bit set after1233// relocation.1234MCSymbol *Label = context.createTempSymbol();1235MCOS->emitLabel(Label);12361237// Create and entry for the info and add it to the other entries.1238MCOS->getContext().addMCGenDwarfLabelEntry(1239MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));1240}12411242static int getDataAlignmentFactor(MCStreamer &streamer) {1243MCContext &context = streamer.getContext();1244const MCAsmInfo *asmInfo = context.getAsmInfo();1245int size = asmInfo->getCalleeSaveStackSlotSize();1246if (asmInfo->isStackGrowthDirectionUp())1247return size;1248else1249return -size;1250}12511252static unsigned getSizeForEncoding(MCStreamer &streamer,1253unsigned symbolEncoding) {1254MCContext &context = streamer.getContext();1255unsigned format = symbolEncoding & 0x0f;1256switch (format) {1257default: llvm_unreachable("Unknown Encoding");1258case dwarf::DW_EH_PE_absptr:1259case dwarf::DW_EH_PE_signed:1260return context.getAsmInfo()->getCodePointerSize();1261case dwarf::DW_EH_PE_udata2:1262case dwarf::DW_EH_PE_sdata2:1263return 2;1264case dwarf::DW_EH_PE_udata4:1265case dwarf::DW_EH_PE_sdata4:1266return 4;1267case dwarf::DW_EH_PE_udata8:1268case dwarf::DW_EH_PE_sdata8:1269return 8;1270}1271}12721273static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,1274unsigned symbolEncoding, bool isEH) {1275MCContext &context = streamer.getContext();1276const MCAsmInfo *asmInfo = context.getAsmInfo();1277const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,1278symbolEncoding,1279streamer);1280unsigned size = getSizeForEncoding(streamer, symbolEncoding);1281if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)1282emitAbsValue(streamer, v, size);1283else1284streamer.emitValue(v, size);1285}12861287static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,1288unsigned symbolEncoding) {1289MCContext &context = streamer.getContext();1290const MCAsmInfo *asmInfo = context.getAsmInfo();1291const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,1292symbolEncoding,1293streamer);1294unsigned size = getSizeForEncoding(streamer, symbolEncoding);1295streamer.emitValue(v, size);1296}12971298namespace {12991300class FrameEmitterImpl {1301int64_t CFAOffset = 0;1302int64_t InitialCFAOffset = 0;1303bool IsEH;1304MCObjectStreamer &Streamer;13051306public:1307FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)1308: IsEH(IsEH), Streamer(Streamer) {}13091310/// Emit the unwind information in a compact way.1311void EmitCompactUnwind(const MCDwarfFrameInfo &frame);13121313const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);1314void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,1315bool LastInSection, const MCSymbol &SectionStart);1316void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,1317MCSymbol *BaseLabel);1318void emitCFIInstruction(const MCCFIInstruction &Instr);1319};13201321} // end anonymous namespace13221323static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {1324Streamer.emitInt8(Encoding);1325}13261327void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {1328int dataAlignmentFactor = getDataAlignmentFactor(Streamer);1329auto *MRI = Streamer.getContext().getRegisterInfo();13301331switch (Instr.getOperation()) {1332case MCCFIInstruction::OpRegister: {1333unsigned Reg1 = Instr.getRegister();1334unsigned Reg2 = Instr.getRegister2();1335if (!IsEH) {1336Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);1337Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);1338}1339Streamer.emitInt8(dwarf::DW_CFA_register);1340Streamer.emitULEB128IntValue(Reg1);1341Streamer.emitULEB128IntValue(Reg2);1342return;1343}1344case MCCFIInstruction::OpWindowSave:1345Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);1346return;13471348case MCCFIInstruction::OpNegateRAState:1349Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);1350return;13511352case MCCFIInstruction::OpUndefined: {1353unsigned Reg = Instr.getRegister();1354Streamer.emitInt8(dwarf::DW_CFA_undefined);1355Streamer.emitULEB128IntValue(Reg);1356return;1357}1358case MCCFIInstruction::OpAdjustCfaOffset:1359case MCCFIInstruction::OpDefCfaOffset: {1360const bool IsRelative =1361Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;13621363Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);13641365if (IsRelative)1366CFAOffset += Instr.getOffset();1367else1368CFAOffset = Instr.getOffset();13691370Streamer.emitULEB128IntValue(CFAOffset);13711372return;1373}1374case MCCFIInstruction::OpDefCfa: {1375unsigned Reg = Instr.getRegister();1376if (!IsEH)1377Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);1378Streamer.emitInt8(dwarf::DW_CFA_def_cfa);1379Streamer.emitULEB128IntValue(Reg);1380CFAOffset = Instr.getOffset();1381Streamer.emitULEB128IntValue(CFAOffset);13821383return;1384}1385case MCCFIInstruction::OpDefCfaRegister: {1386unsigned Reg = Instr.getRegister();1387if (!IsEH)1388Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);1389Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);1390Streamer.emitULEB128IntValue(Reg);13911392return;1393}1394// TODO: Implement `_sf` variants if/when they need to be emitted.1395case MCCFIInstruction::OpLLVMDefAspaceCfa: {1396unsigned Reg = Instr.getRegister();1397if (!IsEH)1398Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);1399Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1);1400Streamer.emitULEB128IntValue(Reg);1401CFAOffset = Instr.getOffset();1402Streamer.emitULEB128IntValue(CFAOffset);1403Streamer.emitULEB128IntValue(Instr.getAddressSpace());14041405return;1406}1407case MCCFIInstruction::OpOffset:1408case MCCFIInstruction::OpRelOffset: {1409const bool IsRelative =1410Instr.getOperation() == MCCFIInstruction::OpRelOffset;14111412unsigned Reg = Instr.getRegister();1413if (!IsEH)1414Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);14151416int64_t Offset = Instr.getOffset();1417if (IsRelative)1418Offset -= CFAOffset;1419Offset = Offset / dataAlignmentFactor;14201421if (Offset < 0) {1422Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);1423Streamer.emitULEB128IntValue(Reg);1424Streamer.emitSLEB128IntValue(Offset);1425} else if (Reg < 64) {1426Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);1427Streamer.emitULEB128IntValue(Offset);1428} else {1429Streamer.emitInt8(dwarf::DW_CFA_offset_extended);1430Streamer.emitULEB128IntValue(Reg);1431Streamer.emitULEB128IntValue(Offset);1432}1433return;1434}1435case MCCFIInstruction::OpRememberState:1436Streamer.emitInt8(dwarf::DW_CFA_remember_state);1437return;1438case MCCFIInstruction::OpRestoreState:1439Streamer.emitInt8(dwarf::DW_CFA_restore_state);1440return;1441case MCCFIInstruction::OpSameValue: {1442unsigned Reg = Instr.getRegister();1443Streamer.emitInt8(dwarf::DW_CFA_same_value);1444Streamer.emitULEB128IntValue(Reg);1445return;1446}1447case MCCFIInstruction::OpRestore: {1448unsigned Reg = Instr.getRegister();1449if (!IsEH)1450Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);1451if (Reg < 64) {1452Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);1453} else {1454Streamer.emitInt8(dwarf::DW_CFA_restore_extended);1455Streamer.emitULEB128IntValue(Reg);1456}1457return;1458}1459case MCCFIInstruction::OpGnuArgsSize:1460Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);1461Streamer.emitULEB128IntValue(Instr.getOffset());1462return;14631464case MCCFIInstruction::OpEscape:1465Streamer.emitBytes(Instr.getValues());1466return;1467case MCCFIInstruction::OpLabel:1468Streamer.emitLabel(Instr.getCfiLabel(), Instr.getLoc());1469return;1470}1471llvm_unreachable("Unhandled case in switch");1472}14731474/// Emit frame instructions to describe the layout of the frame.1475void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,1476MCSymbol *BaseLabel) {1477for (const MCCFIInstruction &Instr : Instrs) {1478MCSymbol *Label = Instr.getLabel();1479// Throw out move if the label is invalid.1480if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.14811482// Advance row if new location.1483if (BaseLabel && Label) {1484MCSymbol *ThisSym = Label;1485if (ThisSym != BaseLabel) {1486Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym, Instr.getLoc());1487BaseLabel = ThisSym;1488}1489}14901491emitCFIInstruction(Instr);1492}1493}14941495/// Emit the unwind information in a compact way.1496void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {1497MCContext &Context = Streamer.getContext();1498const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();14991500// range-start range-length compact-unwind-enc personality-func lsda1501// _foo LfooEnd-_foo 0x00000023 0 01502// _bar LbarEnd-_bar 0x00000025 __gxx_personality except_tab11503//1504// .section __LD,__compact_unwind,regular,debug1505//1506// # compact unwind for _foo1507// .quad _foo1508// .set L1,LfooEnd-_foo1509// .long L11510// .long 0x010100011511// .quad 01512// .quad 01513//1514// # compact unwind for _bar1515// .quad _bar1516// .set L2,LbarEnd-_bar1517// .long L21518// .long 0x010200111519// .quad __gxx_personality1520// .quad except_tab115211522uint32_t Encoding = Frame.CompactUnwindEncoding;1523if (!Encoding) return;1524bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());15251526// The encoding needs to know we have an LSDA.1527if (!DwarfEHFrameOnly && Frame.Lsda)1528Encoding |= 0x40000000;15291530// Range Start1531unsigned FDEEncoding = MOFI->getFDEEncoding();1532unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);1533Streamer.emitSymbolValue(Frame.Begin, Size);15341535// Range Length1536const MCExpr *Range =1537makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);1538emitAbsValue(Streamer, Range, 4);15391540// Compact Encoding1541Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);1542Streamer.emitIntValue(Encoding, Size);15431544// Personality Function1545Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);1546if (!DwarfEHFrameOnly && Frame.Personality)1547Streamer.emitSymbolValue(Frame.Personality, Size);1548else1549Streamer.emitIntValue(0, Size); // No personality fn15501551// LSDA1552Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);1553if (!DwarfEHFrameOnly && Frame.Lsda)1554Streamer.emitSymbolValue(Frame.Lsda, Size);1555else1556Streamer.emitIntValue(0, Size); // No LSDA1557}15581559static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {1560if (IsEH)1561return 1;1562switch (DwarfVersion) {1563case 2:1564return 1;1565case 3:1566return 3;1567case 4:1568case 5:1569return 4;1570}1571llvm_unreachable("Unknown version");1572}15731574const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {1575MCContext &context = Streamer.getContext();1576const MCRegisterInfo *MRI = context.getRegisterInfo();1577const MCObjectFileInfo *MOFI = context.getObjectFileInfo();15781579MCSymbol *sectionStart = context.createTempSymbol();1580Streamer.emitLabel(sectionStart);15811582MCSymbol *sectionEnd = context.createTempSymbol();15831584dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();1585unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);1586unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);1587bool IsDwarf64 = Format == dwarf::DWARF64;15881589if (IsDwarf64)1590// DWARF64 mark1591Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);15921593// Length1594const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,1595*sectionEnd, UnitLengthBytes);1596emitAbsValue(Streamer, Length, OffsetSize);15971598// CIE ID1599uint64_t CIE_ID =1600IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);1601Streamer.emitIntValue(CIE_ID, OffsetSize);16021603// Version1604uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());1605Streamer.emitInt8(CIEVersion);16061607if (IsEH) {1608SmallString<8> Augmentation;1609Augmentation += "z";1610if (Frame.Personality)1611Augmentation += "P";1612if (Frame.Lsda)1613Augmentation += "L";1614Augmentation += "R";1615if (Frame.IsSignalFrame)1616Augmentation += "S";1617if (Frame.IsBKeyFrame)1618Augmentation += "B";1619if (Frame.IsMTETaggedFrame)1620Augmentation += "G";1621Streamer.emitBytes(Augmentation);1622}1623Streamer.emitInt8(0);16241625if (CIEVersion >= 4) {1626// Address Size1627Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());16281629// Segment Descriptor Size1630Streamer.emitInt8(0);1631}16321633// Code Alignment Factor1634Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());16351636// Data Alignment Factor1637Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));16381639// Return Address Register1640unsigned RAReg = Frame.RAReg;1641if (RAReg == static_cast<unsigned>(INT_MAX))1642RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);16431644if (CIEVersion == 1) {1645assert(RAReg <= 255 &&1646"DWARF 2 encodes return_address_register in one byte");1647Streamer.emitInt8(RAReg);1648} else {1649Streamer.emitULEB128IntValue(RAReg);1650}16511652// Augmentation Data Length (optional)1653unsigned augmentationLength = 0;1654if (IsEH) {1655if (Frame.Personality) {1656// Personality Encoding1657augmentationLength += 1;1658// Personality1659augmentationLength +=1660getSizeForEncoding(Streamer, Frame.PersonalityEncoding);1661}1662if (Frame.Lsda)1663augmentationLength += 1;1664// Encoding of the FDE pointers1665augmentationLength += 1;16661667Streamer.emitULEB128IntValue(augmentationLength);16681669// Augmentation Data (optional)1670if (Frame.Personality) {1671// Personality Encoding1672emitEncodingByte(Streamer, Frame.PersonalityEncoding);1673// Personality1674EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);1675}16761677if (Frame.Lsda)1678emitEncodingByte(Streamer, Frame.LsdaEncoding);16791680// Encoding of the FDE pointers1681emitEncodingByte(Streamer, MOFI->getFDEEncoding());1682}16831684// Initial Instructions16851686const MCAsmInfo *MAI = context.getAsmInfo();1687if (!Frame.IsSimple) {1688const std::vector<MCCFIInstruction> &Instructions =1689MAI->getInitialFrameState();1690emitCFIInstructions(Instructions, nullptr);1691}16921693InitialCFAOffset = CFAOffset;16941695// Padding1696Streamer.emitValueToAlignment(Align(IsEH ? 4 : MAI->getCodePointerSize()));16971698Streamer.emitLabel(sectionEnd);1699return *sectionStart;1700}17011702void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,1703const MCDwarfFrameInfo &frame,1704bool LastInSection,1705const MCSymbol &SectionStart) {1706MCContext &context = Streamer.getContext();1707MCSymbol *fdeStart = context.createTempSymbol();1708MCSymbol *fdeEnd = context.createTempSymbol();1709const MCObjectFileInfo *MOFI = context.getObjectFileInfo();17101711CFAOffset = InitialCFAOffset;17121713dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();1714unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);17151716if (Format == dwarf::DWARF64)1717// DWARF64 mark1718Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);17191720// Length1721const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);1722emitAbsValue(Streamer, Length, OffsetSize);17231724Streamer.emitLabel(fdeStart);17251726// CIE Pointer1727const MCAsmInfo *asmInfo = context.getAsmInfo();1728if (IsEH) {1729const MCExpr *offset =1730makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);1731emitAbsValue(Streamer, offset, OffsetSize);1732} else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {1733const MCExpr *offset =1734makeEndMinusStartExpr(context, SectionStart, cieStart, 0);1735emitAbsValue(Streamer, offset, OffsetSize);1736} else {1737Streamer.emitSymbolValue(&cieStart, OffsetSize,1738asmInfo->needsDwarfSectionOffsetDirective());1739}17401741// PC Begin1742unsigned PCEncoding =1743IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;1744unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);1745emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);17461747// PC Range1748const MCExpr *Range =1749makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);1750emitAbsValue(Streamer, Range, PCSize);17511752if (IsEH) {1753// Augmentation Data Length1754unsigned augmentationLength = 0;17551756if (frame.Lsda)1757augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);17581759Streamer.emitULEB128IntValue(augmentationLength);17601761// Augmentation Data1762if (frame.Lsda)1763emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);1764}17651766// Call Frame Instructions1767emitCFIInstructions(frame.Instructions, frame.Begin);17681769// Padding1770// The size of a .eh_frame section has to be a multiple of the alignment1771// since a null CIE is interpreted as the end. Old systems overaligned1772// .eh_frame, so we do too and account for it in the last FDE.1773unsigned Alignment = LastInSection ? asmInfo->getCodePointerSize() : PCSize;1774Streamer.emitValueToAlignment(Align(Alignment));17751776Streamer.emitLabel(fdeEnd);1777}17781779namespace {17801781struct CIEKey {1782CIEKey() = default;17831784explicit CIEKey(const MCDwarfFrameInfo &Frame)1785: Personality(Frame.Personality),1786PersonalityEncoding(Frame.PersonalityEncoding),1787LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),1788IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),1789IsBKeyFrame(Frame.IsBKeyFrame),1790IsMTETaggedFrame(Frame.IsMTETaggedFrame) {}17911792StringRef PersonalityName() const {1793if (!Personality)1794return StringRef();1795return Personality->getName();1796}17971798bool operator<(const CIEKey &Other) const {1799return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,1800IsSignalFrame, IsSimple, RAReg, IsBKeyFrame,1801IsMTETaggedFrame) <1802std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,1803Other.LsdaEncoding, Other.IsSignalFrame,1804Other.IsSimple, Other.RAReg, Other.IsBKeyFrame,1805Other.IsMTETaggedFrame);1806}18071808bool operator==(const CIEKey &Other) const {1809return Personality == Other.Personality &&1810PersonalityEncoding == Other.PersonalityEncoding &&1811LsdaEncoding == Other.LsdaEncoding &&1812IsSignalFrame == Other.IsSignalFrame && IsSimple == Other.IsSimple &&1813RAReg == Other.RAReg && IsBKeyFrame == Other.IsBKeyFrame &&1814IsMTETaggedFrame == Other.IsMTETaggedFrame;1815}1816bool operator!=(const CIEKey &Other) const { return !(*this == Other); }18171818const MCSymbol *Personality = nullptr;1819unsigned PersonalityEncoding = 0;1820unsigned LsdaEncoding = -1;1821bool IsSignalFrame = false;1822bool IsSimple = false;1823unsigned RAReg = static_cast<unsigned>(UINT_MAX);1824bool IsBKeyFrame = false;1825bool IsMTETaggedFrame = false;1826};18271828} // end anonymous namespace18291830void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,1831bool IsEH) {1832MCContext &Context = Streamer.getContext();1833const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();1834const MCAsmInfo *AsmInfo = Context.getAsmInfo();1835FrameEmitterImpl Emitter(IsEH, Streamer);1836ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();18371838// Emit the compact unwind info if available.1839bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();1840if (IsEH && MOFI->getCompactUnwindSection()) {1841Streamer.generateCompactUnwindEncodings(MAB);1842bool SectionEmitted = false;1843for (const MCDwarfFrameInfo &Frame : FrameArray) {1844if (Frame.CompactUnwindEncoding == 0) continue;1845if (!SectionEmitted) {1846Streamer.switchSection(MOFI->getCompactUnwindSection());1847Streamer.emitValueToAlignment(Align(AsmInfo->getCodePointerSize()));1848SectionEmitted = true;1849}1850NeedsEHFrameSection |=1851Frame.CompactUnwindEncoding ==1852MOFI->getCompactUnwindDwarfEHFrameOnly();1853Emitter.EmitCompactUnwind(Frame);1854}1855}18561857// Compact unwind information can be emitted in the eh_frame section or the1858// debug_frame section. Skip emitting FDEs and CIEs when the compact unwind1859// doesn't need an eh_frame section and the emission location is the eh_frame1860// section.1861if (!NeedsEHFrameSection && IsEH) return;18621863MCSection &Section =1864IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()1865: *MOFI->getDwarfFrameSection();18661867Streamer.switchSection(&Section);1868MCSymbol *SectionStart = Context.createTempSymbol();1869Streamer.emitLabel(SectionStart);18701871bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();1872// Sort the FDEs by their corresponding CIE before we emit them.1873// This isn't technically necessary according to the DWARF standard,1874// but the Android libunwindstack rejects eh_frame sections where1875// an FDE refers to a CIE other than the closest previous CIE.1876std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());1877llvm::stable_sort(FrameArrayX,1878[](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {1879return CIEKey(X) < CIEKey(Y);1880});1881CIEKey LastKey;1882const MCSymbol *LastCIEStart = nullptr;1883for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {1884const MCDwarfFrameInfo &Frame = *I;1885++I;1886if (CanOmitDwarf && Frame.CompactUnwindEncoding !=1887MOFI->getCompactUnwindDwarfEHFrameOnly() && IsEH)1888// CIEs and FDEs can be emitted in either the eh_frame section or the1889// debug_frame section, on some platforms (e.g. AArch64) the target object1890// file supports emitting a compact_unwind section without an associated1891// eh_frame section. If the eh_frame section is not needed, and the1892// location where the CIEs and FDEs are to be emitted is the eh_frame1893// section, do not emit anything.1894continue;18951896CIEKey Key(Frame);1897if (!LastCIEStart || (IsEH && Key != LastKey)) {1898LastKey = Key;1899LastCIEStart = &Emitter.EmitCIE(Frame);1900}19011902Emitter.EmitFDE(*LastCIEStart, Frame, I == E, *SectionStart);1903}1904}19051906void MCDwarfFrameEmitter::encodeAdvanceLoc(MCContext &Context,1907uint64_t AddrDelta,1908SmallVectorImpl<char> &Out) {1909// Scale the address delta by the minimum instruction length.1910AddrDelta = ScaleAddrDelta(Context, AddrDelta);1911if (AddrDelta == 0)1912return;19131914llvm::endianness E = Context.getAsmInfo()->isLittleEndian()1915? llvm::endianness::little1916: llvm::endianness::big;19171918if (isUIntN(6, AddrDelta)) {1919uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;1920Out.push_back(Opcode);1921} else if (isUInt<8>(AddrDelta)) {1922Out.push_back(dwarf::DW_CFA_advance_loc1);1923Out.push_back(AddrDelta);1924} else if (isUInt<16>(AddrDelta)) {1925Out.push_back(dwarf::DW_CFA_advance_loc2);1926support::endian::write<uint16_t>(Out, AddrDelta, E);1927} else {1928assert(isUInt<32>(AddrDelta));1929Out.push_back(dwarf::DW_CFA_advance_loc4);1930support::endian::write<uint32_t>(Out, AddrDelta, E);1931}1932}193319341935