[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / MC / MCContext.cpp
blobaa4051aa240055b2cf3c5f5421f7f281959b8f3e
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 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCContext.h"
10 #include "llvm/ADT/Optional.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/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/MCLabel.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCSectionCOFF.h"
27 #include "llvm/MC/MCSectionELF.h"
28 #include "llvm/MC/MCSectionGOFF.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCSectionWasm.h"
31 #include "llvm/MC/MCSectionXCOFF.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCSymbolCOFF.h"
35 #include "llvm/MC/MCSymbolELF.h"
36 #include "llvm/MC/MCSymbolGOFF.h"
37 #include "llvm/MC/MCSymbolMachO.h"
38 #include "llvm/MC/MCSymbolWasm.h"
39 #include "llvm/MC/MCSymbolXCOFF.h"
40 #include "llvm/MC/SectionKind.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <cassert>
50 #include <cstdlib>
51 #include <tuple>
52 #include <utility>
54 using namespace llvm;
56 static cl::opt<char*>
57 AsSecureLogFileName("as-secure-log-file-name",
58 cl::desc("As secure log file name (initialized from "
59 "AS_SECURE_LOG_FILE env variable)"),
60 cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
62 static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
63 std::vector<const MDNode *> &) {
64 SMD.print(nullptr, errs());
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)
71 : TT(TheTriple), SrcMgr(mgr), InlineSrcMgr(nullptr),
72 DiagHandler(defaultDiagHandler), MAI(mai), MRI(mri), MSTI(msti),
73 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 = AsSecureLogFileName;
79 if (SrcMgr && SrcMgr->getNumBuffers())
80 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
81 ->getBufferIdentifier());
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.");
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::UnknownObjectFormat:
107 report_fatal_error("Cannot initialize MC for unknown object file format.");
108 break;
112 MCContext::~MCContext() {
113 if (AutoReset)
114 reset();
116 // NOTE: The symbols are all allocated out of a bump pointer allocator,
117 // we don't need to free them here.
120 void MCContext::initInlineSourceManager() {
121 if (!InlineSrcMgr)
122 InlineSrcMgr.reset(new SourceMgr());
125 //===----------------------------------------------------------------------===//
126 // Module Lifetime Management
127 //===----------------------------------------------------------------------===//
129 void MCContext::reset() {
130 SrcMgr = nullptr;
131 InlineSrcMgr.reset();
132 LocInfos.clear();
133 DiagHandler = defaultDiagHandler;
135 // Call the destructors so the fragments are freed
136 COFFAllocator.DestroyAll();
137 ELFAllocator.DestroyAll();
138 GOFFAllocator.DestroyAll();
139 MachOAllocator.DestroyAll();
140 XCOFFAllocator.DestroyAll();
141 MCInstAllocator.DestroyAll();
143 MCSubtargetAllocator.DestroyAll();
144 InlineAsmUsedLabelNames.clear();
145 UsedNames.clear();
146 Symbols.clear();
147 Allocator.Reset();
148 Instances.clear();
149 CompilationDir.clear();
150 MainFileName.clear();
151 MCDwarfLineTablesCUMap.clear();
152 SectionsForRanges.clear();
153 MCGenDwarfLabelEntries.clear();
154 DwarfDebugFlags = StringRef();
155 DwarfCompileUnitID = 0;
156 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
158 CVContext.reset();
160 MachOUniquingMap.clear();
161 ELFUniquingMap.clear();
162 GOFFUniquingMap.clear();
163 COFFUniquingMap.clear();
164 WasmUniquingMap.clear();
165 XCOFFUniquingMap.clear();
167 ELFEntrySizeMap.clear();
168 ELFSeenGenericMergeableSections.clear();
170 NextID.clear();
171 AllowTemporaryLabels = true;
172 DwarfLocSeen = false;
173 GenDwarfForAssembly = false;
174 GenDwarfFileNumber = 0;
176 HadError = false;
179 //===----------------------------------------------------------------------===//
180 // MCInst Management
181 //===----------------------------------------------------------------------===//
183 MCInst *MCContext::createMCInst() {
184 return new (MCInstAllocator.Allocate()) MCInst;
187 //===----------------------------------------------------------------------===//
188 // Symbol Manipulation
189 //===----------------------------------------------------------------------===//
191 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
192 SmallString<128> NameSV;
193 StringRef NameRef = Name.toStringRef(NameSV);
195 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
197 MCSymbol *&Sym = Symbols[NameRef];
198 if (!Sym)
199 Sym = createSymbol(NameRef, false, false);
201 return Sym;
204 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
205 unsigned Idx) {
206 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
207 "$frame_escape_" + Twine(Idx));
210 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
211 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
212 "$parent_frame_offset");
215 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
216 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
217 FuncName);
220 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
221 bool IsTemporary) {
222 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
223 "MCSymbol classes must be trivially destructible");
224 static_assert(std::is_trivially_destructible<MCSymbolELF>(),
225 "MCSymbol classes must be trivially destructible");
226 static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
227 "MCSymbol classes must be trivially destructible");
228 static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
229 "MCSymbol classes must be trivially destructible");
230 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
231 "MCSymbol classes must be trivially destructible");
233 switch (getObjectFileType()) {
234 case MCContext::IsCOFF:
235 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
236 case MCContext::IsELF:
237 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
238 case MCContext::IsGOFF:
239 return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
240 case MCContext::IsMachO:
241 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
242 case MCContext::IsWasm:
243 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
244 case MCContext::IsXCOFF:
245 return createXCOFFSymbolImpl(Name, IsTemporary);
247 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
248 IsTemporary);
251 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
252 bool CanBeUnnamed) {
253 if (CanBeUnnamed && !UseNamesOnTempLabels)
254 return createSymbolImpl(nullptr, true);
256 // Determine whether this is a user written assembler temporary or normal
257 // label, if used.
258 bool IsTemporary = CanBeUnnamed;
259 if (AllowTemporaryLabels && !IsTemporary)
260 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
262 SmallString<128> NewName = Name;
263 bool AddSuffix = AlwaysAddSuffix;
264 unsigned &NextUniqueID = NextID[Name];
265 while (true) {
266 if (AddSuffix) {
267 NewName.resize(Name.size());
268 raw_svector_ostream(NewName) << NextUniqueID++;
270 auto NameEntry = UsedNames.insert(std::make_pair(NewName.str(), true));
271 if (NameEntry.second || !NameEntry.first->second) {
272 // Ok, we found a name.
273 // Mark it as used for a non-section symbol.
274 NameEntry.first->second = true;
275 // Have the MCSymbol object itself refer to the copy of the string that is
276 // embedded in the UsedNames entry.
277 return createSymbolImpl(&*NameEntry.first, IsTemporary);
279 assert(IsTemporary && "Cannot rename non-temporary symbols");
280 AddSuffix = true;
282 llvm_unreachable("Infinite loop");
285 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
286 SmallString<128> NameSV;
287 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
288 return createSymbol(NameSV, AlwaysAddSuffix, true);
291 MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {
292 SmallString<128> NameSV;
293 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
294 return createSymbol(NameSV, true, false);
297 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
298 SmallString<128> NameSV;
299 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
300 return createSymbol(NameSV, true, false);
303 MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
305 MCSymbol *MCContext::createNamedTempSymbol() {
306 return createNamedTempSymbol("tmp");
309 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
310 MCLabel *&Label = Instances[LocalLabelVal];
311 if (!Label)
312 Label = new (*this) MCLabel(0);
313 return Label->incInstance();
316 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
317 MCLabel *&Label = Instances[LocalLabelVal];
318 if (!Label)
319 Label = new (*this) MCLabel(0);
320 return Label->getInstance();
323 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
324 unsigned Instance) {
325 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
326 if (!Sym)
327 Sym = createNamedTempSymbol();
328 return Sym;
331 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
332 unsigned Instance = NextInstance(LocalLabelVal);
333 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
336 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
337 bool Before) {
338 unsigned Instance = GetInstance(LocalLabelVal);
339 if (!Before)
340 ++Instance;
341 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
344 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
345 SmallString<128> NameSV;
346 StringRef NameRef = Name.toStringRef(NameSV);
347 return Symbols.lookup(NameRef);
350 void MCContext::setSymbolValue(MCStreamer &Streamer,
351 StringRef Sym,
352 uint64_t Val) {
353 auto Symbol = getOrCreateSymbol(Sym);
354 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
357 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
358 InlineAsmUsedLabelNames[Sym->getName()] = Sym;
361 MCSymbolXCOFF *
362 MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
363 bool IsTemporary) {
364 if (!Name)
365 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
367 StringRef OriginalName = Name->first();
368 if (OriginalName.startswith("._Renamed..") ||
369 OriginalName.startswith("_Renamed.."))
370 reportError(SMLoc(), "invalid symbol name from source");
372 if (MAI->isValidUnquotedName(OriginalName))
373 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
375 // Now we have a name that contains invalid character(s) for XCOFF symbol.
376 // Let's replace with something valid, but save the original name so that
377 // we could still use the original name in the symbol table.
378 SmallString<128> InvalidName(OriginalName);
380 // If it's an entry point symbol, we will keep the '.'
381 // in front for the convention purpose. Otherwise, add "_Renamed.."
382 // as prefix to signal this is an renamed symbol.
383 const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.';
384 SmallString<128> ValidName =
385 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
387 // Append the hex values of '_' and invalid characters with "_Renamed..";
388 // at the same time replace invalid characters with '_'.
389 for (size_t I = 0; I < InvalidName.size(); ++I) {
390 if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
391 raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
392 InvalidName[I] = '_';
396 // Skip entry point symbol's '.' as we already have a '.' in front of
397 // "_Renamed".
398 if (IsEntryPoint)
399 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
400 else
401 ValidName.append(InvalidName);
403 auto NameEntry = UsedNames.insert(std::make_pair(ValidName.str(), true));
404 assert((NameEntry.second || !NameEntry.first->second) &&
405 "This name is used somewhere else.");
406 // Mark the name as used for a non-section symbol.
407 NameEntry.first->second = true;
408 // Have the MCSymbol object itself refer to the copy of the string
409 // that is embedded in the UsedNames entry.
410 MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this)
411 MCSymbolXCOFF(&*NameEntry.first, IsTemporary);
412 XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
413 return XSym;
416 //===----------------------------------------------------------------------===//
417 // Section Management
418 //===----------------------------------------------------------------------===//
420 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
421 unsigned TypeAndAttributes,
422 unsigned Reserved2, SectionKind Kind,
423 const char *BeginSymName) {
424 // We unique sections by their segment/section pair. The returned section
425 // may not have the same flags as the requested section, if so this should be
426 // diagnosed by the client as an error.
428 // Form the name to look up.
429 assert(Section.size() <= 16 && "section name is too long");
430 assert(!memchr(Section.data(), '\0', Section.size()) &&
431 "section name cannot contain NUL");
433 // Do the lookup, if we have a hit, return it.
434 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
435 if (!R.second)
436 return R.first->second;
438 MCSymbol *Begin = nullptr;
439 if (BeginSymName)
440 Begin = createTempSymbol(BeginSymName, false);
442 // Otherwise, return a new section.
443 StringRef Name = R.first->first();
444 R.first->second = new (MachOAllocator.Allocate())
445 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
446 TypeAndAttributes, Reserved2, Kind, Begin);
447 return R.first->second;
450 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
451 StringRef GroupName;
452 if (const MCSymbol *Group = Section->getGroup())
453 GroupName = Group->getName();
455 // This function is only used by .debug*, which should not have the
456 // SHF_LINK_ORDER flag.
457 unsigned UniqueID = Section->getUniqueID();
458 ELFUniquingMap.erase(
459 ELFSectionKey{Section->getName(), GroupName, "", UniqueID});
460 auto I = ELFUniquingMap
461 .insert(std::make_pair(
462 ELFSectionKey{Name, GroupName, "", UniqueID}, Section))
463 .first;
464 StringRef CachedName = I->first.SectionName;
465 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
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;
489 R->setBinding(ELF::STB_LOCAL);
490 R->setType(ELF::STT_SECTION);
492 auto *Ret = new (ELFAllocator.Allocate())
493 MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
494 R, LinkedToSym);
496 auto *F = new MCDataFragment();
497 Ret->getFragmentList().insert(Ret->begin(), F);
498 F->setParent(Ret);
499 R->setFragment(F);
501 return Ret;
504 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
505 unsigned Flags, unsigned EntrySize,
506 const MCSymbolELF *Group,
507 const MCSectionELF *RelInfoSection) {
508 StringMap<bool>::iterator I;
509 bool Inserted;
510 std::tie(I, Inserted) =
511 RelSecNames.insert(std::make_pair(Name.str(), true));
513 return createELFSectionImpl(
514 I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
515 true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
518 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
519 const Twine &Suffix, unsigned Type,
520 unsigned Flags,
521 unsigned EntrySize) {
522 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
523 /*IsComdat=*/true);
526 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
527 unsigned Flags, unsigned EntrySize,
528 const Twine &Group, bool IsComdat,
529 unsigned UniqueID,
530 const MCSymbolELF *LinkedToSym) {
531 MCSymbolELF *GroupSym = nullptr;
532 if (!Group.isTriviallyEmpty() && !Group.str().empty())
533 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
535 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
536 UniqueID, LinkedToSym);
539 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
540 unsigned Flags, unsigned EntrySize,
541 const MCSymbolELF *GroupSym,
542 bool IsComdat, unsigned UniqueID,
543 const MCSymbolELF *LinkedToSym) {
544 StringRef Group = "";
545 if (GroupSym)
546 Group = GroupSym->getName();
547 assert(!(LinkedToSym && LinkedToSym->getName().empty()));
548 // Do the lookup, if we have a hit, return it.
549 auto IterBool = ELFUniquingMap.insert(std::make_pair(
550 ELFSectionKey{Section.str(), Group,
551 LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
552 nullptr));
553 auto &Entry = *IterBool.first;
554 if (!IterBool.second)
555 return Entry.second;
557 StringRef CachedName = Entry.first.SectionName;
559 SectionKind Kind;
560 if (Flags & ELF::SHF_ARM_PURECODE)
561 Kind = SectionKind::getExecuteOnly();
562 else if (Flags & ELF::SHF_EXECINSTR)
563 Kind = SectionKind::getText();
564 else
565 Kind = SectionKind::getReadOnly();
567 MCSectionELF *Result =
568 createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
569 IsComdat, UniqueID, LinkedToSym);
570 Entry.second = Result;
572 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
573 Result->getUniqueID(), Result->getEntrySize());
575 return Result;
578 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
579 bool IsComdat) {
580 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
581 SectionKind::getReadOnly(), 4, Group, IsComdat,
582 MCSection::NonUniqueID, nullptr);
585 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
586 unsigned Flags, unsigned UniqueID,
587 unsigned EntrySize) {
588 bool IsMergeable = Flags & ELF::SHF_MERGE;
589 if (UniqueID == GenericSectionID)
590 ELFSeenGenericMergeableSections.insert(SectionName);
592 // For mergeable sections or non-mergeable sections with a generic mergeable
593 // section name we enter their Unique ID into the ELFEntrySizeMap so that
594 // compatible globals can be assigned to the same section.
595 if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
596 ELFEntrySizeMap.insert(std::make_pair(
597 ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
601 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
602 return SectionName.startswith(".rodata.str") ||
603 SectionName.startswith(".rodata.cst");
606 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
607 return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
608 ELFSeenGenericMergeableSections.count(SectionName);
611 Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName,
612 unsigned Flags,
613 unsigned EntrySize) {
614 auto I = ELFEntrySizeMap.find(
615 MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
616 return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None;
619 MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind) {
620 // Do the lookup. If we don't have a hit, return a new section.
621 auto &GOFFSection = GOFFUniquingMap[Section.str()];
622 if (!GOFFSection)
623 GOFFSection = new (GOFFAllocator.Allocate()) MCSectionGOFF(Section, Kind);
625 return GOFFSection;
628 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
629 unsigned Characteristics,
630 SectionKind Kind,
631 StringRef COMDATSymName, int Selection,
632 unsigned UniqueID,
633 const char *BeginSymName) {
634 MCSymbol *COMDATSymbol = nullptr;
635 if (!COMDATSymName.empty()) {
636 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
637 COMDATSymName = COMDATSymbol->getName();
641 // Do the lookup, if we have a hit, return it.
642 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
643 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
644 auto Iter = IterBool.first;
645 if (!IterBool.second)
646 return Iter->second;
648 MCSymbol *Begin = nullptr;
649 if (BeginSymName)
650 Begin = createTempSymbol(BeginSymName, false);
652 StringRef CachedName = Iter->first.SectionName;
653 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
654 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
656 Iter->second = Result;
657 return Result;
660 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
661 unsigned Characteristics,
662 SectionKind Kind,
663 const char *BeginSymName) {
664 return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
665 BeginSymName);
668 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
669 const MCSymbol *KeySym,
670 unsigned UniqueID) {
671 // Return the normal section if we don't have to be associative or unique.
672 if (!KeySym && UniqueID == GenericSectionID)
673 return Sec;
675 // If we have a key symbol, make an associative section with the same name and
676 // kind as the normal section.
677 unsigned Characteristics = Sec->getCharacteristics();
678 if (KeySym) {
679 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
680 return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
681 KeySym->getName(),
682 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
685 return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
686 UniqueID);
689 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
690 unsigned Flags, const Twine &Group,
691 unsigned UniqueID,
692 const char *BeginSymName) {
693 MCSymbolWasm *GroupSym = nullptr;
694 if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
695 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
696 GroupSym->setComdat(true);
699 return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
702 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
703 unsigned Flags,
704 const MCSymbolWasm *GroupSym,
705 unsigned UniqueID,
706 const char *BeginSymName) {
707 StringRef Group = "";
708 if (GroupSym)
709 Group = GroupSym->getName();
710 // Do the lookup, if we have a hit, return it.
711 auto IterBool = WasmUniquingMap.insert(
712 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
713 auto &Entry = *IterBool.first;
714 if (!IterBool.second)
715 return Entry.second;
717 StringRef CachedName = Entry.first.SectionName;
719 MCSymbol *Begin = createSymbol(CachedName, true, false);
720 Symbols[Begin->getName()] = Begin;
721 cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
723 MCSectionWasm *Result = new (WasmAllocator.Allocate())
724 MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
725 Entry.second = Result;
727 auto *F = new MCDataFragment();
728 Result->getFragmentList().insert(Result->begin(), F);
729 F->setParent(Result);
730 Begin->setFragment(F);
732 return Result;
735 MCSectionXCOFF *MCContext::getXCOFFSection(
736 StringRef Section, SectionKind Kind,
737 Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
738 const char *BeginSymName,
739 Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
740 bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue();
741 assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!");
743 // Do the lookup. If we have a hit, return it.
744 auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
745 IsDwarfSec
746 ? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue())
747 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
748 nullptr));
749 auto &Entry = *IterBool.first;
750 if (!IterBool.second) {
751 MCSectionXCOFF *ExistedEntry = Entry.second;
752 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
753 report_fatal_error("section's multiply symbols policy does not match");
755 return ExistedEntry;
758 // Otherwise, return a new section.
759 StringRef CachedName = Entry.first.SectionName;
760 MCSymbolXCOFF *QualName = nullptr;
761 // Debug section don't have storage class attribute.
762 if (IsDwarfSec)
763 QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
764 else
765 QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
766 CachedName + "[" +
767 XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
769 MCSymbol *Begin = nullptr;
770 if (BeginSymName)
771 Begin = createTempSymbol(BeginSymName, false);
773 // QualName->getUnqualifiedName() and CachedName are the same except when
774 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
775 MCSectionXCOFF *Result = nullptr;
776 if (IsDwarfSec)
777 Result = new (XCOFFAllocator.Allocate())
778 MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName,
779 DwarfSectionSubtypeFlags.getValue(), Begin, CachedName,
780 MultiSymbolsAllowed);
781 else
782 Result = new (XCOFFAllocator.Allocate())
783 MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
784 CsectProp->Type, Kind, QualName, Begin, CachedName,
785 MultiSymbolsAllowed);
787 Entry.second = Result;
789 auto *F = new MCDataFragment();
790 Result->getFragmentList().insert(Result->begin(), F);
791 F->setParent(Result);
793 if (Begin)
794 Begin->setFragment(F);
796 return Result;
799 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
800 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
803 void MCContext::addDebugPrefixMapEntry(const std::string &From,
804 const std::string &To) {
805 DebugPrefixMap.insert(std::make_pair(From, To));
808 void MCContext::RemapDebugPaths() {
809 const auto &DebugPrefixMap = this->DebugPrefixMap;
810 if (DebugPrefixMap.empty())
811 return;
813 const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
814 SmallString<256> P(Path);
815 for (const auto &Entry : DebugPrefixMap) {
816 if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second)) {
817 Path = P.str().str();
818 break;
823 // Remap compilation directory.
824 std::string CompDir = std::string(CompilationDir.str());
825 RemapDebugPath(CompDir);
826 CompilationDir = CompDir;
828 // Remap MCDwarfDirs in all compilation units.
829 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
830 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
831 RemapDebugPath(Dir);
834 //===----------------------------------------------------------------------===//
835 // Dwarf Management
836 //===----------------------------------------------------------------------===//
838 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
839 // MCDwarf needs the root file as well as the compilation directory.
840 // If we find a '.file 0' directive that will supersede these values.
841 Optional<MD5::MD5Result> Cksum;
842 if (getDwarfVersion() >= 5) {
843 MD5 Hash;
844 MD5::MD5Result Sum;
845 Hash.update(Buffer);
846 Hash.final(Sum);
847 Cksum = Sum;
849 // Canonicalize the root filename. It cannot be empty, and should not
850 // repeat the compilation dir.
851 // The MCContext ctor initializes MainFileName to the name associated with
852 // the SrcMgr's main file ID, which might be the same as InputFileName (and
853 // possibly include directory components).
854 // Or, MainFileName might have been overridden by a -main-file-name option,
855 // which is supposed to be just a base filename with no directory component.
856 // So, if the InputFileName and MainFileName are not equal, assume
857 // MainFileName is a substitute basename and replace the last component.
858 SmallString<1024> FileNameBuf = InputFileName;
859 if (FileNameBuf.empty() || FileNameBuf == "-")
860 FileNameBuf = "<stdin>";
861 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
862 llvm::sys::path::remove_filename(FileNameBuf);
863 llvm::sys::path::append(FileNameBuf, getMainFileName());
865 StringRef FileName = FileNameBuf;
866 if (FileName.consume_front(getCompilationDir()))
867 if (llvm::sys::path::is_separator(FileName.front()))
868 FileName = FileName.drop_front();
869 assert(!FileName.empty());
870 setMCLineTableRootFile(
871 /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
874 /// getDwarfFile - takes a file name and number to place in the dwarf file and
875 /// directory tables. If the file number has already been allocated it is an
876 /// error and zero is returned and the client reports the error, else the
877 /// allocated file number is returned. The file numbers may be in any order.
878 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
879 StringRef FileName,
880 unsigned FileNumber,
881 Optional<MD5::MD5Result> Checksum,
882 Optional<StringRef> Source,
883 unsigned CUID) {
884 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
885 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
886 FileNumber);
889 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
890 /// currently is assigned and false otherwise.
891 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
892 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
893 if (FileNumber == 0)
894 return getDwarfVersion() >= 5;
895 if (FileNumber >= LineTable.getMCDwarfFiles().size())
896 return false;
898 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
901 /// Remove empty sections from SectionsForRanges, to avoid generating
902 /// useless debug info for them.
903 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
904 SectionsForRanges.remove_if(
905 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
908 CodeViewContext &MCContext::getCVContext() {
909 if (!CVContext.get())
910 CVContext.reset(new CodeViewContext);
911 return *CVContext.get();
914 //===----------------------------------------------------------------------===//
915 // Error Reporting
916 //===----------------------------------------------------------------------===//
918 void MCContext::diagnose(const SMDiagnostic &SMD) {
919 assert(DiagHandler && "MCContext::DiagHandler is not set");
920 bool UseInlineSrcMgr = false;
921 const SourceMgr *SMP = nullptr;
922 if (SrcMgr) {
923 SMP = SrcMgr;
924 } else if (InlineSrcMgr) {
925 SMP = InlineSrcMgr.get();
926 UseInlineSrcMgr = true;
927 } else
928 llvm_unreachable("Either SourceMgr should be available");
929 DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
932 void MCContext::reportCommon(
933 SMLoc Loc,
934 std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
935 // * MCContext::SrcMgr is null when the MC layer emits machine code for input
936 // other than assembly file, say, for .c/.cpp/.ll/.bc.
937 // * MCContext::InlineSrcMgr is null when the inline asm is not used.
938 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
939 // and MCContext::InlineSrcMgr are null.
940 SourceMgr SM;
941 const SourceMgr *SMP = &SM;
942 bool UseInlineSrcMgr = false;
944 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
945 // For MC-only execution, only SrcMgr is used;
946 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is
947 // inline asm in the IR.
948 if (Loc.isValid()) {
949 if (SrcMgr) {
950 SMP = SrcMgr;
951 } else if (InlineSrcMgr) {
952 SMP = InlineSrcMgr.get();
953 UseInlineSrcMgr = true;
954 } else
955 llvm_unreachable("Either SourceMgr should be available");
958 SMDiagnostic D;
959 GetMessage(D, SMP);
960 DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
963 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
964 HadError = true;
965 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
966 D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
970 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
971 if (TargetOptions && TargetOptions->MCNoWarn)
972 return;
973 if (TargetOptions && TargetOptions->MCFatalWarnings) {
974 reportError(Loc, Msg);
975 } else {
976 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
977 D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
982 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
983 reportError(Loc, Msg);
985 // If we reached here, we are failing ungracefully. Run the interrupt handlers
986 // to make sure any special cleanups get done, in particular that we remove
987 // files registered with RemoveFileOnSignal.
988 sys::RunInterruptHandlers();
989 exit(1);