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