xref: /freebsd/contrib/llvm-project/llvm/lib/MC/MCContext.cpp (revision 4b9d605768acabc460aa6dcfe8a1f8db35b16794)
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() && !TheTriple.isUEFI())
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(const Twine &FuncName,
215                                                  unsigned Idx) {
216   return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +
217                            "$frame_escape_" + Twine(Idx));
218 }
219 
220 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(const Twine &FuncName) {
221   return getOrCreateSymbol(MAI->getPrivateGlobalPrefix() + FuncName +
222                            "$parent_frame_offset");
223 }
224 
225 MCSymbol *MCContext::getOrCreateLSDASymbol(const Twine &FuncName) {
226   return getOrCreateSymbol(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)
263       MCSymbol(MCSymbol::SymbolKindUnset, Name, 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   return createLinkerPrivateSymbol("tmp");
314 }
315 
316 MCSymbol *MCContext::createLinkerPrivateSymbol(const Twine &Name) {
317   SmallString<128> NameSV;
318   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << Name;
319   return createSymbol(NameSV, true, false);
320 }
321 
322 MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
323 
324 MCSymbol *MCContext::createNamedTempSymbol() {
325   return createNamedTempSymbol("tmp");
326 }
327 
328 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
329   MCLabel *&Label = Instances[LocalLabelVal];
330   if (!Label)
331     Label = new (*this) MCLabel(0);
332   return Label->incInstance();
333 }
334 
335 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
336   MCLabel *&Label = Instances[LocalLabelVal];
337   if (!Label)
338     Label = new (*this) MCLabel(0);
339   return Label->getInstance();
340 }
341 
342 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
343                                                        unsigned Instance) {
344   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
345   if (!Sym)
346     Sym = createNamedTempSymbol();
347   return Sym;
348 }
349 
350 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
351   unsigned Instance = NextInstance(LocalLabelVal);
352   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
353 }
354 
355 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
356                                                bool Before) {
357   unsigned Instance = GetInstance(LocalLabelVal);
358   if (!Before)
359     ++Instance;
360   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
361 }
362 
363 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
364   SmallString<128> NameSV;
365   StringRef NameRef = Name.toStringRef(NameSV);
366   return Symbols.lookup(NameRef);
367 }
368 
369 void MCContext::setSymbolValue(MCStreamer &Streamer, const Twine &Sym,
370                                uint64_t Val) {
371   auto Symbol = getOrCreateSymbol(Sym);
372   Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
373 }
374 
375 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
376   InlineAsmUsedLabelNames[Sym->getName()] = Sym;
377 }
378 
379 MCSymbolXCOFF *
380 MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
381                                  bool IsTemporary) {
382   if (!Name)
383     return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
384 
385   StringRef OriginalName = Name->first();
386   if (OriginalName.startswith("._Renamed..") ||
387       OriginalName.startswith("_Renamed.."))
388     reportError(SMLoc(), "invalid symbol name from source");
389 
390   if (MAI->isValidUnquotedName(OriginalName))
391     return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
392 
393   // Now we have a name that contains invalid character(s) for XCOFF symbol.
394   // Let's replace with something valid, but save the original name so that
395   // we could still use the original name in the symbol table.
396   SmallString<128> InvalidName(OriginalName);
397 
398   // If it's an entry point symbol, we will keep the '.'
399   // in front for the convention purpose. Otherwise, add "_Renamed.."
400   // as prefix to signal this is an renamed symbol.
401   const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.';
402   SmallString<128> ValidName =
403       StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
404 
405   // Append the hex values of '_' and invalid characters with "_Renamed..";
406   // at the same time replace invalid characters with '_'.
407   for (size_t I = 0; I < InvalidName.size(); ++I) {
408     if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
409       raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
410       InvalidName[I] = '_';
411     }
412   }
413 
414   // Skip entry point symbol's '.' as we already have a '.' in front of
415   // "_Renamed".
416   if (IsEntryPoint)
417     ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
418   else
419     ValidName.append(InvalidName);
420 
421   auto NameEntry = UsedNames.insert(std::make_pair(ValidName.str(), true));
422   assert((NameEntry.second || !NameEntry.first->second) &&
423          "This name is used somewhere else.");
424   // Mark the name as used for a non-section symbol.
425   NameEntry.first->second = true;
426   // Have the MCSymbol object itself refer to the copy of the string
427   // that is embedded in the UsedNames entry.
428   MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this)
429       MCSymbolXCOFF(&*NameEntry.first, IsTemporary);
430   XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
431   return XSym;
432 }
433 
434 //===----------------------------------------------------------------------===//
435 // Section Management
436 //===----------------------------------------------------------------------===//
437 
438 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
439                                            unsigned TypeAndAttributes,
440                                            unsigned Reserved2, SectionKind Kind,
441                                            const char *BeginSymName) {
442   // We unique sections by their segment/section pair.  The returned section
443   // may not have the same flags as the requested section, if so this should be
444   // diagnosed by the client as an error.
445 
446   // Form the name to look up.
447   assert(Section.size() <= 16 && "section name is too long");
448   assert(!memchr(Section.data(), '\0', Section.size()) &&
449          "section name cannot contain NUL");
450 
451   // Do the lookup, if we have a hit, return it.
452   auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
453   if (!R.second)
454     return R.first->second;
455 
456   MCSymbol *Begin = nullptr;
457   if (BeginSymName)
458     Begin = createTempSymbol(BeginSymName, false);
459 
460   // Otherwise, return a new section.
461   StringRef Name = R.first->first();
462   R.first->second = new (MachOAllocator.Allocate())
463       MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
464                      TypeAndAttributes, Reserved2, Kind, Begin);
465   return R.first->second;
466 }
467 
468 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
469                                               unsigned Flags, SectionKind K,
470                                               unsigned EntrySize,
471                                               const MCSymbolELF *Group,
472                                               bool Comdat, unsigned UniqueID,
473                                               const MCSymbolELF *LinkedToSym) {
474   MCSymbolELF *R;
475   MCSymbol *&Sym = Symbols[Section];
476   // A section symbol can not redefine regular symbols. There may be multiple
477   // sections with the same name, in which case the first such section wins.
478   if (Sym && Sym->isDefined() &&
479       (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
480     reportError(SMLoc(), "invalid symbol redefinition");
481   if (Sym && Sym->isUndefined()) {
482     R = cast<MCSymbolELF>(Sym);
483   } else {
484     auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
485     R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
486     if (!Sym)
487       Sym = R;
488   }
489   R->setBinding(ELF::STB_LOCAL);
490   R->setType(ELF::STT_SECTION);
491 
492   auto *Ret = new (ELFAllocator.Allocate())
493       MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
494                    R, LinkedToSym);
495 
496   auto *F = new MCDataFragment();
497   Ret->getFragmentList().insert(Ret->begin(), F);
498   F->setParent(Ret);
499   R->setFragment(F);
500 
501   return Ret;
502 }
503 
504 MCSectionELF *
505 MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,
506                                unsigned EntrySize, const MCSymbolELF *Group,
507                                const MCSectionELF *RelInfoSection) {
508   StringMap<bool>::iterator I;
509   bool Inserted;
510   std::tie(I, Inserted) = RelSecNames.insert(std::make_pair(Name.str(), true));
511 
512   return createELFSectionImpl(
513       I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
514       true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
515 }
516 
517 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
518                                             const Twine &Suffix, unsigned Type,
519                                             unsigned Flags,
520                                             unsigned EntrySize) {
521   return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
522                        /*IsComdat=*/true);
523 }
524 
525 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
526                                        unsigned Flags, unsigned EntrySize,
527                                        const Twine &Group, bool IsComdat,
528                                        unsigned UniqueID,
529                                        const MCSymbolELF *LinkedToSym) {
530   MCSymbolELF *GroupSym = nullptr;
531   if (!Group.isTriviallyEmpty() && !Group.str().empty())
532     GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
533 
534   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
535                        UniqueID, LinkedToSym);
536 }
537 
538 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
539                                        unsigned Flags, unsigned EntrySize,
540                                        const MCSymbolELF *GroupSym,
541                                        bool IsComdat, unsigned UniqueID,
542                                        const MCSymbolELF *LinkedToSym) {
543   StringRef Group = "";
544   if (GroupSym)
545     Group = GroupSym->getName();
546   assert(!(LinkedToSym && LinkedToSym->getName().empty()));
547   // Do the lookup, if we have a hit, return it.
548   auto IterBool = ELFUniquingMap.insert(std::make_pair(
549       ELFSectionKey{Section.str(), Group,
550                     LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
551       nullptr));
552   auto &Entry = *IterBool.first;
553   if (!IterBool.second)
554     return Entry.second;
555 
556   StringRef CachedName = Entry.first.SectionName;
557 
558   SectionKind Kind;
559   if (Flags & ELF::SHF_ARM_PURECODE)
560     Kind = SectionKind::getExecuteOnly();
561   else if (Flags & ELF::SHF_EXECINSTR)
562     Kind = SectionKind::getText();
563   else if (~Flags & ELF::SHF_WRITE)
564     Kind = SectionKind::getReadOnly();
565   else if (Flags & ELF::SHF_TLS)
566     Kind = (Type & ELF::SHT_NOBITS) ? SectionKind::getThreadBSS()
567                                     : SectionKind::getThreadData();
568   else
569     // Default to `SectionKind::getText()`. This is the default for gas as
570     // well. The condition that falls into this case is where we do not have any
571     // section flags and must infer a classification rather than where we have
572     // section flags (i.e. this is not that SHF_EXECINSTR is unset bur rather it
573     // is unknown).
574     Kind = llvm::StringSwitch<SectionKind>(CachedName)
575                .Case(".bss", SectionKind::getBSS())
576                .StartsWith(".bss.", SectionKind::getBSS())
577                .StartsWith(".gnu.linkonce.b.", SectionKind::getBSS())
578                .StartsWith(".llvm.linkonce.b.", SectionKind::getBSS())
579                .Case(".data", SectionKind::getData())
580                .Case(".data1", SectionKind::getData())
581                .Case(".data.rel.ro", SectionKind::getReadOnlyWithRel())
582                .StartsWith(".data.", SectionKind::getData())
583                .Case(".rodata", SectionKind::getReadOnly())
584                .Case(".rodata1", SectionKind::getReadOnly())
585                .StartsWith(".rodata.", SectionKind::getReadOnly())
586                .Case(".tbss", SectionKind::getThreadBSS())
587                .StartsWith(".tbss.", SectionKind::getThreadData())
588                .StartsWith(".gnu.linkonce.tb.", SectionKind::getThreadData())
589                .StartsWith(".llvm.linkonce.tb.", SectionKind::getThreadData())
590                .Case(".tdata", SectionKind::getThreadData())
591                .StartsWith(".tdata.", SectionKind::getThreadData())
592                .StartsWith(".gnu.linkonce.td.", SectionKind::getThreadData())
593                .StartsWith(".llvm.linkonce.td.", SectionKind::getThreadData())
594                .StartsWith(".debug_", SectionKind::getMetadata())
595                .Default(SectionKind::getText());
596 
597   MCSectionELF *Result =
598       createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
599                            IsComdat, UniqueID, LinkedToSym);
600   Entry.second = Result;
601 
602   recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
603                                 Result->getUniqueID(), Result->getEntrySize());
604 
605   return Result;
606 }
607 
608 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
609                                                bool IsComdat) {
610   return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
611                               SectionKind::getReadOnly(), 4, Group, IsComdat,
612                               MCSection::NonUniqueID, nullptr);
613 }
614 
615 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
616                                               unsigned Flags, unsigned UniqueID,
617                                               unsigned EntrySize) {
618   bool IsMergeable = Flags & ELF::SHF_MERGE;
619   if (UniqueID == GenericSectionID)
620     ELFSeenGenericMergeableSections.insert(SectionName);
621 
622   // For mergeable sections or non-mergeable sections with a generic mergeable
623   // section name we enter their Unique ID into the ELFEntrySizeMap so that
624   // compatible globals can be assigned to the same section.
625   if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
626     ELFEntrySizeMap.insert(std::make_pair(
627         ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
628   }
629 }
630 
631 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
632   return SectionName.startswith(".rodata.str") ||
633          SectionName.startswith(".rodata.cst");
634 }
635 
636 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
637   return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
638          ELFSeenGenericMergeableSections.count(SectionName);
639 }
640 
641 std::optional<unsigned>
642 MCContext::getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags,
643                                     unsigned EntrySize) {
644   auto I = ELFEntrySizeMap.find(
645       MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
646   return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second)
647                                       : std::nullopt;
648 }
649 
650 MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind,
651                                          MCSection *Parent,
652                                          const MCExpr *SubsectionId) {
653   // Do the lookup. If we don't have a hit, return a new section.
654   auto &GOFFSection = GOFFUniquingMap[Section.str()];
655   if (!GOFFSection)
656     GOFFSection = new (GOFFAllocator.Allocate())
657         MCSectionGOFF(Section, Kind, Parent, SubsectionId);
658 
659   return GOFFSection;
660 }
661 
662 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
663                                          unsigned Characteristics,
664                                          SectionKind Kind,
665                                          StringRef COMDATSymName, int Selection,
666                                          unsigned UniqueID,
667                                          const char *BeginSymName) {
668   MCSymbol *COMDATSymbol = nullptr;
669   if (!COMDATSymName.empty()) {
670     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
671     COMDATSymName = COMDATSymbol->getName();
672   }
673 
674   // Do the lookup, if we have a hit, return it.
675   COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
676   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
677   auto Iter = IterBool.first;
678   if (!IterBool.second)
679     return Iter->second;
680 
681   MCSymbol *Begin = nullptr;
682   if (BeginSymName)
683     Begin = createTempSymbol(BeginSymName, false);
684 
685   StringRef CachedName = Iter->first.SectionName;
686   MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
687       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
688 
689   Iter->second = Result;
690   return Result;
691 }
692 
693 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
694                                          unsigned Characteristics,
695                                          SectionKind Kind,
696                                          const char *BeginSymName) {
697   return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
698                         BeginSymName);
699 }
700 
701 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
702                                                     const MCSymbol *KeySym,
703                                                     unsigned UniqueID) {
704   // Return the normal section if we don't have to be associative or unique.
705   if (!KeySym && UniqueID == GenericSectionID)
706     return Sec;
707 
708   // If we have a key symbol, make an associative section with the same name and
709   // kind as the normal section.
710   unsigned Characteristics = Sec->getCharacteristics();
711   if (KeySym) {
712     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
713     return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
714                           KeySym->getName(),
715                           COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
716   }
717 
718   return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
719                         UniqueID);
720 }
721 
722 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
723                                          unsigned Flags, const Twine &Group,
724                                          unsigned UniqueID,
725                                          const char *BeginSymName) {
726   MCSymbolWasm *GroupSym = nullptr;
727   if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
728     GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
729     GroupSym->setComdat(true);
730   }
731 
732   return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
733 }
734 
735 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
736                                          unsigned Flags,
737                                          const MCSymbolWasm *GroupSym,
738                                          unsigned UniqueID,
739                                          const char *BeginSymName) {
740   StringRef Group = "";
741   if (GroupSym)
742     Group = GroupSym->getName();
743   // Do the lookup, if we have a hit, return it.
744   auto IterBool = WasmUniquingMap.insert(
745       std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
746   auto &Entry = *IterBool.first;
747   if (!IterBool.second)
748     return Entry.second;
749 
750   StringRef CachedName = Entry.first.SectionName;
751 
752   MCSymbol *Begin = createSymbol(CachedName, true, false);
753   Symbols[Begin->getName()] = Begin;
754   cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
755 
756   MCSectionWasm *Result = new (WasmAllocator.Allocate())
757       MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
758   Entry.second = Result;
759 
760   auto *F = new MCDataFragment();
761   Result->getFragmentList().insert(Result->begin(), F);
762   F->setParent(Result);
763   Begin->setFragment(F);
764 
765   return Result;
766 }
767 
768 bool MCContext::hasXCOFFSection(StringRef Section,
769                                 XCOFF::CsectProperties CsectProp) const {
770   return XCOFFUniquingMap.count(
771              XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
772 }
773 
774 MCSectionXCOFF *MCContext::getXCOFFSection(
775     StringRef Section, SectionKind Kind,
776     std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
777     const char *BeginSymName,
778     std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
779   bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
780   assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
781 
782   // Do the lookup. If we have a hit, return it.
783   auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
784       IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)
785                  : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
786       nullptr));
787   auto &Entry = *IterBool.first;
788   if (!IterBool.second) {
789     MCSectionXCOFF *ExistedEntry = Entry.second;
790     if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
791       report_fatal_error("section's multiply symbols policy does not match");
792 
793     return ExistedEntry;
794   }
795 
796   // Otherwise, return a new section.
797   StringRef CachedName = Entry.first.SectionName;
798   MCSymbolXCOFF *QualName = nullptr;
799   // Debug section don't have storage class attribute.
800   if (IsDwarfSec)
801     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
802   else
803     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
804         CachedName + "[" +
805         XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
806 
807   MCSymbol *Begin = nullptr;
808   if (BeginSymName)
809     Begin = createTempSymbol(BeginSymName, false);
810 
811   // QualName->getUnqualifiedName() and CachedName are the same except when
812   // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
813   MCSectionXCOFF *Result = nullptr;
814   if (IsDwarfSec)
815     Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
816         QualName->getUnqualifiedName(), Kind, QualName,
817         *DwarfSectionSubtypeFlags, Begin, CachedName, MultiSymbolsAllowed);
818   else
819     Result = new (XCOFFAllocator.Allocate())
820         MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
821                        CsectProp->Type, Kind, QualName, Begin, CachedName,
822                        MultiSymbolsAllowed);
823 
824   Entry.second = Result;
825 
826   auto *F = new MCDataFragment();
827   Result->getFragmentList().insert(Result->begin(), F);
828   F->setParent(Result);
829 
830   if (Begin)
831     Begin->setFragment(F);
832 
833   // We might miss calculating the symbols difference as absolute value before
834   // adding fixups when symbol_A without the fragment set is the csect itself
835   // and symbol_B is in it.
836   // TODO: Currently we only set the fragment for XMC_PR csects because we don't
837   // have other cases that hit this problem yet.
838   if (!IsDwarfSec && CsectProp->MappingClass == XCOFF::XMC_PR)
839     QualName->setFragment(F);
840 
841   return Result;
842 }
843 
844 MCSectionSPIRV *MCContext::getSPIRVSection() {
845   MCSymbol *Begin = nullptr;
846   MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate())
847       MCSectionSPIRV(SectionKind::getText(), Begin);
848 
849   auto *F = new MCDataFragment();
850   Result->getFragmentList().insert(Result->begin(), F);
851   F->setParent(Result);
852 
853   return Result;
854 }
855 
856 MCSectionDXContainer *MCContext::getDXContainerSection(StringRef Section,
857                                                        SectionKind K) {
858   // Do the lookup, if we have a hit, return it.
859   auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);
860   if (!ItInsertedPair.second)
861     return ItInsertedPair.first->second;
862 
863   auto MapIt = ItInsertedPair.first;
864   // Grab the name from the StringMap. Since the Section is going to keep a
865   // copy of this StringRef we need to make sure the underlying string stays
866   // alive as long as we need it.
867   StringRef Name = MapIt->first();
868   MapIt->second =
869       new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);
870 
871   // The first fragment will store the header
872   auto *F = new MCDataFragment();
873   MapIt->second->getFragmentList().insert(MapIt->second->begin(), F);
874   F->setParent(MapIt->second);
875 
876   return MapIt->second;
877 }
878 
879 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
880   return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
881 }
882 
883 void MCContext::addDebugPrefixMapEntry(const std::string &From,
884                                        const std::string &To) {
885   DebugPrefixMap.emplace_back(From, To);
886 }
887 
888 void MCContext::remapDebugPath(SmallVectorImpl<char> &Path) {
889   for (const auto &[From, To] : llvm::reverse(DebugPrefixMap))
890     if (llvm::sys::path::replace_path_prefix(Path, From, To))
891       break;
892 }
893 
894 void MCContext::RemapDebugPaths() {
895   const auto &DebugPrefixMap = this->DebugPrefixMap;
896   if (DebugPrefixMap.empty())
897     return;
898 
899   // Remap compilation directory.
900   remapDebugPath(CompilationDir);
901 
902   // Remap MCDwarfDirs and RootFile.Name in all compilation units.
903   SmallString<256> P;
904   for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {
905     for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {
906       P = Dir;
907       remapDebugPath(P);
908       Dir = std::string(P);
909     }
910 
911     // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
912     // DW_AT_decl_file for DWARF v5 generated for assembly source.
913     P = CUIDTablePair.second.getRootFile().Name;
914     remapDebugPath(P);
915     CUIDTablePair.second.getRootFile().Name = std::string(P);
916   }
917 }
918 
919 //===----------------------------------------------------------------------===//
920 // Dwarf Management
921 //===----------------------------------------------------------------------===//
922 
923 EmitDwarfUnwindType MCContext::emitDwarfUnwindInfo() const {
924   if (!TargetOptions)
925     return EmitDwarfUnwindType::Default;
926   return TargetOptions->EmitDwarfUnwind;
927 }
928 
929 bool MCContext::emitCompactUnwindNonCanonical() const {
930   if (TargetOptions)
931     return TargetOptions->EmitCompactUnwindNonCanonical;
932   return false;
933 }
934 
935 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
936   // MCDwarf needs the root file as well as the compilation directory.
937   // If we find a '.file 0' directive that will supersede these values.
938   std::optional<MD5::MD5Result> Cksum;
939   if (getDwarfVersion() >= 5) {
940     MD5 Hash;
941     MD5::MD5Result Sum;
942     Hash.update(Buffer);
943     Hash.final(Sum);
944     Cksum = Sum;
945   }
946   // Canonicalize the root filename. It cannot be empty, and should not
947   // repeat the compilation dir.
948   // The MCContext ctor initializes MainFileName to the name associated with
949   // the SrcMgr's main file ID, which might be the same as InputFileName (and
950   // possibly include directory components).
951   // Or, MainFileName might have been overridden by a -main-file-name option,
952   // which is supposed to be just a base filename with no directory component.
953   // So, if the InputFileName and MainFileName are not equal, assume
954   // MainFileName is a substitute basename and replace the last component.
955   SmallString<1024> FileNameBuf = InputFileName;
956   if (FileNameBuf.empty() || FileNameBuf == "-")
957     FileNameBuf = "<stdin>";
958   if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
959     llvm::sys::path::remove_filename(FileNameBuf);
960     llvm::sys::path::append(FileNameBuf, getMainFileName());
961   }
962   StringRef FileName = FileNameBuf;
963   if (FileName.consume_front(getCompilationDir()))
964     if (llvm::sys::path::is_separator(FileName.front()))
965       FileName = FileName.drop_front();
966   assert(!FileName.empty());
967   setMCLineTableRootFile(
968       /*CUID=*/0, getCompilationDir(), FileName, Cksum, std::nullopt);
969 }
970 
971 /// getDwarfFile - takes a file name and number to place in the dwarf file and
972 /// directory tables.  If the file number has already been allocated it is an
973 /// error and zero is returned and the client reports the error, else the
974 /// allocated file number is returned.  The file numbers may be in any order.
975 Expected<unsigned>
976 MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
977                         unsigned FileNumber,
978                         std::optional<MD5::MD5Result> Checksum,
979                         std::optional<StringRef> Source, unsigned CUID) {
980   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
981   return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
982                           FileNumber);
983 }
984 
985 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
986 /// currently is assigned and false otherwise.
987 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
988   const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
989   if (FileNumber == 0)
990     return getDwarfVersion() >= 5;
991   if (FileNumber >= LineTable.getMCDwarfFiles().size())
992     return false;
993 
994   return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
995 }
996 
997 /// Remove empty sections from SectionsForRanges, to avoid generating
998 /// useless debug info for them.
999 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
1000   SectionsForRanges.remove_if(
1001       [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
1002 }
1003 
1004 CodeViewContext &MCContext::getCVContext() {
1005   if (!CVContext)
1006     CVContext.reset(new CodeViewContext);
1007   return *CVContext;
1008 }
1009 
1010 //===----------------------------------------------------------------------===//
1011 // Error Reporting
1012 //===----------------------------------------------------------------------===//
1013 
1014 void MCContext::diagnose(const SMDiagnostic &SMD) {
1015   assert(DiagHandler && "MCContext::DiagHandler is not set");
1016   bool UseInlineSrcMgr = false;
1017   const SourceMgr *SMP = nullptr;
1018   if (SrcMgr) {
1019     SMP = SrcMgr;
1020   } else if (InlineSrcMgr) {
1021     SMP = InlineSrcMgr.get();
1022     UseInlineSrcMgr = true;
1023   } else
1024     llvm_unreachable("Either SourceMgr should be available");
1025   DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
1026 }
1027 
1028 void MCContext::reportCommon(
1029     SMLoc Loc,
1030     std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
1031   // * MCContext::SrcMgr is null when the MC layer emits machine code for input
1032   //   other than assembly file, say, for .c/.cpp/.ll/.bc.
1033   // * MCContext::InlineSrcMgr is null when the inline asm is not used.
1034   // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
1035   //   and MCContext::InlineSrcMgr are null.
1036   SourceMgr SM;
1037   const SourceMgr *SMP = &SM;
1038   bool UseInlineSrcMgr = false;
1039 
1040   // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
1041   //        For MC-only execution, only SrcMgr is used;
1042   //        For non MC-only execution, InlineSrcMgr is only ctor'd if there is
1043   //        inline asm in the IR.
1044   if (Loc.isValid()) {
1045     if (SrcMgr) {
1046       SMP = SrcMgr;
1047     } else if (InlineSrcMgr) {
1048       SMP = InlineSrcMgr.get();
1049       UseInlineSrcMgr = true;
1050     } else
1051       llvm_unreachable("Either SourceMgr should be available");
1052   }
1053 
1054   SMDiagnostic D;
1055   GetMessage(D, SMP);
1056   DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
1057 }
1058 
1059 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
1060   HadError = true;
1061   reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1062     D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
1063   });
1064 }
1065 
1066 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
1067   if (TargetOptions && TargetOptions->MCNoWarn)
1068     return;
1069   if (TargetOptions && TargetOptions->MCFatalWarnings) {
1070     reportError(Loc, Msg);
1071   } else {
1072     reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1073       D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
1074     });
1075   }
1076 }
1077