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