1140 lines · cpp
1//===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "llvm/MC/MCContext.h"10#include "llvm/ADT/SmallString.h"11#include "llvm/ADT/SmallVector.h"12#include "llvm/ADT/StringMap.h"13#include "llvm/ADT/StringRef.h"14#include "llvm/ADT/Twine.h"15#include "llvm/BinaryFormat/COFF.h"16#include "llvm/BinaryFormat/ELF.h"17#include "llvm/BinaryFormat/GOFF.h"18#include "llvm/BinaryFormat/Wasm.h"19#include "llvm/BinaryFormat/XCOFF.h"20#include "llvm/MC/MCAsmInfo.h"21#include "llvm/MC/MCCodeView.h"22#include "llvm/MC/MCDwarf.h"23#include "llvm/MC/MCExpr.h"24#include "llvm/MC/MCInst.h"25#include "llvm/MC/MCLabel.h"26#include "llvm/MC/MCSectionCOFF.h"27#include "llvm/MC/MCSectionDXContainer.h"28#include "llvm/MC/MCSectionELF.h"29#include "llvm/MC/MCSectionGOFF.h"30#include "llvm/MC/MCSectionMachO.h"31#include "llvm/MC/MCSectionSPIRV.h"32#include "llvm/MC/MCSectionWasm.h"33#include "llvm/MC/MCSectionXCOFF.h"34#include "llvm/MC/MCStreamer.h"35#include "llvm/MC/MCSubtargetInfo.h"36#include "llvm/MC/MCSymbol.h"37#include "llvm/MC/MCSymbolCOFF.h"38#include "llvm/MC/MCSymbolELF.h"39#include "llvm/MC/MCSymbolGOFF.h"40#include "llvm/MC/MCSymbolMachO.h"41#include "llvm/MC/MCSymbolWasm.h"42#include "llvm/MC/MCSymbolXCOFF.h"43#include "llvm/MC/MCTargetOptions.h"44#include "llvm/MC/SectionKind.h"45#include "llvm/Support/EndianStream.h"46#include "llvm/Support/ErrorHandling.h"47#include "llvm/Support/MemoryBuffer.h"48#include "llvm/Support/Path.h"49#include "llvm/Support/SMLoc.h"50#include "llvm/Support/SourceMgr.h"51#include "llvm/Support/raw_ostream.h"52#include <cassert>53#include <cstdlib>54#include <optional>55#include <tuple>56#include <utility>57 58using namespace llvm;59 60static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,61 std::vector<const MDNode *> &) {62 SMD.print(nullptr, errs());63}64 65MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,66 const MCRegisterInfo *mri, const MCSubtargetInfo *msti,67 const SourceMgr *mgr, MCTargetOptions const *TargetOpts,68 bool DoAutoReset, StringRef Swift5ReflSegmentName)69 : Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),70 SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),71 MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator),72 InlineAsmUsedLabelNames(Allocator),73 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),74 AutoReset(DoAutoReset), TargetOptions(TargetOpts) {75 SaveTempLabels = TargetOptions && TargetOptions->MCSaveTempLabels;76 if (SaveTempLabels)77 setUseNamesOnTempLabels(true);78 SecureLogFile = TargetOptions ? TargetOptions->AsSecureLogFile : "";79 80 if (SrcMgr && SrcMgr->getNumBuffers())81 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())82 ->getBufferIdentifier());83 84 switch (TheTriple.getObjectFormat()) {85 case Triple::MachO:86 Env = IsMachO;87 break;88 case Triple::COFF:89 if (!TheTriple.isOSWindows() && !TheTriple.isUEFI()) {90 reportFatalUsageError(91 "cannot initialize MC for non-Windows COFF object files");92 }93 94 Env = IsCOFF;95 break;96 case Triple::ELF:97 Env = IsELF;98 break;99 case Triple::Wasm:100 Env = IsWasm;101 break;102 case Triple::XCOFF:103 Env = IsXCOFF;104 break;105 case Triple::GOFF:106 Env = IsGOFF;107 break;108 case Triple::DXContainer:109 Env = IsDXContainer;110 break;111 case Triple::SPIRV:112 Env = IsSPIRV;113 break;114 case Triple::UnknownObjectFormat:115 report_fatal_error("Cannot initialize MC for unknown object file format.");116 break;117 }118}119 120MCContext::~MCContext() {121 if (AutoReset)122 reset();123 124 // NOTE: The symbols are all allocated out of a bump pointer allocator,125 // we don't need to free them here.126}127 128void MCContext::initInlineSourceManager() {129 if (!InlineSrcMgr)130 InlineSrcMgr.reset(new SourceMgr());131}132 133//===----------------------------------------------------------------------===//134// Module Lifetime Management135//===----------------------------------------------------------------------===//136 137void MCContext::reset() {138 SrcMgr = nullptr;139 InlineSrcMgr.reset();140 LocInfos.clear();141 DiagHandler = defaultDiagHandler;142 143 // Call the destructors so the fragments are freed144 COFFAllocator.DestroyAll();145 DXCAllocator.DestroyAll();146 ELFAllocator.DestroyAll();147 GOFFAllocator.DestroyAll();148 MachOAllocator.DestroyAll();149 WasmAllocator.DestroyAll();150 XCOFFAllocator.DestroyAll();151 MCInstAllocator.DestroyAll();152 SPIRVAllocator.DestroyAll();153 WasmSignatureAllocator.DestroyAll();154 155 CVContext.reset();156 157 MCSubtargetAllocator.DestroyAll();158 InlineAsmUsedLabelNames.clear();159 Symbols.clear();160 Allocator.Reset();161 Instances.clear();162 CompilationDir.clear();163 MainFileName.clear();164 MCDwarfLineTablesCUMap.clear();165 SectionsForRanges.clear();166 MCGenDwarfLabelEntries.clear();167 DwarfDebugFlags = StringRef();168 DwarfCompileUnitID = 0;169 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);170 171 MachOUniquingMap.clear();172 ELFUniquingMap.clear();173 GOFFUniquingMap.clear();174 COFFUniquingMap.clear();175 WasmUniquingMap.clear();176 XCOFFUniquingMap.clear();177 DXCUniquingMap.clear();178 179 RelSecNames.clear();180 MacroMap.clear();181 ELFEntrySizeMap.clear();182 ELFSeenGenericMergeableSections.clear();183 184 DwarfLocSeen = false;185 GenDwarfForAssembly = false;186 GenDwarfFileNumber = 0;187 188 HadError = false;189}190 191//===----------------------------------------------------------------------===//192// MCInst Management193//===----------------------------------------------------------------------===//194 195MCInst *MCContext::createMCInst() {196 return new (MCInstAllocator.Allocate()) MCInst;197}198 199//===----------------------------------------------------------------------===//200// Symbol Manipulation201//===----------------------------------------------------------------------===//202 203MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {204 SmallString<128> NameSV;205 StringRef NameRef = Name.toStringRef(NameSV);206 207 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");208 209 MCSymbolTableEntry &Entry = getSymbolTableEntry(NameRef);210 if (!Entry.second.Symbol) {211 bool IsRenamable = NameRef.starts_with(MAI->getPrivateGlobalPrefix());212 bool IsTemporary = IsRenamable && !SaveTempLabels;213 if (!Entry.second.Used) {214 Entry.second.Used = true;215 Entry.second.Symbol = createSymbolImpl(&Entry, IsTemporary);216 } else {217 assert(IsRenamable && "cannot rename non-private symbol");218 // Slow path: we need to rename a temp symbol from the user.219 Entry.second.Symbol = createRenamableSymbol(NameRef, false, IsTemporary);220 }221 }222 223 return Entry.second.Symbol;224}225 226MCSymbol *MCContext::parseSymbol(const Twine &Name) {227 SmallString<128> SV;228 StringRef NameRef = Name.toStringRef(SV);229 if (NameRef.contains('\\')) {230 SV = NameRef;231 size_t S = 0;232 // Support escaped \\ and \" as in GNU Assembler. GAS issues a warning for233 // other characters following \\, which we do not implement due to code234 // structure.235 for (size_t I = 0, E = SV.size(); I != E; ++I) {236 char C = SV[I];237 if (C == '\\' && I + 1 != E) {238 switch (SV[I + 1]) {239 case '"':240 case '\\':241 C = SV[++I];242 break;243 }244 }245 SV[S++] = C;246 }247 SV.resize(S);248 NameRef = SV;249 }250 251 return getOrCreateSymbol(NameRef);252}253 254MCSymbol *MCContext::getOrCreateFrameAllocSymbol(const Twine &FuncName,255 unsigned Idx) {256 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +257 "$frame_escape_" + Twine(Idx));258}259 260MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(const Twine &FuncName) {261 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +262 "$parent_frame_offset");263}264 265MCSymbol *MCContext::getOrCreateLSDASymbol(const Twine &FuncName) {266 return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + "__ehtable$" +267 FuncName);268}269 270MCSymbolTableEntry &MCContext::getSymbolTableEntry(StringRef Name) {271 return *Symbols.try_emplace(Name, MCSymbolTableValue{}).first;272}273 274MCSymbol *MCContext::createSymbolImpl(const MCSymbolTableEntry *Name,275 bool IsTemporary) {276 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),277 "MCSymbol classes must be trivially destructible");278 static_assert(std::is_trivially_destructible<MCSymbolELF>(),279 "MCSymbol classes must be trivially destructible");280 static_assert(std::is_trivially_destructible<MCSymbolMachO>(),281 "MCSymbol classes must be trivially destructible");282 static_assert(std::is_trivially_destructible<MCSymbolWasm>(),283 "MCSymbol classes must be trivially destructible");284 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),285 "MCSymbol classes must be trivially destructible");286 287 switch (getObjectFileType()) {288 case MCContext::IsCOFF:289 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);290 case MCContext::IsELF:291 return new (Name, *this) MCSymbolELF(Name, IsTemporary);292 case MCContext::IsGOFF:293 return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);294 case MCContext::IsMachO:295 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);296 case MCContext::IsWasm:297 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);298 case MCContext::IsXCOFF:299 return createXCOFFSymbolImpl(Name, IsTemporary);300 case MCContext::IsDXContainer:301 break;302 case MCContext::IsSPIRV:303 return new (Name, *this) MCSymbol(Name, IsTemporary);304 }305 return new (Name, *this) MCSymbol(Name, IsTemporary);306}307 308MCSymbol *MCContext::cloneSymbol(MCSymbol &Sym) {309 MCSymbol *NewSym = nullptr;310 auto Name = Sym.getNameEntryPtr();311 switch (getObjectFileType()) {312 case MCContext::IsCOFF:313 NewSym =314 new (Name, *this) MCSymbolCOFF(static_cast<const MCSymbolCOFF &>(Sym));315 break;316 case MCContext::IsELF:317 NewSym =318 new (Name, *this) MCSymbolELF(static_cast<const MCSymbolELF &>(Sym));319 break;320 case MCContext::IsMachO:321 NewSym = new (Name, *this)322 MCSymbolMachO(static_cast<const MCSymbolMachO &>(Sym));323 break;324 default:325 reportFatalUsageError(".set redefinition is not supported");326 break;327 }328 // Set the name and redirect the `Symbols` entry to `NewSym`.329 NewSym->getNameEntryPtr() = Name;330 const_cast<MCSymbolTableEntry *>(Name)->second.Symbol = NewSym;331 // Ensure the next `registerSymbol` call will add the new symbol to `Symbols`.332 NewSym->setIsRegistered(false);333 334 // Ensure the original symbol is not emitted to the symbol table.335 Sym.IsTemporary = true;336 return NewSym;337}338 339MCSymbol *MCContext::createRenamableSymbol(const Twine &Name,340 bool AlwaysAddSuffix,341 bool IsTemporary) {342 SmallString<128> NewName;343 Name.toVector(NewName);344 size_t NameLen = NewName.size();345 346 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(NewName.str());347 MCSymbolTableEntry *EntryPtr = &NameEntry;348 while (AlwaysAddSuffix || EntryPtr->second.Used) {349 AlwaysAddSuffix = false;350 351 NewName.resize(NameLen);352 raw_svector_ostream(NewName) << NameEntry.second.NextUniqueID++;353 EntryPtr = &getSymbolTableEntry(NewName.str());354 }355 356 EntryPtr->second.Used = true;357 return createSymbolImpl(EntryPtr, IsTemporary);358}359 360MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {361 if (!UseNamesOnTempLabels)362 return createSymbolImpl(nullptr, /*IsTemporary=*/true);363 return createRenamableSymbol(MAI->getPrivateGlobalPrefix() + Name,364 AlwaysAddSuffix, /*IsTemporary=*/true);365}366 367MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {368 return createRenamableSymbol(MAI->getPrivateGlobalPrefix() + Name, true,369 /*IsTemporary=*/!SaveTempLabels);370}371 372MCSymbol *MCContext::createBlockSymbol(const Twine &Name, bool AlwaysEmit) {373 if (AlwaysEmit)374 return getOrCreateSymbol(MAI->getPrivateLabelPrefix() + Name);375 376 bool IsTemporary = !SaveTempLabels;377 if (IsTemporary && !UseNamesOnTempLabels)378 return createSymbolImpl(nullptr, IsTemporary);379 return createRenamableSymbol(MAI->getPrivateLabelPrefix() + Name,380 /*AlwaysAddSuffix=*/false, IsTemporary);381}382 383MCSymbol *MCContext::createLinkerPrivateTempSymbol() {384 return createLinkerPrivateSymbol("tmp");385}386 387MCSymbol *MCContext::createLinkerPrivateSymbol(const Twine &Name) {388 return createRenamableSymbol(MAI->getLinkerPrivateGlobalPrefix() + Name,389 /*AlwaysAddSuffix=*/true,390 /*IsTemporary=*/false);391}392 393MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }394 395MCSymbol *MCContext::createNamedTempSymbol() {396 return createNamedTempSymbol("tmp");397}398 399MCSymbol *MCContext::createLocalSymbol(StringRef Name) {400 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name);401 return createSymbolImpl(&NameEntry, /*IsTemporary=*/false);402}403 404unsigned MCContext::NextInstance(unsigned LocalLabelVal) {405 MCLabel *&Label = Instances[LocalLabelVal];406 if (!Label)407 Label = new (*this) MCLabel(0);408 return Label->incInstance();409}410 411unsigned MCContext::GetInstance(unsigned LocalLabelVal) {412 MCLabel *&Label = Instances[LocalLabelVal];413 if (!Label)414 Label = new (*this) MCLabel(0);415 return Label->getInstance();416}417 418MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,419 unsigned Instance) {420 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];421 if (!Sym)422 Sym = createNamedTempSymbol();423 return Sym;424}425 426MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {427 unsigned Instance = NextInstance(LocalLabelVal);428 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);429}430 431MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,432 bool Before) {433 unsigned Instance = GetInstance(LocalLabelVal);434 if (!Before)435 ++Instance;436 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);437}438 439// Create a section symbol, with a distinct one for each section of the same.440// The first symbol is used for assembly code references.441template <typename Symbol>442Symbol *MCContext::getOrCreateSectionSymbol(StringRef Section) {443 Symbol *R;444 auto &SymEntry = getSymbolTableEntry(Section);445 MCSymbol *Sym = SymEntry.second.Symbol;446 if (Sym && Sym->isDefined() &&447 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))448 reportError(SMLoc(), "invalid symbol redefinition");449 // Use the symbol's index to track if it has been used as a section symbol.450 // Set to -1 to catch potential bugs if misused as a symbol index.451 if (Sym && Sym->getIndex() != -1u) {452 R = static_cast<Symbol *>(Sym);453 } else {454 SymEntry.second.Used = true;455 R = new (&SymEntry, *this) Symbol(&SymEntry, /*isTemporary=*/false);456 if (!Sym)457 SymEntry.second.Symbol = R;458 }459 // Mark as section symbol.460 R->setIndex(-1u);461 return R;462}463 464MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {465 SmallString<128> NameSV;466 StringRef NameRef = Name.toStringRef(NameSV);467 return Symbols.lookup(NameRef).Symbol;468}469 470void MCContext::setSymbolValue(MCStreamer &Streamer, const Twine &Sym,471 uint64_t Val) {472 auto Symbol = getOrCreateSymbol(Sym);473 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));474}475 476void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {477 InlineAsmUsedLabelNames[Sym->getName()] = Sym;478}479 480wasm::WasmSignature *MCContext::createWasmSignature() {481 return new (WasmSignatureAllocator.Allocate()) wasm::WasmSignature;482}483 484MCSymbolXCOFF *MCContext::createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,485 bool IsTemporary) {486 if (!Name)487 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);488 489 StringRef OriginalName = Name->first();490 if (OriginalName.starts_with("._Renamed..") ||491 OriginalName.starts_with("_Renamed.."))492 reportError(SMLoc(), "invalid symbol name from source");493 494 if (MAI->isValidUnquotedName(OriginalName))495 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);496 497 // Now we have a name that contains invalid character(s) for XCOFF symbol.498 // Let's replace with something valid, but save the original name so that499 // we could still use the original name in the symbol table.500 SmallString<128> InvalidName(OriginalName);501 502 // If it's an entry point symbol, we will keep the '.'503 // in front for the convention purpose. Otherwise, add "_Renamed.."504 // as prefix to signal this is an renamed symbol.505 const bool IsEntryPoint = InvalidName.starts_with(".");506 SmallString<128> ValidName =507 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");508 509 // Append the hex values of '_' and invalid characters with "_Renamed..";510 // at the same time replace invalid characters with '_'.511 for (char &C : InvalidName) {512 if (!MAI->isAcceptableChar(C) || C == '_') {513 raw_svector_ostream(ValidName).write_hex(C);514 C = '_';515 }516 }517 518 // Skip entry point symbol's '.' as we already have a '.' in front of519 // "_Renamed".520 if (IsEntryPoint)521 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));522 else523 ValidName.append(InvalidName);524 525 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(ValidName.str());526 assert(!NameEntry.second.Used && "This name is used somewhere else.");527 NameEntry.second.Used = true;528 // Have the MCSymbol object itself refer to the copy of the string529 // that is embedded in the symbol table entry.530 MCSymbolXCOFF *XSym =531 new (&NameEntry, *this) MCSymbolXCOFF(&NameEntry, IsTemporary);532 XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));533 return XSym;534}535 536//===----------------------------------------------------------------------===//537// Section Management538//===----------------------------------------------------------------------===//539 540MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,541 unsigned TypeAndAttributes,542 unsigned Reserved2, SectionKind Kind,543 const char *BeginSymName) {544 // We unique sections by their segment/section pair. The returned section545 // may not have the same flags as the requested section, if so this should be546 // diagnosed by the client as an error.547 548 // Form the name to look up.549 assert(Section.size() <= 16 && "section name is too long");550 assert(!memchr(Section.data(), '\0', Section.size()) &&551 "section name cannot contain NUL");552 553 // Do the lookup, if we have a hit, return it.554 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());555 if (!R.second)556 return R.first->second;557 558 MCSymbol *Begin = nullptr;559 if (BeginSymName)560 Begin = createTempSymbol(BeginSymName, false);561 562 // Otherwise, return a new section.563 StringRef Name = R.first->first();564 auto *Ret = new (MachOAllocator.Allocate())565 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),566 TypeAndAttributes, Reserved2, Kind, Begin);567 R.first->second = Ret;568 return Ret;569}570 571MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,572 unsigned Flags,573 unsigned EntrySize,574 const MCSymbolELF *Group,575 bool Comdat, unsigned UniqueID,576 const MCSymbolELF *LinkedToSym) {577 auto *R = getOrCreateSectionSymbol<MCSymbolELF>(Section);578 return new (ELFAllocator.Allocate()) MCSectionELF(579 Section, Type, Flags, EntrySize, Group, Comdat, UniqueID, R, LinkedToSym);580}581 582MCSectionELF *583MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,584 unsigned EntrySize, const MCSymbolELF *Group,585 const MCSectionELF *RelInfoSection) {586 StringMap<bool>::iterator I;587 bool Inserted;588 std::tie(I, Inserted) = RelSecNames.insert(std::make_pair(Name.str(), true));589 590 return createELFSectionImpl(591 I->getKey(), Type, Flags, EntrySize, Group, true, true,592 static_cast<const MCSymbolELF *>(RelInfoSection->getBeginSymbol()));593}594 595MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,596 const Twine &Suffix, unsigned Type,597 unsigned Flags,598 unsigned EntrySize) {599 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,600 /*IsComdat=*/true);601}602 603MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,604 unsigned Flags, unsigned EntrySize,605 const Twine &Group, bool IsComdat,606 unsigned UniqueID,607 const MCSymbolELF *LinkedToSym) {608 MCSymbolELF *GroupSym = nullptr;609 if (!Group.isTriviallyEmpty() && !Group.str().empty())610 GroupSym = static_cast<MCSymbolELF *>(getOrCreateSymbol(Group));611 612 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,613 UniqueID, LinkedToSym);614}615 616MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,617 unsigned Flags, unsigned EntrySize,618 const MCSymbolELF *GroupSym,619 bool IsComdat, unsigned UniqueID,620 const MCSymbolELF *LinkedToSym) {621 assert(!(LinkedToSym && LinkedToSym->getName().empty()));622 623 // Sections are differentiated by the quadruple (section_name, group_name,624 // unique_id, link_to_symbol_name). Sections sharing the same quadruple are625 // combined into one section. As an optimization, non-unique sections without626 // group or linked-to symbol have a shorter unique-ing key.627 std::pair<StringMap<MCSectionELF *>::iterator, bool> EntryNewPair;628 // Length of the section name, which are the first SectionLen bytes of the key629 unsigned SectionLen;630 if (GroupSym || LinkedToSym || UniqueID != MCSection::NonUniqueID) {631 SmallString<128> Buffer;632 Section.toVector(Buffer);633 SectionLen = Buffer.size();634 Buffer.push_back(0); // separator which cannot occur in the name635 if (GroupSym)636 Buffer.append(GroupSym->getName());637 Buffer.push_back(0); // separator which cannot occur in the name638 if (LinkedToSym)639 Buffer.append(LinkedToSym->getName());640 support::endian::write(Buffer, UniqueID, endianness::native);641 StringRef UniqueMapKey = StringRef(Buffer);642 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);643 } else if (!Section.isSingleStringRef()) {644 SmallString<128> Buffer;645 StringRef UniqueMapKey = Section.toStringRef(Buffer);646 SectionLen = UniqueMapKey.size();647 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);648 } else {649 StringRef UniqueMapKey = Section.getSingleStringRef();650 SectionLen = UniqueMapKey.size();651 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);652 }653 654 if (!EntryNewPair.second)655 return EntryNewPair.first->second;656 657 StringRef CachedName = EntryNewPair.first->getKey().take_front(SectionLen);658 659 MCSectionELF *Result =660 createELFSectionImpl(CachedName, Type, Flags, EntrySize, GroupSym,661 IsComdat, UniqueID, LinkedToSym);662 EntryNewPair.first->second = Result;663 664 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),665 Result->getUniqueID(), Result->getEntrySize());666 667 return Result;668}669 670MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,671 bool IsComdat) {672 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 4, Group, IsComdat,673 MCSection::NonUniqueID, nullptr);674}675 676void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,677 unsigned Flags, unsigned UniqueID,678 unsigned EntrySize) {679 bool IsMergeable = Flags & ELF::SHF_MERGE;680 if (UniqueID == MCSection::NonUniqueID) {681 ELFSeenGenericMergeableSections.insert(SectionName);682 // Minor performance optimization: avoid hash map lookup in683 // isELFGenericMergeableSection, which will return true for SectionName.684 IsMergeable = true;685 }686 687 // For mergeable sections or non-mergeable sections with a generic mergeable688 // section name we enter their Unique ID into the ELFEntrySizeMap so that689 // compatible globals can be assigned to the same section.690 691 if (IsMergeable || isELFGenericMergeableSection(SectionName)) {692 ELFEntrySizeMap.insert(std::make_pair(693 std::make_tuple(SectionName, Flags, EntrySize), UniqueID));694 }695}696 697bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {698 return SectionName.starts_with(".rodata.str") ||699 SectionName.starts_with(".rodata.cst");700}701 702bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {703 return isELFImplicitMergeableSectionNamePrefix(SectionName) ||704 ELFSeenGenericMergeableSections.count(SectionName);705}706 707std::optional<unsigned>708MCContext::getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags,709 unsigned EntrySize) {710 auto I = ELFEntrySizeMap.find(std::make_tuple(SectionName, Flags, EntrySize));711 return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second)712 : std::nullopt;713}714 715template <typename TAttr>716MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,717 TAttr Attributes, MCSection *Parent,718 bool IsVirtual) {719 std::string UniqueName(Name);720 if (Parent) {721 UniqueName.append("/").append(Parent->getName());722 if (auto *P = static_cast<MCSectionGOFF *>(Parent)->getParent())723 UniqueName.append("/").append(P->getName());724 }725 // Do the lookup. If we don't have a hit, return a new section.726 auto [Iter, Inserted] = GOFFUniquingMap.try_emplace(UniqueName);727 if (!Inserted)728 return Iter->second;729 730 StringRef CachedName = StringRef(Iter->first.c_str(), Name.size());731 MCSectionGOFF *GOFFSection = new (GOFFAllocator.Allocate())732 MCSectionGOFF(CachedName, Kind, IsVirtual, Attributes,733 static_cast<MCSectionGOFF *>(Parent));734 Iter->second = GOFFSection;735 return GOFFSection;736}737 738MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,739 GOFF::SDAttr SDAttributes) {740 return getGOFFSection<GOFF::SDAttr>(Kind, Name, SDAttributes, nullptr,741 /*IsVirtual=*/true);742}743 744MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,745 GOFF::EDAttr EDAttributes,746 MCSection *Parent) {747 return getGOFFSection<GOFF::EDAttr>(748 Kind, Name, EDAttributes, Parent,749 /*IsVirtual=*/EDAttributes.BindAlgorithm == GOFF::ESD_BA_Merge);750}751 752MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,753 GOFF::PRAttr PRAttributes,754 MCSection *Parent) {755 return getGOFFSection<GOFF::PRAttr>(Kind, Name, PRAttributes, Parent,756 /*IsVirtual=*/false);757}758 759MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,760 unsigned Characteristics,761 StringRef COMDATSymName, int Selection,762 unsigned UniqueID) {763 MCSymbol *COMDATSymbol = nullptr;764 if (!COMDATSymName.empty()) {765 COMDATSymbol = getOrCreateSymbol(COMDATSymName);766 assert(COMDATSymbol && "COMDATSymbol is null");767 COMDATSymName = COMDATSymbol->getName();768 // A non-associative COMDAT is considered to define the COMDAT symbol. Check769 // the redefinition error.770 if (Selection != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE &&771 COMDATSymbol->isDefined() &&772 (!COMDATSymbol->isInSection() ||773 static_cast<const MCSectionCOFF &>(COMDATSymbol->getSection())774 .getCOMDATSymbol() != COMDATSymbol))775 reportError(SMLoc(), "invalid symbol redefinition");776 }777 778 // Do the lookup, if we have a hit, return it.779 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};780 auto [Iter, Inserted] = COFFUniquingMap.try_emplace(T);781 if (!Inserted)782 return Iter->second;783 784 StringRef CachedName = Iter->first.SectionName;785 MCSymbol *Begin = getOrCreateSectionSymbol<MCSymbolCOFF>(Section);786 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(787 CachedName, Characteristics, COMDATSymbol, Selection, UniqueID, Begin);788 Iter->second = Result;789 Begin->setFragment(&Result->getDummyFragment());790 return Result;791}792 793MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,794 unsigned Characteristics) {795 return getCOFFSection(Section, Characteristics, "", 0,796 MCSection::NonUniqueID);797}798 799MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,800 const MCSymbol *KeySym,801 unsigned UniqueID) {802 // Return the normal section if we don't have to be associative or unique.803 if (!KeySym && UniqueID == MCSection::NonUniqueID)804 return Sec;805 806 // If we have a key symbol, make an associative section with the same name and807 // kind as the normal section.808 unsigned Characteristics = Sec->getCharacteristics();809 if (KeySym) {810 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;811 return getCOFFSection(Sec->getName(), Characteristics, KeySym->getName(),812 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);813 }814 815 return getCOFFSection(Sec->getName(), Characteristics, "", 0, UniqueID);816}817 818MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,819 unsigned Flags, const Twine &Group,820 unsigned UniqueID) {821 MCSymbolWasm *GroupSym = nullptr;822 if (!Group.isTriviallyEmpty() && !Group.str().empty()) {823 GroupSym = static_cast<MCSymbolWasm *>(getOrCreateSymbol(Group));824 GroupSym->setComdat(true);825 if (K.isMetadata() && !GroupSym->getType().has_value()) {826 // Comdat group symbol associated with a custom section is a section827 // symbol (not a data symbol).828 GroupSym->setType(wasm::WASM_SYMBOL_TYPE_SECTION);829 }830 }831 832 return getWasmSection(Section, K, Flags, GroupSym, UniqueID);833}834 835MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,836 unsigned Flags,837 const MCSymbolWasm *GroupSym,838 unsigned UniqueID) {839 StringRef Group = "";840 if (GroupSym)841 Group = GroupSym->getName();842 // Do the lookup, if we have a hit, return it.843 auto IterBool = WasmUniquingMap.insert(844 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));845 auto &Entry = *IterBool.first;846 if (!IterBool.second)847 return Entry.second;848 849 StringRef CachedName = Entry.first.SectionName;850 851 MCSymbol *Begin = createRenamableSymbol(CachedName, true, false);852 // Begin always has a different name than CachedName... see #48596.853 getSymbolTableEntry(Begin->getName()).second.Symbol = Begin;854 static_cast<MCSymbolWasm *>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);855 856 MCSectionWasm *Result = new (WasmAllocator.Allocate())857 MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);858 Entry.second = Result;859 860 return Result;861}862 863bool MCContext::hasXCOFFSection(StringRef Section,864 XCOFF::CsectProperties CsectProp) const {865 return XCOFFUniquingMap.count(866 XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;867}868 869MCSectionXCOFF *MCContext::getXCOFFSection(870 StringRef Section, SectionKind Kind,871 std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,872 std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {873 bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();874 assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");875 876 // Do the lookup. If we have a hit, return it.877 auto IterBool = XCOFFUniquingMap.insert(std::make_pair(878 IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)879 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),880 nullptr));881 auto &Entry = *IterBool.first;882 if (!IterBool.second) {883 MCSectionXCOFF *ExistedEntry = Entry.second;884 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)885 report_fatal_error("section's multiply symbols policy does not match");886 887 return ExistedEntry;888 }889 890 // Otherwise, return a new section.891 StringRef CachedName = Entry.first.SectionName;892 MCSymbolXCOFF *QualName = nullptr;893 // Debug section don't have storage class attribute.894 if (IsDwarfSec)895 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(CachedName));896 else897 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(898 CachedName + "[" +899 XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));900 901 // QualName->getUnqualifiedName() and CachedName are the same except when902 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.903 MCSectionXCOFF *Result = nullptr;904 if (IsDwarfSec)905 Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(906 QualName->getUnqualifiedName(), Kind, QualName,907 *DwarfSectionSubtypeFlags, QualName, CachedName, MultiSymbolsAllowed);908 else909 Result = new (XCOFFAllocator.Allocate())910 MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,911 CsectProp->Type, Kind, QualName, nullptr, CachedName,912 MultiSymbolsAllowed);913 914 Entry.second = Result;915 return Result;916}917 918MCSectionSPIRV *MCContext::getSPIRVSection() {919 MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate()) MCSectionSPIRV();920 return Result;921}922 923MCSectionDXContainer *MCContext::getDXContainerSection(StringRef Section,924 SectionKind K) {925 // Do the lookup, if we have a hit, return it.926 auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);927 if (!ItInsertedPair.second)928 return ItInsertedPair.first->second;929 930 auto MapIt = ItInsertedPair.first;931 // Grab the name from the StringMap. Since the Section is going to keep a932 // copy of this StringRef we need to make sure the underlying string stays933 // alive as long as we need it.934 StringRef Name = MapIt->first();935 MapIt->second =936 new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);937 938 // The first fragment will store the header939 return MapIt->second;940}941 942MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {943 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);944}945 946void MCContext::addDebugPrefixMapEntry(const std::string &From,947 const std::string &To) {948 DebugPrefixMap.emplace_back(From, To);949}950 951void MCContext::remapDebugPath(SmallVectorImpl<char> &Path) {952 for (const auto &[From, To] : llvm::reverse(DebugPrefixMap))953 if (llvm::sys::path::replace_path_prefix(Path, From, To))954 break;955}956 957void MCContext::RemapDebugPaths() {958 const auto &DebugPrefixMap = this->DebugPrefixMap;959 if (DebugPrefixMap.empty())960 return;961 962 // Remap compilation directory.963 remapDebugPath(CompilationDir);964 965 // Remap MCDwarfDirs and RootFile.Name in all compilation units.966 SmallString<256> P;967 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {968 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {969 P = Dir;970 remapDebugPath(P);971 Dir = std::string(P);972 }973 974 // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's975 // DW_AT_decl_file for DWARF v5 generated for assembly source.976 P = CUIDTablePair.second.getRootFile().Name;977 remapDebugPath(P);978 CUIDTablePair.second.getRootFile().Name = std::string(P);979 }980}981 982//===----------------------------------------------------------------------===//983// Dwarf Management984//===----------------------------------------------------------------------===//985 986EmitDwarfUnwindType MCContext::emitDwarfUnwindInfo() const {987 if (!TargetOptions)988 return EmitDwarfUnwindType::Default;989 return TargetOptions->EmitDwarfUnwind;990}991 992bool MCContext::emitCompactUnwindNonCanonical() const {993 if (TargetOptions)994 return TargetOptions->EmitCompactUnwindNonCanonical;995 return false;996}997 998void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {999 // MCDwarf needs the root file as well as the compilation directory.1000 // If we find a '.file 0' directive that will supersede these values.1001 std::optional<MD5::MD5Result> Cksum;1002 if (getDwarfVersion() >= 5) {1003 MD5 Hash;1004 MD5::MD5Result Sum;1005 Hash.update(Buffer);1006 Hash.final(Sum);1007 Cksum = Sum;1008 }1009 // Canonicalize the root filename. It cannot be empty, and should not1010 // repeat the compilation dir.1011 // The MCContext ctor initializes MainFileName to the name associated with1012 // the SrcMgr's main file ID, which might be the same as InputFileName (and1013 // possibly include directory components).1014 // Or, MainFileName might have been overridden by a -main-file-name option,1015 // which is supposed to be just a base filename with no directory component.1016 // So, if the InputFileName and MainFileName are not equal, assume1017 // MainFileName is a substitute basename and replace the last component.1018 SmallString<1024> FileNameBuf = InputFileName;1019 if (FileNameBuf.empty() || FileNameBuf == "-")1020 FileNameBuf = "<stdin>";1021 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {1022 llvm::sys::path::remove_filename(FileNameBuf);1023 llvm::sys::path::append(FileNameBuf, getMainFileName());1024 }1025 StringRef FileName = FileNameBuf;1026 if (FileName.consume_front(getCompilationDir()))1027 if (llvm::sys::path::is_separator(FileName.front()))1028 FileName = FileName.drop_front();1029 assert(!FileName.empty());1030 setMCLineTableRootFile(1031 /*CUID=*/0, getCompilationDir(), FileName, Cksum, std::nullopt);1032}1033 1034/// getDwarfFile - takes a file name and number to place in the dwarf file and1035/// directory tables. If the file number has already been allocated it is an1036/// error and zero is returned and the client reports the error, else the1037/// allocated file number is returned. The file numbers may be in any order.1038Expected<unsigned>1039MCContext::getDwarfFile(StringRef Directory, StringRef FileName,1040 unsigned FileNumber,1041 std::optional<MD5::MD5Result> Checksum,1042 std::optional<StringRef> Source, unsigned CUID) {1043 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];1044 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,1045 FileNumber);1046}1047 1048/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it1049/// currently is assigned and false otherwise.1050bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {1051 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);1052 if (FileNumber == 0)1053 return getDwarfVersion() >= 5;1054 if (FileNumber >= LineTable.getMCDwarfFiles().size())1055 return false;1056 1057 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();1058}1059 1060/// Remove empty sections from SectionsForRanges, to avoid generating1061/// useless debug info for them.1062void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {1063 SectionsForRanges.remove_if(1064 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });1065}1066 1067CodeViewContext &MCContext::getCVContext() {1068 if (!CVContext)1069 CVContext.reset(new CodeViewContext(this));1070 return *CVContext;1071}1072 1073//===----------------------------------------------------------------------===//1074// Error Reporting1075//===----------------------------------------------------------------------===//1076 1077void MCContext::diagnose(const SMDiagnostic &SMD) {1078 assert(DiagHandler && "MCContext::DiagHandler is not set");1079 bool UseInlineSrcMgr = false;1080 const SourceMgr *SMP = nullptr;1081 if (SrcMgr) {1082 SMP = SrcMgr;1083 } else if (InlineSrcMgr) {1084 SMP = InlineSrcMgr.get();1085 UseInlineSrcMgr = true;1086 } else1087 llvm_unreachable("Either SourceMgr should be available");1088 DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);1089}1090 1091void MCContext::reportCommon(1092 SMLoc Loc,1093 std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {1094 // * MCContext::SrcMgr is null when the MC layer emits machine code for input1095 // other than assembly file, say, for .c/.cpp/.ll/.bc.1096 // * MCContext::InlineSrcMgr is null when the inline asm is not used.1097 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr1098 // and MCContext::InlineSrcMgr are null.1099 SourceMgr SM;1100 const SourceMgr *SMP = &SM;1101 bool UseInlineSrcMgr = false;1102 1103 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.1104 // For MC-only execution, only SrcMgr is used;1105 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is1106 // inline asm in the IR.1107 if (Loc.isValid()) {1108 if (SrcMgr) {1109 SMP = SrcMgr;1110 } else if (InlineSrcMgr) {1111 SMP = InlineSrcMgr.get();1112 UseInlineSrcMgr = true;1113 } else1114 llvm_unreachable("Either SourceMgr should be available");1115 }1116 1117 SMDiagnostic D;1118 GetMessage(D, SMP);1119 DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);1120}1121 1122void MCContext::reportError(SMLoc Loc, const Twine &Msg) {1123 HadError = true;1124 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {1125 D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);1126 });1127}1128 1129void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {1130 if (TargetOptions && TargetOptions->MCNoWarn)1131 return;1132 if (TargetOptions && TargetOptions->MCFatalWarnings) {1133 reportError(Loc, Msg);1134 } else {1135 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {1136 D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);1137 });1138 }1139}1140