LLVM 23.0.0git
MCContext.cpp
Go to the documentation of this file.
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"
12#include "llvm/ADT/StringMap.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.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/MCInst.h"
25#include "llvm/MC/MCLabel.h"
34#include "llvm/MC/MCStreamer.h"
36#include "llvm/MC/MCSymbol.h"
38#include "llvm/MC/MCSymbolELF.h"
44#include "llvm/MC/SectionKind.h"
48#include "llvm/Support/Path.h"
49#include "llvm/Support/SMLoc.h"
52#include <cassert>
53#include <cstdlib>
54#include <optional>
55#include <tuple>
56#include <utility>
57
58using namespace llvm;
59
60static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
61 std::vector<const MDNode *> &) {
62 SMD.print(nullptr, errs());
63}
64
65MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo &mai,
66 const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
67 const SourceMgr *mgr, bool DoAutoReset,
68 StringRef Swift5ReflSegmentName)
69 : Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),
70 SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),
71 MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator),
72 InlineAsmUsedLabelNames(Allocator),
73 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
74 AutoReset(DoAutoReset) {
76 SaveTempLabels = TO.MCSaveTempLabels;
77 if (SaveTempLabels)
79 SecureLogFile = TO.AsSecureLogFile;
80
81 if (SrcMgr && SrcMgr->getNumBuffers())
82 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
83 ->getBufferIdentifier());
84
85 switch (TheTriple.getObjectFormat()) {
86 case Triple::MachO:
87 Env = IsMachO;
88 break;
89 case Triple::COFF:
90 if (!TheTriple.isOSWindows() && !TheTriple.isUEFI()) {
92 "cannot initialize MC for non-Windows COFF object files");
93 }
94
95 Env = IsCOFF;
96 break;
97 case Triple::ELF:
98 Env = IsELF;
99 break;
100 case Triple::Wasm:
101 Env = IsWasm;
102 break;
103 case Triple::XCOFF:
104 Env = IsXCOFF;
105 break;
106 case Triple::GOFF:
107 Env = IsGOFF;
108 break;
110 Env = IsDXContainer;
111 break;
112 case Triple::SPIRV:
113 Env = IsSPIRV;
114 break;
116 report_fatal_error("Cannot initialize MC for unknown object file format.");
117 break;
118 }
119}
120
122 return MAI.getTargetOptions();
123}
124
126 if (AutoReset)
127 reset();
128
129 // NOTE: The symbols are all allocated out of a bump pointer allocator,
130 // we don't need to free them here.
131}
132
134 if (!InlineSrcMgr)
135 InlineSrcMgr.reset(new SourceMgr());
136}
137
138//===----------------------------------------------------------------------===//
139// Module Lifetime Management
140//===----------------------------------------------------------------------===//
141
143 SrcMgr = nullptr;
144 InlineSrcMgr.reset();
145 LocInfos.clear();
146 DiagHandler = defaultDiagHandler;
147
148 // Call the destructors so the fragments are freed
149 COFFAllocator.DestroyAll();
150 DXCAllocator.DestroyAll();
151 ELFAllocator.DestroyAll();
152 GOFFAllocator.DestroyAll();
153 MachOAllocator.DestroyAll();
154 WasmAllocator.DestroyAll();
155 XCOFFAllocator.DestroyAll();
156 MCInstAllocator.DestroyAll();
157 SPIRVAllocator.DestroyAll();
158 WasmSignatureAllocator.DestroyAll();
159
160 CVContext.reset();
161
162 MCSubtargetAllocator.DestroyAll();
163 InlineAsmUsedLabelNames.clear();
164 Symbols.clear();
165 Allocator.Reset();
166 Instances.clear();
167 CompilationDir.clear();
168 MainFileName.clear();
169 MCDwarfLineTablesCUMap.clear();
170 SectionsForRanges.clear();
171 MCGenDwarfLabelEntries.clear();
172 DwarfDebugFlags = StringRef();
173 DwarfCompileUnitID = 0;
174 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
175
176 MachOUniquingMap.clear();
177 ELFUniquingMap.clear();
178 GOFFUniquingMap.clear();
179 COFFUniquingMap.clear();
180 WasmUniquingMap.clear();
181 XCOFFUniquingMap.clear();
182 DXCUniquingMap.clear();
183
184 RelSecNames.clear();
185 MacroMap.clear();
186 ELFEntrySizeMap.clear();
187 ELFSeenGenericMergeableSections.clear();
188
189 DwarfLocSeen = false;
190 GenDwarfForAssembly = false;
191 GenDwarfFileNumber = 0;
192
193 HadError = false;
194}
195
196//===----------------------------------------------------------------------===//
197// MCInst Management
198//===----------------------------------------------------------------------===//
199
201 return new (MCInstAllocator.Allocate()) MCInst;
202}
203
204//===----------------------------------------------------------------------===//
205// Symbol Manipulation
206//===----------------------------------------------------------------------===//
207
209 SmallString<128> NameSV;
210 StringRef NameRef = Name.toStringRef(NameSV);
211
212 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
213
214 MCSymbolTableEntry &Entry = getSymbolTableEntry(NameRef);
215 if (!Entry.second.Symbol) {
216 bool IsRenamable = NameRef.starts_with(MAI.getInternalSymbolPrefix());
217 bool IsTemporary = IsRenamable && !SaveTempLabels;
218 if (!Entry.second.Used) {
219 Entry.second.Used = true;
220 Entry.second.Symbol = createSymbolImpl(&Entry, IsTemporary);
221 } else {
222 assert(IsRenamable && "cannot rename non-private symbol");
223 // Slow path: we need to rename a temp symbol from the user.
224 Entry.second.Symbol = createRenamableSymbol(NameRef, false, IsTemporary);
225 }
226 }
227
228 return Entry.second.Symbol;
229}
230
233 StringRef NameRef = Name.toStringRef(SV);
234 if (NameRef.contains('\\')) {
235 SV = NameRef;
236 size_t S = 0;
237 // Support escaped \\ and \" as in GNU Assembler. GAS issues a warning for
238 // other characters following \\, which we do not implement due to code
239 // structure.
240 for (size_t I = 0, E = SV.size(); I != E; ++I) {
241 char C = SV[I];
242 if (C == '\\' && I + 1 != E) {
243 switch (SV[I + 1]) {
244 case '"':
245 case '\\':
246 C = SV[++I];
247 break;
248 }
249 }
250 SV[S++] = C;
251 }
252 SV.resize(S);
253 NameRef = SV;
254 }
255
256 return getOrCreateSymbol(NameRef);
257}
258
260 unsigned Idx) {
261 return getOrCreateSymbol(MAI.getInternalSymbolPrefix() + FuncName +
262 "$frame_escape_" + Twine(Idx));
263}
264
266 return getOrCreateSymbol(MAI.getInternalSymbolPrefix() + FuncName +
267 "$parent_frame_offset");
268}
269
271 return getOrCreateSymbol(MAI.getInternalSymbolPrefix() + "__ehtable$" +
272 FuncName);
273}
274
275MCSymbolTableEntry &MCContext::getSymbolTableEntry(StringRef Name) {
276 return *Symbols.try_emplace(Name, MCSymbolTableValue{}).first;
277}
278
279MCSymbol *MCContext::createSymbolImpl(const MCSymbolTableEntry *Name,
280 bool IsTemporary) {
281 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
282 "MCSymbol classes must be trivially destructible");
283 static_assert(std::is_trivially_destructible<MCSymbolELF>(),
284 "MCSymbol classes must be trivially destructible");
285 static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
286 "MCSymbol classes must be trivially destructible");
287 static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
288 "MCSymbol classes must be trivially destructible");
289 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
290 "MCSymbol classes must be trivially destructible");
291
292 switch (getObjectFileType()) {
294 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
295 case MCContext::IsELF:
296 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
298 return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
300 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
302 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
304 return createXCOFFSymbolImpl(Name, IsTemporary);
306 break;
308 return new (Name, *this) MCSymbol(Name, IsTemporary);
309 }
310 return new (Name, *this) MCSymbol(Name, IsTemporary);
311}
312
314 MCSymbol *NewSym = nullptr;
315 auto Name = Sym.getNameEntryPtr();
316 switch (getObjectFileType()) {
318 NewSym =
319 new (Name, *this) MCSymbolCOFF(static_cast<const MCSymbolCOFF &>(Sym));
320 break;
321 case MCContext::IsELF:
322 NewSym =
323 new (Name, *this) MCSymbolELF(static_cast<const MCSymbolELF &>(Sym));
324 break;
326 NewSym = new (Name, *this)
327 MCSymbolMachO(static_cast<const MCSymbolMachO &>(Sym));
328 break;
329 default:
330 reportFatalUsageError(".set redefinition is not supported");
331 break;
332 }
333 // Set the name and redirect the `Symbols` entry to `NewSym`.
334 NewSym->getNameEntryPtr() = Name;
335 const_cast<MCSymbolTableEntry *>(Name)->second.Symbol = NewSym;
336 // Ensure the next `registerSymbol` call will add the new symbol to `Symbols`.
337 NewSym->setIsRegistered(false);
338
339 // Ensure the original symbol is not emitted to the symbol table.
340 Sym.IsTemporary = true;
341 return NewSym;
342}
343
344MCSymbol *MCContext::createRenamableSymbol(const Twine &Name,
345 bool AlwaysAddSuffix,
346 bool IsTemporary) {
347 SmallString<128> NewName;
348 Name.toVector(NewName);
349 size_t NameLen = NewName.size();
350
351 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(NewName.str());
352 MCSymbolTableEntry *EntryPtr = &NameEntry;
353 while (AlwaysAddSuffix || EntryPtr->second.Used) {
354 AlwaysAddSuffix = false;
355
356 NewName.resize(NameLen);
357 raw_svector_ostream(NewName) << NameEntry.second.NextUniqueID++;
358 EntryPtr = &getSymbolTableEntry(NewName.str());
359 }
360
361 EntryPtr->second.Used = true;
362 return createSymbolImpl(EntryPtr, IsTemporary);
363}
364
365MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
366 if (!UseNamesOnTempLabels)
367 return createSymbolImpl(nullptr, /*IsTemporary=*/true);
368 return createRenamableSymbol(MAI.getInternalSymbolPrefix() + Name,
369 AlwaysAddSuffix, /*IsTemporary=*/true);
370}
371
373 return createRenamableSymbol(MAI.getInternalSymbolPrefix() + Name, true,
374 /*IsTemporary=*/!SaveTempLabels);
375}
376
377MCSymbol *MCContext::createBlockSymbol(const Twine &Name, bool AlwaysEmit) {
378 if (AlwaysEmit)
379 return getOrCreateSymbol(MAI.getPrivateLabelPrefix() + Name);
380
381 bool IsTemporary = !SaveTempLabels;
382 if (IsTemporary && !UseNamesOnTempLabels)
383 return createSymbolImpl(nullptr, IsTemporary);
384 return createRenamableSymbol(MAI.getPrivateLabelPrefix() + Name,
385 /*AlwaysAddSuffix=*/false, IsTemporary);
386}
387
391
393 return createRenamableSymbol(MAI.getLinkerPrivateGlobalPrefix() + Name,
394 /*AlwaysAddSuffix=*/true,
395 /*IsTemporary=*/false);
396}
397
399
403
405 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name);
406 return createSymbolImpl(&NameEntry, /*IsTemporary=*/false);
407}
408
409unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
410 MCLabel *&Label = Instances[LocalLabelVal];
411 if (!Label)
412 Label = new (*this) MCLabel(0);
413 return Label->incInstance();
414}
415
416unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
417 MCLabel *&Label = Instances[LocalLabelVal];
418 if (!Label)
419 Label = new (*this) MCLabel(0);
420 return Label->getInstance();
421}
422
423MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
424 unsigned Instance) {
425 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
426 if (!Sym)
427 Sym = createNamedTempSymbol();
428 return Sym;
429}
430
432 unsigned Instance = NextInstance(LocalLabelVal);
433 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
434}
435
437 bool Before) {
438 unsigned Instance = GetInstance(LocalLabelVal);
439 if (!Before)
440 ++Instance;
441 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
442}
443
444// Create a section symbol, with a distinct one for each section of the same.
445// The first symbol is used for assembly code references.
446template <typename Symbol>
447Symbol *MCContext::getOrCreateSectionSymbol(StringRef Section) {
448 Symbol *R;
449 auto &SymEntry = getSymbolTableEntry(Section);
450 MCSymbol *Sym = SymEntry.second.Symbol;
451 if (Sym && Sym->isDefined() &&
452 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym)) {
453 reportError(SMLoc(), "invalid symbol redefinition");
454 // Don't reuse the conflicting symbol (e.g. an equated symbol from `x=0`)
455 // as a section symbol, which would cause a crash in changeSection.
456 Sym = nullptr;
457 }
458 // Use the symbol's index to track if it has been used as a section symbol.
459 // Set to -1 to catch potential bugs if misused as a symbol index.
460 if (Sym && Sym->getIndex() != -1u) {
461 R = static_cast<Symbol *>(Sym);
462 } else {
463 SymEntry.second.Used = true;
464 R = new (&SymEntry, *this) Symbol(&SymEntry, /*isTemporary=*/false);
465 if (!Sym)
466 SymEntry.second.Symbol = R;
467 }
468 // Mark as section symbol.
469 R->setIndex(-1u);
470 return R;
471}
472
474 SmallString<128> NameSV;
475 StringRef NameRef = Name.toStringRef(NameSV);
476 return Symbols.lookup(NameRef).Symbol;
477}
478
479void MCContext::setSymbolValue(MCStreamer &Streamer, const Twine &Sym,
480 uint64_t Val) {
481 auto Symbol = getOrCreateSymbol(Sym);
482 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
483}
484
486 InlineAsmUsedLabelNames[Sym->getName()] = Sym;
487}
488
490 return new (WasmSignatureAllocator.Allocate()) wasm::WasmSignature;
491}
492
493MCSymbolXCOFF *MCContext::createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,
494 bool IsTemporary) {
495 if (!Name)
496 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
497
498 StringRef OriginalName = Name->first();
499 if (OriginalName.starts_with("._Renamed..") ||
500 OriginalName.starts_with("_Renamed.."))
501 reportError(SMLoc(), "invalid symbol name from source");
502
503 if (MAI.isValidUnquotedName(OriginalName))
504 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
505
506 // Now we have a name that contains invalid character(s) for XCOFF symbol.
507 // Let's replace with something valid, but save the original name so that
508 // we could still use the original name in the symbol table.
509 SmallString<128> InvalidName(OriginalName);
510
511 // If it's an entry point symbol, we will keep the '.'
512 // in front for the convention purpose. Otherwise, add "_Renamed.."
513 // as prefix to signal this is an renamed symbol.
514 const bool IsEntryPoint = InvalidName.starts_with(".");
515 SmallString<128> ValidName =
516 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
517
518 // Append the hex values of '_' and invalid characters with "_Renamed..";
519 // at the same time replace invalid characters with '_'.
520 for (char &C : InvalidName) {
521 if (!MAI.isAcceptableChar(C) || C == '_') {
522 raw_svector_ostream(ValidName).write_hex(C);
523 C = '_';
524 }
525 }
526
527 // Skip entry point symbol's '.' as we already have a '.' in front of
528 // "_Renamed".
529 if (IsEntryPoint)
530 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
531 else
532 ValidName.append(InvalidName);
533
534 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(ValidName.str());
535 assert(!NameEntry.second.Used && "This name is used somewhere else.");
536 NameEntry.second.Used = true;
537 // Have the MCSymbol object itself refer to the copy of the string
538 // that is embedded in the symbol table entry.
539 MCSymbolXCOFF *XSym =
540 new (&NameEntry, *this) MCSymbolXCOFF(&NameEntry, IsTemporary);
542 return XSym;
543}
544
545//===----------------------------------------------------------------------===//
546// Section Management
547//===----------------------------------------------------------------------===//
548
550 unsigned TypeAndAttributes,
551 unsigned Reserved2, SectionKind Kind,
552 const char *BeginSymName) {
553 // We unique sections by their segment/section pair. The returned section
554 // may not have the same flags as the requested section, if so this should be
555 // diagnosed by the client as an error.
556
557 // Form the name to look up.
558 assert(Section.size() <= 16 && "section name is too long");
559 assert(!memchr(Section.data(), '\0', Section.size()) &&
560 "section name cannot contain NUL");
561
562 // Do the lookup, if we have a hit, return it.
563 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
564 if (!R.second)
565 return R.first->second;
566
567 MCSymbol *Begin = nullptr;
568 if (BeginSymName)
569 Begin = createTempSymbol(BeginSymName, false);
570
571 // Otherwise, return a new section.
572 StringRef Name = R.first->first();
573 auto *Ret = new (MachOAllocator.Allocate())
574 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
575 TypeAndAttributes, Reserved2, Kind, Begin);
576 R.first->second = Ret;
577 return Ret;
578}
579
580MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
581 unsigned Flags,
582 unsigned EntrySize,
583 const MCSymbolELF *Group,
584 bool Comdat, unsigned UniqueID,
585 const MCSymbolELF *LinkedToSym) {
586 auto *R = getOrCreateSectionSymbol<MCSymbolELF>(Section);
587 return new (ELFAllocator.Allocate()) MCSectionELF(
588 Section, Type, Flags, EntrySize, Group, Comdat, UniqueID, R, LinkedToSym);
589}
590
592MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,
593 unsigned EntrySize, const MCSymbolELF *Group,
594 const MCSectionELF *RelInfoSection) {
596 bool Inserted;
597 std::tie(I, Inserted) = RelSecNames.insert(std::make_pair(Name.str(), true));
598
599 return createELFSectionImpl(
600 I->getKey(), Type, Flags, EntrySize, Group, true, true,
601 static_cast<const MCSymbolELF *>(RelInfoSection->getBeginSymbol()));
602}
603
605 const Twine &Suffix, unsigned Type,
606 unsigned Flags,
607 unsigned EntrySize) {
608 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
609 /*IsComdat=*/true);
610}
611
613 unsigned Flags, unsigned EntrySize,
614 const Twine &Group, bool IsComdat,
615 unsigned UniqueID,
616 const MCSymbolELF *LinkedToSym) {
617 MCSymbolELF *GroupSym = nullptr;
618 if (!Group.isTriviallyEmpty() && !Group.str().empty())
619 GroupSym = static_cast<MCSymbolELF *>(getOrCreateSymbol(Group));
620
621 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
622 UniqueID, LinkedToSym);
623}
624
626 unsigned Flags, unsigned EntrySize,
627 const MCSymbolELF *GroupSym,
628 bool IsComdat, unsigned UniqueID,
629 const MCSymbolELF *LinkedToSym) {
630 assert(!(LinkedToSym && LinkedToSym->getName().empty()));
631
632 // Sections are differentiated by the quadruple (section_name, group_name,
633 // unique_id, link_to_symbol_name). Sections sharing the same quadruple are
634 // combined into one section. As an optimization, non-unique sections without
635 // group or linked-to symbol have a shorter unique-ing key.
636 std::pair<StringMap<MCSectionELF *>::iterator, bool> EntryNewPair;
637 // Length of the section name, which are the first SectionLen bytes of the key
638 unsigned SectionLen;
639 if (GroupSym || LinkedToSym || UniqueID != MCSection::NonUniqueID) {
640 SmallString<128> Buffer;
641 Section.toVector(Buffer);
642 SectionLen = Buffer.size();
643 Buffer.push_back(0); // separator which cannot occur in the name
644 if (GroupSym)
645 Buffer.append(GroupSym->getName());
646 Buffer.push_back(0); // separator which cannot occur in the name
647 if (LinkedToSym)
648 Buffer.append(LinkedToSym->getName());
650 StringRef UniqueMapKey = StringRef(Buffer);
651 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
652 } else if (!Section.isSingleStringRef()) {
653 SmallString<128> Buffer;
654 StringRef UniqueMapKey = Section.toStringRef(Buffer);
655 SectionLen = UniqueMapKey.size();
656 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
657 } else {
658 StringRef UniqueMapKey = Section.getSingleStringRef();
659 SectionLen = UniqueMapKey.size();
660 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
661 }
662
663 if (!EntryNewPair.second)
664 return EntryNewPair.first->second;
665
666 StringRef CachedName = EntryNewPair.first->getKey().take_front(SectionLen);
667
668 MCSectionELF *Result =
669 createELFSectionImpl(CachedName, Type, Flags, EntrySize, GroupSym,
670 IsComdat, UniqueID, LinkedToSym);
671 EntryNewPair.first->second = Result;
672
673 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
674 Result->getUniqueID(), Result->getEntrySize());
675
676 return Result;
677}
678
680 bool IsComdat) {
681 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 4, Group, IsComdat,
682 MCSection::NonUniqueID, nullptr);
683}
684
686 unsigned Flags, unsigned UniqueID,
687 unsigned EntrySize) {
688 bool IsMergeable = Flags & ELF::SHF_MERGE;
690 ELFSeenGenericMergeableSections.insert(SectionName);
691 // Minor performance optimization: avoid hash map lookup in
692 // isELFGenericMergeableSection, which will return true for SectionName.
693 IsMergeable = true;
694 }
695
696 // For mergeable sections or non-mergeable sections with a generic mergeable
697 // section name we enter their Unique ID into the ELFEntrySizeMap so that
698 // compatible globals can be assigned to the same section.
699
700 if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
701 ELFEntrySizeMap.insert(std::make_pair(
702 std::make_tuple(SectionName, Flags, EntrySize), UniqueID));
703 }
704}
705
707 return SectionName.starts_with(".rodata.str") ||
708 SectionName.starts_with(".rodata.cst");
709}
710
715
716std::optional<unsigned>
718 unsigned EntrySize) {
719 auto I = ELFEntrySizeMap.find(std::make_tuple(SectionName, Flags, EntrySize));
720 return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second)
721 : std::nullopt;
722}
723
724template <typename TAttr>
725MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
726 TAttr Attributes, MCSection *Parent,
727 bool IsVirtual) {
728 std::string UniqueName(Name);
729 if (Parent) {
730 UniqueName.append("/").append(Parent->getName());
731 if (auto *P = static_cast<MCSectionGOFF *>(Parent)->getParent())
732 UniqueName.append("/").append(P->getName());
733 }
734 // Do the lookup. If we don't have a hit, return a new section.
735 auto [Iter, Inserted] = GOFFUniquingMap.try_emplace(UniqueName);
736 if (!Inserted)
737 return Iter->second;
738
739 StringRef CachedName = StringRef(Iter->first.c_str(), Name.size());
740 MCSectionGOFF *GOFFSection = new (GOFFAllocator.Allocate())
741 MCSectionGOFF(CachedName, Kind, IsVirtual, Attributes,
742 static_cast<MCSectionGOFF *>(Parent));
743 Iter->second = GOFFSection;
744 return GOFFSection;
745}
746
747MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
748 GOFF::SDAttr SDAttributes) {
749 return getGOFFSection<GOFF::SDAttr>(Kind, Name, SDAttributes, nullptr,
750 /*IsVirtual=*/true);
751}
752
753MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
754 GOFF::EDAttr EDAttributes,
755 MCSection *Parent) {
756 return getGOFFSection<GOFF::EDAttr>(
757 Kind, Name, EDAttributes, Parent,
758 /*IsVirtual=*/EDAttributes.BindAlgorithm == GOFF::ESD_BA_Merge);
759}
760
761MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
762 GOFF::PRAttr PRAttributes,
763 MCSection *Parent) {
764 return getGOFFSection<GOFF::PRAttr>(Kind, Name, PRAttributes, Parent,
765 /*IsVirtual=*/false);
766}
767
769 unsigned Characteristics,
770 StringRef COMDATSymName, int Selection,
771 unsigned UniqueID) {
772 MCSymbol *COMDATSymbol = nullptr;
773 if (!COMDATSymName.empty()) {
774 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
775 assert(COMDATSymbol && "COMDATSymbol is null");
776 COMDATSymName = COMDATSymbol->getName();
777 // A non-associative COMDAT is considered to define the COMDAT symbol. Check
778 // the redefinition error.
780 COMDATSymbol->isDefined() &&
781 (!COMDATSymbol->isInSection() ||
782 static_cast<const MCSectionCOFF &>(COMDATSymbol->getSection())
783 .getCOMDATSymbol() != COMDATSymbol))
784 reportError(SMLoc(), "invalid symbol redefinition");
785 }
786
787 // Do the lookup, if we have a hit, return it.
788 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
789 auto [Iter, Inserted] = COFFUniquingMap.try_emplace(T);
790 if (!Inserted)
791 return Iter->second;
792
793 StringRef CachedName = Iter->first.SectionName;
794 MCSymbol *Begin = getOrCreateSectionSymbol<MCSymbolCOFF>(Section);
795 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
796 CachedName, Characteristics, COMDATSymbol, Selection, UniqueID, Begin);
797 Iter->second = Result;
798 Begin->setFragment(&Result->getDummyFragment());
799 return Result;
800}
801
803 unsigned Characteristics) {
804 return getCOFFSection(Section, Characteristics, "", 0,
806}
807
809 const MCSymbol *KeySym,
810 unsigned UniqueID) {
811 // Return the normal section if we don't have to be associative or unique.
812 if (!KeySym && UniqueID == MCSection::NonUniqueID)
813 return Sec;
814
815 // If we have a key symbol, make an associative section with the same name and
816 // kind as the normal section.
817 unsigned Characteristics = Sec->getCharacteristics();
818 if (KeySym) {
819 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
820 return getCOFFSection(Sec->getName(), Characteristics, KeySym->getName(),
822 }
823
824 return getCOFFSection(Sec->getName(), Characteristics, "", 0, UniqueID);
825}
826
828 unsigned Flags, const Twine &Group,
829 unsigned UniqueID) {
830 MCSymbolWasm *GroupSym = nullptr;
831 if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
832 GroupSym = static_cast<MCSymbolWasm *>(getOrCreateSymbol(Group));
833 GroupSym->setComdat(true);
834 if (K.isMetadata() && !GroupSym->getType().has_value()) {
835 // Comdat group symbol associated with a custom section is a section
836 // symbol (not a data symbol).
838 }
839 }
840
841 return getWasmSection(Section, K, Flags, GroupSym, UniqueID);
842}
843
845 unsigned Flags,
846 const MCSymbolWasm *GroupSym,
847 unsigned UniqueID) {
848 StringRef Group = "";
849 if (GroupSym)
850 Group = GroupSym->getName();
851 // Do the lookup, if we have a hit, return it.
852 auto IterBool = WasmUniquingMap.insert(
853 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
854 auto &Entry = *IterBool.first;
855 if (!IterBool.second)
856 return Entry.second;
857
858 StringRef CachedName = Entry.first.SectionName;
859
860 MCSymbol *Begin = createRenamableSymbol(CachedName, true, false);
861 // Begin always has a different name than CachedName... see #48596.
862 getSymbolTableEntry(Begin->getName()).second.Symbol = Begin;
863 static_cast<MCSymbolWasm *>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
864
865 MCSectionWasm *Result = new (WasmAllocator.Allocate())
866 MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
867 Entry.second = Result;
868
869 return Result;
870}
871
873 XCOFF::CsectProperties CsectProp) const {
874 return XCOFFUniquingMap.count(
875 XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
876}
877
879 StringRef Section, SectionKind Kind,
880 std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
881 std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
882 bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
883 assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
884
885 // Do the lookup. If we have a hit, return it.
886 auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
887 IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)
888 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
889 nullptr));
890 auto &Entry = *IterBool.first;
891 if (!IterBool.second) {
892 MCSectionXCOFF *ExistedEntry = Entry.second;
893 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
894 report_fatal_error("section's multiply symbols policy does not match");
895
896 return ExistedEntry;
897 }
898
899 // Otherwise, return a new section.
900 StringRef CachedName = Entry.first.SectionName;
901 MCSymbolXCOFF *QualName = nullptr;
902 // Debug section don't have storage class attribute.
903 if (IsDwarfSec)
904 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(CachedName));
905 else
906 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(
907 CachedName + "[" +
908 XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
909
910 // QualName->getUnqualifiedName() and CachedName are the same except when
911 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
912 MCSectionXCOFF *Result = nullptr;
913 if (IsDwarfSec)
914 Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
915 QualName->getUnqualifiedName(), Kind, QualName,
916 *DwarfSectionSubtypeFlags, QualName, CachedName, MultiSymbolsAllowed);
917 else
918 Result = new (XCOFFAllocator.Allocate())
919 MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
920 CsectProp->Type, Kind, QualName, nullptr, CachedName,
921 MultiSymbolsAllowed);
922
923 Entry.second = Result;
924 return Result;
925}
926
928 MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate()) MCSectionSPIRV();
929 return Result;
930}
931
933 SectionKind K) {
934 // Do the lookup, if we have a hit, return it.
935 auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);
936 if (!ItInsertedPair.second)
937 return ItInsertedPair.first->second;
938
939 auto MapIt = ItInsertedPair.first;
940 // Grab the name from the StringMap. Since the Section is going to keep a
941 // copy of this StringRef we need to make sure the underlying string stays
942 // alive as long as we need it.
943 StringRef Name = MapIt->first();
944 MapIt->second =
945 new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);
946
947 // The first fragment will store the header
948 return MapIt->second;
949}
950
952 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
953}
954
955void MCContext::addDebugPrefixMapEntry(const std::string &From,
956 const std::string &To) {
957 DebugPrefixMap.emplace_back(From, To);
958}
959
961 for (const auto &[From, To] : llvm::reverse(DebugPrefixMap))
962 if (llvm::sys::path::replace_path_prefix(Path, From, To))
963 break;
964}
965
967 const auto &DebugPrefixMap = this->DebugPrefixMap;
968 if (DebugPrefixMap.empty())
969 return;
970
971 // Remap compilation directory.
972 remapDebugPath(CompilationDir);
973
974 // Remap MCDwarfDirs and RootFile.Name in all compilation units.
976 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {
977 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {
978 P = Dir;
980 Dir = std::string(P);
981 }
982
983 // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
984 // DW_AT_decl_file for DWARF v5 generated for assembly source.
985 P = CUIDTablePair.second.getRootFile().Name;
987 CUIDTablePair.second.getRootFile().Name = std::string(P);
988 }
989}
990
991//===----------------------------------------------------------------------===//
992// Dwarf Management
993//===----------------------------------------------------------------------===//
994
998
1002
1004 // MCDwarf needs the root file as well as the compilation directory.
1005 // If we find a '.file 0' directive that will supersede these values.
1006 std::optional<MD5::MD5Result> Cksum;
1007 if (getDwarfVersion() >= 5) {
1008 MD5 Hash;
1009 MD5::MD5Result Sum;
1010 Hash.update(Buffer);
1011 Hash.final(Sum);
1012 Cksum = Sum;
1013 }
1014 // Canonicalize the root filename. It cannot be empty, and should not
1015 // repeat the compilation dir.
1016 // The MCContext ctor initializes MainFileName to the name associated with
1017 // the SrcMgr's main file ID, which might be the same as InputFileName (and
1018 // possibly include directory components).
1019 // Or, MainFileName might have been overridden by a -main-file-name option,
1020 // which is supposed to be just a base filename with no directory component.
1021 // So, if the InputFileName and MainFileName are not equal, assume
1022 // MainFileName is a substitute basename and replace the last component.
1023 SmallString<1024> FileNameBuf = InputFileName;
1024 if (FileNameBuf.empty() || FileNameBuf == "-")
1025 FileNameBuf = "<stdin>";
1026 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
1029 }
1030 StringRef FileName = FileNameBuf;
1031 if (FileName.consume_front(getCompilationDir()))
1032 if (llvm::sys::path::is_separator(FileName.front()))
1033 FileName = FileName.drop_front();
1034 assert(!FileName.empty());
1036 /*CUID=*/0, getCompilationDir(), FileName, Cksum, std::nullopt);
1037}
1038
1039/// getDwarfFile - takes a file name and number to place in the dwarf file and
1040/// directory tables. If the file number has already been allocated it is an
1041/// error and zero is returned and the client reports the error, else the
1042/// allocated file number is returned. The file numbers may be in any order.
1045 unsigned FileNumber,
1046 std::optional<MD5::MD5Result> Checksum,
1047 std::optional<StringRef> Source, unsigned CUID) {
1048 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
1049 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
1050 FileNumber);
1051}
1052
1053/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
1054/// currently is assigned and false otherwise.
1055bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
1056 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
1057 if (FileNumber == 0)
1058 return getDwarfVersion() >= 5;
1059 if (FileNumber >= LineTable.getMCDwarfFiles().size())
1060 return false;
1061
1062 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
1063}
1064
1065/// Remove empty sections from SectionsForRanges, to avoid generating
1066/// useless debug info for them.
1068 SectionsForRanges.remove_if(
1069 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
1070}
1071
1073 if (!CVContext)
1074 CVContext.reset(new CodeViewContext(this));
1075 return *CVContext;
1076}
1077
1078//===----------------------------------------------------------------------===//
1079// Error Reporting
1080//===----------------------------------------------------------------------===//
1081
1083 assert(DiagHandler && "MCContext::DiagHandler is not set");
1084 bool UseInlineSrcMgr = false;
1085 const SourceMgr *SMP = nullptr;
1086 if (SrcMgr) {
1087 SMP = SrcMgr;
1088 } else if (InlineSrcMgr) {
1089 SMP = InlineSrcMgr.get();
1090 UseInlineSrcMgr = true;
1091 } else
1092 llvm_unreachable("Either SourceMgr should be available");
1093 DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
1094}
1095
1096void MCContext::reportCommon(
1097 SMLoc Loc,
1098 std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
1099 // * MCContext::SrcMgr is null when the MC layer emits machine code for input
1100 // other than assembly file, say, for .c/.cpp/.ll/.bc.
1101 // * MCContext::InlineSrcMgr is null when the inline asm is not used.
1102 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
1103 // and MCContext::InlineSrcMgr are null.
1104 SourceMgr SM;
1105 const SourceMgr *SMP = &SM;
1106 bool UseInlineSrcMgr = false;
1107
1108 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
1109 // For MC-only execution, only SrcMgr is used;
1110 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is
1111 // inline asm in the IR.
1112 if (Loc.isValid()) {
1113 if (SrcMgr) {
1114 SMP = SrcMgr;
1115 } else if (InlineSrcMgr) {
1116 SMP = InlineSrcMgr.get();
1117 UseInlineSrcMgr = true;
1118 } else
1119 llvm_unreachable("Either SourceMgr should be available");
1120 }
1121
1122 SMDiagnostic D;
1123 GetMessage(D, SMP);
1124 DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
1125}
1126
1128 HadError = true;
1129 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1130 D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
1131 });
1132}
1133
1135 if (getTargetOptions().MCNoWarn)
1136 return;
1137 if (getTargetOptions().MCFatalWarnings) {
1138 reportError(Loc, Msg);
1139 } else {
1140 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1141 D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
1142 });
1143 }
1144}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
amdgpu AMDGPU DAG DAG Pattern Instruction Selection
static const Function * getParent(const Value *V)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &, std::vector< const MDNode * > &)
Definition MCContext.cpp:60
#define DWARF2_FLAG_IS_STMT
Definition MCDwarf.h:119
This file declares the MCSectionGOFF class, which contains all of the necessary machine code sections...
This file contains the MCSymbolGOFF class.
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static constexpr unsigned SM(unsigned Version)
#define P(N)
This file defines the SmallString class.
This file defines the SmallVector class.
Holds state from .cv_file and .cv_loc directives for later emission.
Definition MCCodeView.h:144
Tagged union holding either a T or a Error.
Definition Error.h:485
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:64
virtual bool isAcceptableChar(char C) const
Return true if C is an acceptable character inside a symbol name.
Definition MCAsmInfo.cpp:79
virtual bool isValidUnquotedName(StringRef Name) const
Return true if the identifier Name does not need quotes to be syntactically correct.
Definition MCAsmInfo.cpp:86
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
LLVM_ABI void remapDebugPath(SmallVectorImpl< char > &Path)
Remap one path in-place as per the debug prefix map.
LLVM_ABI MCSymbol * createBlockSymbol(const Twine &Name, bool AlwaysEmit=false)
Get or create a symbol for a basic block.
LLVM_ABI MCSubtargetInfo & getSubtargetCopy(const MCSubtargetInfo &STI)
LLVM_ABI MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Environment getObjectFileType() const
Definition MCContext.h:389
LLVM_ABI void setSymbolValue(MCStreamer &Streamer, const Twine &Sym, uint64_t Val)
Set value for a symbol.
const std::string & getMainFileName() const
Get the main file name for use in error messages and debug info.
Definition MCContext.h:697
LLVM_ABI MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, StringRef COMDATSymName, int Selection, unsigned UniqueID=MCSection::NonUniqueID)
LLVM_ABI void addDebugPrefixMapEntry(const std::string &From, const std::string &To)
Add an entry to the debug prefix map.
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
StringRef getCompilationDir() const
Get the compilation directory for DW_AT_comp_dir The compilation directory should be set with setComp...
Definition MCContext.h:679
LLVM_ABI void RemapDebugPaths()
LLVM_ABI MCInst * createMCInst()
Create and return a new MC instruction.
LLVM_ABI MCSymbol * getOrCreateFrameAllocSymbol(const Twine &FuncName, unsigned Idx)
Gets a symbol that will be defined to the final stack offset of a local variable after codegen.
LLVM_ABI MCSectionELF * createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags, unsigned EntrySize, const MCSymbolELF *Group, const MCSectionELF *RelInfoSection)
LLVM_ABI MCSymbol * createLinkerPrivateTempSymbol()
Create a new linker temporary symbol with the specified prefix (Name) or "tmp".
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K, unsigned Flags=0)
Definition MCContext.h:638
LLVM_ABI void recordELFMergeableSectionInfo(StringRef SectionName, unsigned Flags, unsigned UniqueID, unsigned EntrySize)
LLVM_ABI Expected< unsigned > getDwarfFile(StringRef Directory, StringRef FileName, unsigned FileNumber, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source, unsigned CUID)
Creates an entry in the dwarf file and directory tables.
LLVM_ABI wasm::WasmSignature * createWasmSignature()
Allocates and returns a new WasmSignature instance (with empty parameter and return type lists).
LLVM_ABI MCSectionELF * getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize=0)
Get a section with the provided group identifier.
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition MCContext.h:550
LLVM_ABI MCSectionXCOFF * getXCOFFSection(StringRef Section, SectionKind K, std::optional< XCOFF::CsectProperties > CsectProp=std::nullopt, bool MultiSymbolsAllowed=false, std::optional< XCOFF::DwarfSectionSubtypeFlags > DwarfSubtypeFlags=std::nullopt)
LLVM_ABI void diagnose(const SMDiagnostic &SMD)
LLVM_ABI bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID=0)
isValidDwarfFileNumber - takes a dwarf file number and returns true if it currently is assigned and f...
LLVM_ABI void registerInlineAsmLabel(MCSymbol *Sym)
registerInlineAsmLabel - Records that the name is a label referenced in inline assembly.
LLVM_ABI MCSymbol * createLocalSymbol(StringRef Name)
Create a local, non-temporary symbol like an ELF mapping symbol.
MCDwarfLineTable & getMCDwarfLineTable(unsigned CUID)
Definition MCContext.h:714
LLVM_ABI void initInlineSourceManager()
LLVM_ABI MCSymbol * getOrCreateParentFrameOffsetSymbol(const Twine &FuncName)
LLVM_ABI MCSymbol * lookupSymbol(const Twine &Name) const
Get the symbol for Name, or null.
LLVM_ABI bool emitCompactUnwindNonCanonical() const
LLVM_ABI ~MCContext()
LLVM_ABI CodeViewContext & getCVContext()
LLVM_ABI void reset()
reset - return object to right after construction state to prepare to process a new module
LLVM_ABI bool isELFGenericMergeableSection(StringRef Name)
LLVM_ABI std::optional< unsigned > getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags, unsigned EntrySize)
Return the unique ID of the section with the given name, flags and entry size, if it exists.
LLVM_ABI MCSymbol * createDirectionalLocalSymbol(unsigned LocalLabelVal)
Create the definition of a directional local symbol for numbered label (used for "1:" definitions).
LLVM_ABI void reportWarning(SMLoc L, const Twine &Msg)
uint16_t getDwarfVersion() const
Definition MCContext.h:814
LLVM_ABI void finalizeDwarfSections(MCStreamer &MCOS)
Remove empty sections from SectionsForRanges, to avoid generating useless debug info for them.
LLVM_ABI void reportError(SMLoc L, const Twine &Msg)
LLVM_ABI MCContext(const Triple &TheTriple, const MCAsmInfo &MAI, const MCRegisterInfo *MRI, const MCSubtargetInfo *MSTI, const SourceMgr *Mgr=nullptr, bool DoAutoReset=true, StringRef Swift5ReflSegmentName={})
Definition MCContext.cpp:65
LLVM_ABI MCSymbol * getOrCreateLSDASymbol(const Twine &FuncName)
LLVM_ABI MCSectionDXContainer * getDXContainerSection(StringRef Section, SectionKind K)
Get the section for the provided Section name.
LLVM_ABI bool hasXCOFFSection(StringRef Section, XCOFF::CsectProperties CsectProp) const
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
LLVM_ABI MCSymbol * createLinkerPrivateSymbol(const Twine &Name)
LLVM_ABI MCSectionSPIRV * getSPIRVSection()
LLVM_ABI MCSectionCOFF * getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID=MCSection::NonUniqueID)
Gets or creates a section equivalent to Sec that is associated with the section containing KeySym.
LLVM_ABI MCSymbol * cloneSymbol(MCSymbol &Sym)
Clone a symbol for the .set directive, replacing it in the symbol table.
LLVM_ABI MCSymbol * parseSymbol(const Twine &Name)
Variant of getOrCreateSymbol that handles backslash-escaped symbols.
LLVM_ABI EmitDwarfUnwindType emitDwarfUnwindInfo() const
LLVM_ABI bool isELFImplicitMergeableSectionNamePrefix(StringRef Name)
LLVM_ABI MCSectionELF * createELFGroupSection(const MCSymbolELF *Group, bool IsComdat)
void setUseNamesOnTempLabels(bool Value)
Definition MCContext.h:421
LLVM_ABI void setGenDwarfRootFile(StringRef FileName, StringRef Buffer)
Specifies information about the "root file" for assembler clients (e.g., llvm-mc).
LLVM_ABI const MCTargetOptions & getTargetOptions() const
void setMCLineTableRootFile(unsigned CUID, StringRef CompilationDir, StringRef Filename, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source)
Specifies the "root" file and directory of the compilation unit.
Definition MCContext.h:738
LLVM_ABI MCSymbol * getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before)
Create and return a directional local symbol for numbered label (used for "1b" or 1f" references).
LLVM_ABI MCSymbol * createNamedTempSymbol()
Create a temporary symbol with a unique name whose name cannot be omitted in the symbol table.
LLVM_ABI Expected< unsigned > tryGetFile(StringRef &Directory, StringRef &FileName, std::optional< MD5::MD5Result > Checksum, std::optional< StringRef > Source, uint16_t DwarfVersion, unsigned FileNumber=0)
Definition MCDwarf.cpp:631
const SmallVectorImpl< MCDwarfFile > & getMCDwarfFiles() const
Definition MCDwarf.h:443
Instances of this class represent the information from a dwarf .loc directive.
Definition MCDwarf.h:107
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
Instances of this class represent a label name in the MC file, and MCLabel are created and uniqued by...
Definition MCLabel.h:23
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
This represents a section on Windows.
MCSymbol * getCOMDATSymbol() const
unsigned getCharacteristics() const
This represents a section on linux, lots of unix variants and some bare metal systems.
This represents a section on a Mach-O system (used by Mac OS X).
This represents a section on wasm.
bool isMultiSymbolsAllowed() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:573
static constexpr unsigned NonUniqueID
Definition MCSection.h:578
StringRef getName() const
Definition MCSection.h:643
MCSymbol * getBeginSymbol()
Definition MCSection.h:646
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value)
Emit an assignment of Value to Symbol.
virtual bool mayHaveInstructions(MCSection &Sec) const
Generic base class for all target subtargets.
void setComdat(bool isComdat)
void setType(wasm::WasmSymbolType type)
std::optional< wasm::WasmSymbolType > getType() const
static StringRef getUnqualifiedName(StringRef Name)
void setSymbolTableName(StringRef STN)
StringRef getUnqualifiedName() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition MCSymbol.h:233
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition MCSymbol.h:237
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
void setFragment(MCFragment *F) const
Mark the symbol as defined in the fragment F.
Definition MCSymbol.h:257
uint32_t getIndex() const
Get the (implementation defined) index.
Definition MCSymbol.h:280
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition MCSymbol.h:251
unsigned IsTemporary
IsTemporary - True if this is an assembler temporary label, which typically does not survive in the ....
Definition MCSymbol.h:78
void setIsRegistered(bool Value) const
Definition MCSymbol.h:196
EmitDwarfUnwindType EmitDwarfUnwind
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:297
LLVM_ABI void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
Represents a location in source code.
Definition SMLoc.h:22
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition SectionKind.h:22
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize(size_type N)
void push_back(const T &Elt)
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
StringMapIterBase< ValueTy, false > iterator
Definition StringMap.h:221
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&...Args)
Emplace a new element for the specified key into the map if the key isn't already in the map.
Definition StringMap.h:381
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:629
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:143
char front() const
front - Get the first character in the string.
Definition StringRef.h:146
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition Triple.h:459
bool isUEFI() const
Tests whether the OS is UEFI.
Definition Triple.h:695
bool isOSWindows() const
Tests whether the OS is Windows.
Definition Triple.h:698
@ UnknownObjectFormat
Definition Triple.h:331
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition Twine.h:398
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
raw_ostream & write_hex(unsigned long long N)
Output N in hexadecimal, without any prefix or padding.
A raw_ostream that writes to an SmallVector or SmallString.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ IMAGE_SCN_LNK_COMDAT
Definition COFF.h:309
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition COFF.h:459
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ SHF_MERGE
Definition ELF.h:1255
@ SHT_GROUP
Definition ELF.h:1162
@ ESD_BA_Merge
Definition GOFF.h:99
DwarfSectionSubtypeFlags
Values for defining the section subtype of sections of type STYP_DWARF as they would appear in the (s...
Definition XCOFF.h:155
LLVM_ABI StringRef getMappingClassString(XCOFF::StorageMappingClass SMC)
Definition XCOFF.cpp:22
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition Endian.h:96
LLVM_ABI void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition Path.cpp:475
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
Definition Path.cpp:519
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:457
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:608
@ WASM_SYMBOL_TYPE_SECTION
Definition Wasm.h:232
This is an optimization pass for GlobalISel generic memory operations.
SourceMgr SrcMgr
Definition Error.cpp:24
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
EmitDwarfUnwindType
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
StringMapEntry< MCSymbolTableValue > MCSymbolTableEntry
MCContext stores MCSymbolTableValue in a string map (see MCSymbol::operator new).
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
GOFF::ESDBindingAlgorithm BindAlgorithm
The value for an entry in the symbol table of an MCContext.
StorageMappingClass MappingClass
Definition XCOFF.h:502