1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
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
, 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
: "";
79 if (SrcMgr
&& SrcMgr
->getNumBuffers())
80 MainFileName
= std::string(SrcMgr
->getMemoryBuffer(SrcMgr
->getMainFileID())
81 ->getBufferIdentifier());
83 switch (TheTriple
.getObjectFormat()) {
88 if (!TheTriple
.isOSWindows() && !TheTriple
.isUEFI())
90 "Cannot initialize MC for non-Windows COFF object files.");
106 case Triple::DXContainer
:
112 case Triple::UnknownObjectFormat
:
113 report_fatal_error("Cannot initialize MC for unknown object file format.");
118 MCContext::~MCContext() {
122 // NOTE: The symbols are all allocated out of a bump pointer allocator,
123 // we don't need to free them here.
126 void MCContext::initInlineSourceManager() {
128 InlineSrcMgr
.reset(new SourceMgr());
131 //===----------------------------------------------------------------------===//
132 // Module Lifetime Management
133 //===----------------------------------------------------------------------===//
135 void MCContext::reset() {
137 InlineSrcMgr
.reset();
139 DiagHandler
= defaultDiagHandler
;
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();
152 MCSubtargetAllocator
.DestroyAll();
153 InlineAsmUsedLabelNames
.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);
169 MachOUniquingMap
.clear();
170 ELFUniquingMap
.clear();
171 GOFFUniquingMap
.clear();
172 COFFUniquingMap
.clear();
173 WasmUniquingMap
.clear();
174 XCOFFUniquingMap
.clear();
175 DXCUniquingMap
.clear();
177 ELFEntrySizeMap
.clear();
178 ELFSeenGenericMergeableSections
.clear();
181 AllowTemporaryLabels
= true;
182 DwarfLocSeen
= false;
183 GenDwarfForAssembly
= false;
184 GenDwarfFileNumber
= 0;
189 //===----------------------------------------------------------------------===//
191 //===----------------------------------------------------------------------===//
193 MCInst
*MCContext::createMCInst() {
194 return new (MCInstAllocator
.Allocate()) MCInst
;
197 //===----------------------------------------------------------------------===//
198 // Symbol Manipulation
199 //===----------------------------------------------------------------------===//
201 MCSymbol
*MCContext::getOrCreateSymbol(const Twine
&Name
) {
202 SmallString
<128> NameSV
;
203 StringRef NameRef
= Name
.toStringRef(NameSV
);
205 assert(!NameRef
.empty() && "Normal symbols cannot be unnamed!");
207 MCSymbol
*&Sym
= Symbols
[NameRef
];
209 Sym
= createSymbol(NameRef
, false, false);
214 MCSymbol
*MCContext::getOrCreateFrameAllocSymbol(const Twine
&FuncName
,
216 return getOrCreateSymbol(MAI
->getPrivateGlobalPrefix() + FuncName
+
217 "$frame_escape_" + Twine(Idx
));
220 MCSymbol
*MCContext::getOrCreateParentFrameOffsetSymbol(const Twine
&FuncName
) {
221 return getOrCreateSymbol(MAI
->getPrivateGlobalPrefix() + FuncName
+
222 "$parent_frame_offset");
225 MCSymbol
*MCContext::getOrCreateLSDASymbol(const Twine
&FuncName
) {
226 return getOrCreateSymbol(MAI
->getPrivateGlobalPrefix() + "__ehtable$" +
230 MCSymbol
*MCContext::createSymbolImpl(const StringMapEntry
<bool> *Name
,
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");
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
:
258 case MCContext::IsSPIRV
:
259 return new (Name
, *this)
260 MCSymbol(MCSymbol::SymbolKindUnset
, Name
, IsTemporary
);
262 return new (Name
, *this)
263 MCSymbol(MCSymbol::SymbolKindUnset
, Name
, IsTemporary
);
266 MCSymbol
*MCContext::createSymbol(StringRef Name
, bool AlwaysAddSuffix
,
268 if (CanBeUnnamed
&& !UseNamesOnTempLabels
)
269 return createSymbolImpl(nullptr, true);
271 // Determine whether this is a user written assembler temporary or normal
273 bool IsTemporary
= CanBeUnnamed
;
274 if (AllowTemporaryLabels
&& !IsTemporary
)
275 IsTemporary
= Name
.startswith(MAI
->getPrivateGlobalPrefix());
277 SmallString
<128> NewName
= Name
;
278 bool AddSuffix
= AlwaysAddSuffix
;
279 unsigned &NextUniqueID
= NextID
[Name
];
282 NewName
.resize(Name
.size());
283 raw_svector_ostream(NewName
) << NextUniqueID
++;
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
);
294 assert(IsTemporary
&& "Cannot rename non-temporary symbols");
297 llvm_unreachable("Infinite loop");
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);
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);
312 MCSymbol
*MCContext::createLinkerPrivateTempSymbol() {
313 return createLinkerPrivateSymbol("tmp");
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);
322 MCSymbol
*MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
324 MCSymbol
*MCContext::createNamedTempSymbol() {
325 return createNamedTempSymbol("tmp");
328 unsigned MCContext::NextInstance(unsigned LocalLabelVal
) {
329 MCLabel
*&Label
= Instances
[LocalLabelVal
];
331 Label
= new (*this) MCLabel(0);
332 return Label
->incInstance();
335 unsigned MCContext::GetInstance(unsigned LocalLabelVal
) {
336 MCLabel
*&Label
= Instances
[LocalLabelVal
];
338 Label
= new (*this) MCLabel(0);
339 return Label
->getInstance();
342 MCSymbol
*MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal
,
344 MCSymbol
*&Sym
= LocalSymbols
[std::make_pair(LocalLabelVal
, Instance
)];
346 Sym
= createNamedTempSymbol();
350 MCSymbol
*MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal
) {
351 unsigned Instance
= NextInstance(LocalLabelVal
);
352 return getOrCreateDirectionalLocalSymbol(LocalLabelVal
, Instance
);
355 MCSymbol
*MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal
,
357 unsigned Instance
= GetInstance(LocalLabelVal
);
360 return getOrCreateDirectionalLocalSymbol(LocalLabelVal
, Instance
);
363 MCSymbol
*MCContext::lookupSymbol(const Twine
&Name
) const {
364 SmallString
<128> NameSV
;
365 StringRef NameRef
= Name
.toStringRef(NameSV
);
366 return Symbols
.lookup(NameRef
);
369 void MCContext::setSymbolValue(MCStreamer
&Streamer
, const Twine
&Sym
,
371 auto Symbol
= getOrCreateSymbol(Sym
);
372 Streamer
.emitAssignment(Symbol
, MCConstantExpr::create(Val
, *this));
375 void MCContext::registerInlineAsmLabel(MCSymbol
*Sym
) {
376 InlineAsmUsedLabelNames
[Sym
->getName()] = Sym
;
380 MCContext::createXCOFFSymbolImpl(const StringMapEntry
<bool> *Name
,
383 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary
);
385 StringRef OriginalName
= Name
->first();
386 if (OriginalName
.startswith("._Renamed..") ||
387 OriginalName
.startswith("_Renamed.."))
388 reportError(SMLoc(), "invalid symbol name from source");
390 if (MAI
->isValidUnquotedName(OriginalName
))
391 return new (Name
, *this) MCSymbolXCOFF(Name
, IsTemporary
);
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
);
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..");
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
] = '_';
414 // Skip entry point symbol's '.' as we already have a '.' in front of
417 ValidName
.append(InvalidName
.substr(1, InvalidName
.size() - 1));
419 ValidName
.append(InvalidName
);
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
));
434 //===----------------------------------------------------------------------===//
435 // Section Management
436 //===----------------------------------------------------------------------===//
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.
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");
451 // Do the lookup, if we have a hit, return it.
452 auto R
= MachOUniquingMap
.try_emplace((Segment
+ Twine(',') + Section
).str());
454 return R
.first
->second
;
456 MCSymbol
*Begin
= nullptr;
458 Begin
= createTempSymbol(BeginSymName
, false);
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
;
468 MCSectionELF
*MCContext::createELFSectionImpl(StringRef Section
, unsigned Type
,
469 unsigned Flags
, SectionKind K
,
471 const MCSymbolELF
*Group
,
472 bool Comdat
, unsigned UniqueID
,
473 const MCSymbolELF
*LinkedToSym
) {
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
);
484 auto NameIter
= UsedNames
.insert(std::make_pair(Section
, false)).first
;
485 R
= new (&*NameIter
, *this) MCSymbolELF(&*NameIter
, /*isTemporary*/ false);
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
,
496 auto *F
= new MCDataFragment();
497 Ret
->getFragmentList().insert(Ret
->begin(), F
);
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
;
510 std::tie(I
, Inserted
) = RelSecNames
.insert(std::make_pair(Name
.str(), true));
512 return createELFSectionImpl(
513 I
->getKey(), Type
, Flags
, SectionKind::getReadOnly(), EntrySize
, Group
,
514 true, true, cast
<MCSymbolELF
>(RelInfoSection
->getBeginSymbol()));
517 MCSectionELF
*MCContext::getELFNamedSection(const Twine
&Prefix
,
518 const Twine
&Suffix
, unsigned Type
,
520 unsigned EntrySize
) {
521 return getELFSection(Prefix
+ "." + Suffix
, Type
, Flags
, EntrySize
, Suffix
,
525 MCSectionELF
*MCContext::getELFSection(const Twine
&Section
, unsigned Type
,
526 unsigned Flags
, unsigned EntrySize
,
527 const Twine
&Group
, bool IsComdat
,
529 const MCSymbolELF
*LinkedToSym
) {
530 MCSymbolELF
*GroupSym
= nullptr;
531 if (!Group
.isTriviallyEmpty() && !Group
.str().empty())
532 GroupSym
= cast
<MCSymbolELF
>(getOrCreateSymbol(Group
));
534 return getELFSection(Section
, Type
, Flags
, EntrySize
, GroupSym
, IsComdat
,
535 UniqueID
, LinkedToSym
);
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
= "";
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
},
552 auto &Entry
= *IterBool
.first
;
553 if (!IterBool
.second
)
556 StringRef CachedName
= Entry
.first
.SectionName
;
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();
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
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::getReadOnly());
597 MCSectionELF
*Result
=
598 createELFSectionImpl(CachedName
, Type
, Flags
, Kind
, EntrySize
, GroupSym
,
599 IsComdat
, UniqueID
, LinkedToSym
);
600 Entry
.second
= Result
;
602 recordELFMergeableSectionInfo(Result
->getName(), Result
->getFlags(),
603 Result
->getUniqueID(), Result
->getEntrySize());
608 MCSectionELF
*MCContext::createELFGroupSection(const MCSymbolELF
*Group
,
610 return createELFSectionImpl(".group", ELF::SHT_GROUP
, 0,
611 SectionKind::getReadOnly(), 4, Group
, IsComdat
,
612 MCSection::NonUniqueID
, nullptr);
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
);
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
));
631 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName
) {
632 return SectionName
.startswith(".rodata.str") ||
633 SectionName
.startswith(".rodata.cst");
636 bool MCContext::isELFGenericMergeableSection(StringRef SectionName
) {
637 return isELFImplicitMergeableSectionNamePrefix(SectionName
) ||
638 ELFSeenGenericMergeableSections
.count(SectionName
);
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
)
650 MCSectionGOFF
*MCContext::getGOFFSection(StringRef Section
, SectionKind Kind
,
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()];
656 GOFFSection
= new (GOFFAllocator
.Allocate())
657 MCSectionGOFF(Section
, Kind
, Parent
, SubsectionId
);
662 MCSectionCOFF
*MCContext::getCOFFSection(StringRef Section
,
663 unsigned Characteristics
,
665 StringRef COMDATSymName
, int Selection
,
667 const char *BeginSymName
) {
668 MCSymbol
*COMDATSymbol
= nullptr;
669 if (!COMDATSymName
.empty()) {
670 COMDATSymbol
= getOrCreateSymbol(COMDATSymName
);
671 COMDATSymName
= COMDATSymbol
->getName();
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
)
681 MCSymbol
*Begin
= nullptr;
683 Begin
= createTempSymbol(BeginSymName
, false);
685 StringRef CachedName
= Iter
->first
.SectionName
;
686 MCSectionCOFF
*Result
= new (COFFAllocator
.Allocate()) MCSectionCOFF(
687 CachedName
, Characteristics
, COMDATSymbol
, Selection
, Kind
, Begin
);
689 Iter
->second
= Result
;
693 MCSectionCOFF
*MCContext::getCOFFSection(StringRef Section
,
694 unsigned Characteristics
,
696 const char *BeginSymName
) {
697 return getCOFFSection(Section
, Characteristics
, Kind
, "", 0, GenericSectionID
,
701 MCSectionCOFF
*MCContext::getAssociativeCOFFSection(MCSectionCOFF
*Sec
,
702 const MCSymbol
*KeySym
,
704 // Return the normal section if we don't have to be associative or unique.
705 if (!KeySym
&& UniqueID
== GenericSectionID
)
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();
712 Characteristics
|= COFF::IMAGE_SCN_LNK_COMDAT
;
713 return getCOFFSection(Sec
->getName(), Characteristics
, Sec
->getKind(),
715 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
, UniqueID
);
718 return getCOFFSection(Sec
->getName(), Characteristics
, Sec
->getKind(), "", 0,
722 MCSectionWasm
*MCContext::getWasmSection(const Twine
&Section
, SectionKind K
,
723 unsigned Flags
, const Twine
&Group
,
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);
732 return getWasmSection(Section
, K
, Flags
, GroupSym
, UniqueID
, BeginSymName
);
735 MCSectionWasm
*MCContext::getWasmSection(const Twine
&Section
, SectionKind Kind
,
737 const MCSymbolWasm
*GroupSym
,
739 const char *BeginSymName
) {
740 StringRef Group
= "";
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
)
750 StringRef CachedName
= Entry
.first
.SectionName
;
752 MCSymbol
*Begin
= createSymbol(CachedName
, true, false);
753 Symbols
[Begin
->getName()] = Begin
;
754 cast
<MCSymbolWasm
>(Begin
)->setType(wasm::WASM_SYMBOL_TYPE_SECTION
);
756 MCSectionWasm
*Result
= new (WasmAllocator
.Allocate())
757 MCSectionWasm(CachedName
, Kind
, Flags
, GroupSym
, UniqueID
, Begin
);
758 Entry
.second
= Result
;
760 auto *F
= new MCDataFragment();
761 Result
->getFragmentList().insert(Result
->begin(), F
);
762 F
->setParent(Result
);
763 Begin
->setFragment(F
);
768 bool MCContext::hasXCOFFSection(StringRef Section
,
769 XCOFF::CsectProperties CsectProp
) const {
770 return XCOFFUniquingMap
.count(
771 XCOFFSectionKey(Section
.str(), CsectProp
.MappingClass
)) != 0;
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!");
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
),
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");
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.
801 QualName
= cast
<MCSymbolXCOFF
>(getOrCreateSymbol(CachedName
));
803 QualName
= cast
<MCSymbolXCOFF
>(getOrCreateSymbol(
805 XCOFF::getMappingClassString(CsectProp
->MappingClass
) + "]"));
807 MCSymbol
*Begin
= nullptr;
809 Begin
= createTempSymbol(BeginSymName
, false);
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;
815 Result
= new (XCOFFAllocator
.Allocate()) MCSectionXCOFF(
816 QualName
->getUnqualifiedName(), Kind
, QualName
,
817 *DwarfSectionSubtypeFlags
, Begin
, CachedName
, MultiSymbolsAllowed
);
819 Result
= new (XCOFFAllocator
.Allocate())
820 MCSectionXCOFF(QualName
->getUnqualifiedName(), CsectProp
->MappingClass
,
821 CsectProp
->Type
, Kind
, QualName
, Begin
, CachedName
,
822 MultiSymbolsAllowed
);
824 Entry
.second
= Result
;
826 auto *F
= new MCDataFragment();
827 Result
->getFragmentList().insert(Result
->begin(), F
);
828 F
->setParent(Result
);
831 Begin
->setFragment(F
);
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
);
844 MCSectionSPIRV
*MCContext::getSPIRVSection() {
845 MCSymbol
*Begin
= nullptr;
846 MCSectionSPIRV
*Result
= new (SPIRVAllocator
.Allocate())
847 MCSectionSPIRV(SectionKind::getText(), Begin
);
849 auto *F
= new MCDataFragment();
850 Result
->getFragmentList().insert(Result
->begin(), F
);
851 F
->setParent(Result
);
856 MCSectionDXContainer
*MCContext::getDXContainerSection(StringRef Section
,
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
;
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();
869 new (DXCAllocator
.Allocate()) MCSectionDXContainer(Name
, K
, nullptr);
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
);
876 return MapIt
->second
;
879 MCSubtargetInfo
&MCContext::getSubtargetCopy(const MCSubtargetInfo
&STI
) {
880 return *new (MCSubtargetAllocator
.Allocate()) MCSubtargetInfo(STI
);
883 void MCContext::addDebugPrefixMapEntry(const std::string
&From
,
884 const std::string
&To
) {
885 DebugPrefixMap
.emplace_back(From
, To
);
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
))
894 void MCContext::RemapDebugPaths() {
895 const auto &DebugPrefixMap
= this->DebugPrefixMap
;
896 if (DebugPrefixMap
.empty())
899 // Remap compilation directory.
900 remapDebugPath(CompilationDir
);
902 // Remap MCDwarfDirs and RootFile.Name in all compilation units.
904 for (auto &CUIDTablePair
: MCDwarfLineTablesCUMap
) {
905 for (auto &Dir
: CUIDTablePair
.second
.getMCDwarfDirs()) {
908 Dir
= std::string(P
);
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
;
915 CUIDTablePair
.second
.getRootFile().Name
= std::string(P
);
919 //===----------------------------------------------------------------------===//
921 //===----------------------------------------------------------------------===//
923 EmitDwarfUnwindType
MCContext::emitDwarfUnwindInfo() const {
925 return EmitDwarfUnwindType::Default
;
926 return TargetOptions
->EmitDwarfUnwind
;
929 bool MCContext::emitCompactUnwindNonCanonical() const {
931 return TargetOptions
->EmitCompactUnwindNonCanonical
;
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) {
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());
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
);
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.
976 MCContext::getDwarfFile(StringRef Directory
, StringRef FileName
,
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
,
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
);
990 return getDwarfVersion() >= 5;
991 if (FileNumber
>= LineTable
.getMCDwarfFiles().size())
994 return !LineTable
.getMCDwarfFiles()[FileNumber
].Name
.empty();
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
); });
1004 CodeViewContext
&MCContext::getCVContext() {
1006 CVContext
.reset(new CodeViewContext
);
1010 //===----------------------------------------------------------------------===//
1012 //===----------------------------------------------------------------------===//
1014 void MCContext::diagnose(const SMDiagnostic
&SMD
) {
1015 assert(DiagHandler
&& "MCContext::DiagHandler is not set");
1016 bool UseInlineSrcMgr
= false;
1017 const SourceMgr
*SMP
= nullptr;
1020 } else if (InlineSrcMgr
) {
1021 SMP
= InlineSrcMgr
.get();
1022 UseInlineSrcMgr
= true;
1024 llvm_unreachable("Either SourceMgr should be available");
1025 DiagHandler(SMD
, UseInlineSrcMgr
, *SMP
, LocInfos
);
1028 void MCContext::reportCommon(
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.
1037 const SourceMgr
*SMP
= &SM
;
1038 bool UseInlineSrcMgr
= false;
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()) {
1047 } else if (InlineSrcMgr
) {
1048 SMP
= InlineSrcMgr
.get();
1049 UseInlineSrcMgr
= true;
1051 llvm_unreachable("Either SourceMgr should be available");
1056 DiagHandler(D
, UseInlineSrcMgr
, *SMP
, LocInfos
);
1059 void MCContext::reportError(SMLoc Loc
, const Twine
&Msg
) {
1061 reportCommon(Loc
, [&](SMDiagnostic
&D
, const SourceMgr
*SMP
) {
1062 D
= SMP
->GetMessage(Loc
, SourceMgr::DK_Error
, Msg
);
1066 void MCContext::reportWarning(SMLoc Loc
, const Twine
&Msg
) {
1067 if (TargetOptions
&& TargetOptions
->MCNoWarn
)
1069 if (TargetOptions
&& TargetOptions
->MCFatalWarnings
) {
1070 reportError(Loc
, Msg
);
1072 reportCommon(Loc
, [&](SMDiagnostic
&D
, const SourceMgr
*SMP
) {
1073 D
= SMP
->GetMessage(Loc
, SourceMgr::DK_Warning
, Msg
);