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) {
75 assert(MAI && MAI->getTargetOptions() &&
76 "MCAsmInfo and MCTargetOptions must be available");
78 SaveTempLabels = TO.MCSaveTempLabels;
79 if (SaveTempLabels)
81 SecureLogFile = TO.AsSecureLogFile;
82
83 if (SrcMgr && SrcMgr->getNumBuffers())
84 MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
85 ->getBufferIdentifier());
86
87 switch (TheTriple.getObjectFormat()) {
88 case Triple::MachO:
89 Env = IsMachO;
90 break;
91 case Triple::COFF:
92 if (!TheTriple.isOSWindows() && !TheTriple.isUEFI()) {
94 "cannot initialize MC for non-Windows COFF object files");
95 }
96
97 Env = IsCOFF;
98 break;
99 case Triple::ELF:
100 Env = IsELF;
101 break;
102 case Triple::Wasm:
103 Env = IsWasm;
104 break;
105 case Triple::XCOFF:
106 Env = IsXCOFF;
107 break;
108 case Triple::GOFF:
109 Env = IsGOFF;
110 break;
112 Env = IsDXContainer;
113 break;
114 case Triple::SPIRV:
115 Env = IsSPIRV;
116 break;
118 report_fatal_error("Cannot initialize MC for unknown object file format.");
119 break;
120 }
121}
122
124 return *MAI->getTargetOptions();
125}
126
128 if (AutoReset)
129 reset();
130
131 // NOTE: The symbols are all allocated out of a bump pointer allocator,
132 // we don't need to free them here.
133}
134
136 if (!InlineSrcMgr)
137 InlineSrcMgr.reset(new SourceMgr());
138}
139
140//===----------------------------------------------------------------------===//
141// Module Lifetime Management
142//===----------------------------------------------------------------------===//
143
145 SrcMgr = nullptr;
146 InlineSrcMgr.reset();
147 LocInfos.clear();
148 DiagHandler = defaultDiagHandler;
149
150 // Call the destructors so the fragments are freed
151 COFFAllocator.DestroyAll();
152 DXCAllocator.DestroyAll();
153 ELFAllocator.DestroyAll();
154 GOFFAllocator.DestroyAll();
155 MachOAllocator.DestroyAll();
156 WasmAllocator.DestroyAll();
157 XCOFFAllocator.DestroyAll();
158 MCInstAllocator.DestroyAll();
159 SPIRVAllocator.DestroyAll();
160 WasmSignatureAllocator.DestroyAll();
161
162 CVContext.reset();
163
164 MCSubtargetAllocator.DestroyAll();
165 InlineAsmUsedLabelNames.clear();
166 Symbols.clear();
167 Allocator.Reset();
168 Instances.clear();
169 CompilationDir.clear();
170 MainFileName.clear();
171 MCDwarfLineTablesCUMap.clear();
172 SectionsForRanges.clear();
173 MCGenDwarfLabelEntries.clear();
174 DwarfDebugFlags = StringRef();
175 DwarfCompileUnitID = 0;
176 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
177
178 MachOUniquingMap.clear();
179 ELFUniquingMap.clear();
180 GOFFUniquingMap.clear();
181 COFFUniquingMap.clear();
182 WasmUniquingMap.clear();
183 XCOFFUniquingMap.clear();
184 DXCUniquingMap.clear();
185
186 RelSecNames.clear();
187 MacroMap.clear();
188 ELFEntrySizeMap.clear();
189 ELFSeenGenericMergeableSections.clear();
190
191 DwarfLocSeen = false;
192 GenDwarfForAssembly = false;
193 GenDwarfFileNumber = 0;
194
195 HadError = false;
196}
197
198//===----------------------------------------------------------------------===//
199// MCInst Management
200//===----------------------------------------------------------------------===//
201
203 return new (MCInstAllocator.Allocate()) MCInst;
204}
205
206//===----------------------------------------------------------------------===//
207// Symbol Manipulation
208//===----------------------------------------------------------------------===//
209
211 SmallString<128> NameSV;
212 StringRef NameRef = Name.toStringRef(NameSV);
213
214 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
215
216 MCSymbolTableEntry &Entry = getSymbolTableEntry(NameRef);
217 if (!Entry.second.Symbol) {
218 bool IsRenamable = NameRef.starts_with(MAI->getInternalSymbolPrefix());
219 bool IsTemporary = IsRenamable && !SaveTempLabels;
220 if (!Entry.second.Used) {
221 Entry.second.Used = true;
222 Entry.second.Symbol = createSymbolImpl(&Entry, IsTemporary);
223 } else {
224 assert(IsRenamable && "cannot rename non-private symbol");
225 // Slow path: we need to rename a temp symbol from the user.
226 Entry.second.Symbol = createRenamableSymbol(NameRef, false, IsTemporary);
227 }
228 }
229
230 return Entry.second.Symbol;
231}
232
235 StringRef NameRef = Name.toStringRef(SV);
236 if (NameRef.contains('\\')) {
237 SV = NameRef;
238 size_t S = 0;
239 // Support escaped \\ and \" as in GNU Assembler. GAS issues a warning for
240 // other characters following \\, which we do not implement due to code
241 // structure.
242 for (size_t I = 0, E = SV.size(); I != E; ++I) {
243 char C = SV[I];
244 if (C == '\\' && I + 1 != E) {
245 switch (SV[I + 1]) {
246 case '"':
247 case '\\':
248 C = SV[++I];
249 break;
250 }
251 }
252 SV[S++] = C;
253 }
254 SV.resize(S);
255 NameRef = SV;
256 }
257
258 return getOrCreateSymbol(NameRef);
259}
260
262 unsigned Idx) {
263 return getOrCreateSymbol(MAI->getInternalSymbolPrefix() + FuncName +
264 "$frame_escape_" + Twine(Idx));
265}
266
268 return getOrCreateSymbol(MAI->getInternalSymbolPrefix() + FuncName +
269 "$parent_frame_offset");
270}
271
273 return getOrCreateSymbol(MAI->getInternalSymbolPrefix() + "__ehtable$" +
274 FuncName);
275}
276
277MCSymbolTableEntry &MCContext::getSymbolTableEntry(StringRef Name) {
278 return *Symbols.try_emplace(Name, MCSymbolTableValue{}).first;
279}
280
281MCSymbol *MCContext::createSymbolImpl(const MCSymbolTableEntry *Name,
282 bool IsTemporary) {
283 static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
284 "MCSymbol classes must be trivially destructible");
285 static_assert(std::is_trivially_destructible<MCSymbolELF>(),
286 "MCSymbol classes must be trivially destructible");
287 static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
288 "MCSymbol classes must be trivially destructible");
289 static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
290 "MCSymbol classes must be trivially destructible");
291 static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
292 "MCSymbol classes must be trivially destructible");
293
294 switch (getObjectFileType()) {
296 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
297 case MCContext::IsELF:
298 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
300 return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
302 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
304 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
306 return createXCOFFSymbolImpl(Name, IsTemporary);
308 break;
310 return new (Name, *this) MCSymbol(Name, IsTemporary);
311 }
312 return new (Name, *this) MCSymbol(Name, IsTemporary);
313}
314
316 MCSymbol *NewSym = nullptr;
317 auto Name = Sym.getNameEntryPtr();
318 switch (getObjectFileType()) {
320 NewSym =
321 new (Name, *this) MCSymbolCOFF(static_cast<const MCSymbolCOFF &>(Sym));
322 break;
323 case MCContext::IsELF:
324 NewSym =
325 new (Name, *this) MCSymbolELF(static_cast<const MCSymbolELF &>(Sym));
326 break;
328 NewSym = new (Name, *this)
329 MCSymbolMachO(static_cast<const MCSymbolMachO &>(Sym));
330 break;
331 default:
332 reportFatalUsageError(".set redefinition is not supported");
333 break;
334 }
335 // Set the name and redirect the `Symbols` entry to `NewSym`.
336 NewSym->getNameEntryPtr() = Name;
337 const_cast<MCSymbolTableEntry *>(Name)->second.Symbol = NewSym;
338 // Ensure the next `registerSymbol` call will add the new symbol to `Symbols`.
339 NewSym->setIsRegistered(false);
340
341 // Ensure the original symbol is not emitted to the symbol table.
342 Sym.IsTemporary = true;
343 return NewSym;
344}
345
346MCSymbol *MCContext::createRenamableSymbol(const Twine &Name,
347 bool AlwaysAddSuffix,
348 bool IsTemporary) {
349 SmallString<128> NewName;
350 Name.toVector(NewName);
351 size_t NameLen = NewName.size();
352
353 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(NewName.str());
354 MCSymbolTableEntry *EntryPtr = &NameEntry;
355 while (AlwaysAddSuffix || EntryPtr->second.Used) {
356 AlwaysAddSuffix = false;
357
358 NewName.resize(NameLen);
359 raw_svector_ostream(NewName) << NameEntry.second.NextUniqueID++;
360 EntryPtr = &getSymbolTableEntry(NewName.str());
361 }
362
363 EntryPtr->second.Used = true;
364 return createSymbolImpl(EntryPtr, IsTemporary);
365}
366
367MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
368 if (!UseNamesOnTempLabels)
369 return createSymbolImpl(nullptr, /*IsTemporary=*/true);
370 return createRenamableSymbol(MAI->getInternalSymbolPrefix() + Name,
371 AlwaysAddSuffix, /*IsTemporary=*/true);
372}
373
375 return createRenamableSymbol(MAI->getInternalSymbolPrefix() + Name, true,
376 /*IsTemporary=*/!SaveTempLabels);
377}
378
379MCSymbol *MCContext::createBlockSymbol(const Twine &Name, bool AlwaysEmit) {
380 if (AlwaysEmit)
381 return getOrCreateSymbol(MAI->getPrivateLabelPrefix() + Name);
382
383 bool IsTemporary = !SaveTempLabels;
384 if (IsTemporary && !UseNamesOnTempLabels)
385 return createSymbolImpl(nullptr, IsTemporary);
386 return createRenamableSymbol(MAI->getPrivateLabelPrefix() + Name,
387 /*AlwaysAddSuffix=*/false, IsTemporary);
388}
389
393
395 return createRenamableSymbol(MAI->getLinkerPrivateGlobalPrefix() + Name,
396 /*AlwaysAddSuffix=*/true,
397 /*IsTemporary=*/false);
398}
399
401
405
407 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(Name);
408 return createSymbolImpl(&NameEntry, /*IsTemporary=*/false);
409}
410
411unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
412 MCLabel *&Label = Instances[LocalLabelVal];
413 if (!Label)
414 Label = new (*this) MCLabel(0);
415 return Label->incInstance();
416}
417
418unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
419 MCLabel *&Label = Instances[LocalLabelVal];
420 if (!Label)
421 Label = new (*this) MCLabel(0);
422 return Label->getInstance();
423}
424
425MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
426 unsigned Instance) {
427 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
428 if (!Sym)
429 Sym = createNamedTempSymbol();
430 return Sym;
431}
432
434 unsigned Instance = NextInstance(LocalLabelVal);
435 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
436}
437
439 bool Before) {
440 unsigned Instance = GetInstance(LocalLabelVal);
441 if (!Before)
442 ++Instance;
443 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
444}
445
446// Create a section symbol, with a distinct one for each section of the same.
447// The first symbol is used for assembly code references.
448template <typename Symbol>
449Symbol *MCContext::getOrCreateSectionSymbol(StringRef Section) {
450 Symbol *R;
451 auto &SymEntry = getSymbolTableEntry(Section);
452 MCSymbol *Sym = SymEntry.second.Symbol;
453 if (Sym && Sym->isDefined() &&
454 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym)) {
455 reportError(SMLoc(), "invalid symbol redefinition");
456 // Don't reuse the conflicting symbol (e.g. an equated symbol from `x=0`)
457 // as a section symbol, which would cause a crash in changeSection.
458 Sym = nullptr;
459 }
460 // Use the symbol's index to track if it has been used as a section symbol.
461 // Set to -1 to catch potential bugs if misused as a symbol index.
462 if (Sym && Sym->getIndex() != -1u) {
463 R = static_cast<Symbol *>(Sym);
464 } else {
465 SymEntry.second.Used = true;
466 R = new (&SymEntry, *this) Symbol(&SymEntry, /*isTemporary=*/false);
467 if (!Sym)
468 SymEntry.second.Symbol = R;
469 }
470 // Mark as section symbol.
471 R->setIndex(-1u);
472 return R;
473}
474
476 SmallString<128> NameSV;
477 StringRef NameRef = Name.toStringRef(NameSV);
478 return Symbols.lookup(NameRef).Symbol;
479}
480
481void MCContext::setSymbolValue(MCStreamer &Streamer, const Twine &Sym,
482 uint64_t Val) {
483 auto Symbol = getOrCreateSymbol(Sym);
484 Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
485}
486
488 InlineAsmUsedLabelNames[Sym->getName()] = Sym;
489}
490
492 return new (WasmSignatureAllocator.Allocate()) wasm::WasmSignature;
493}
494
495MCSymbolXCOFF *MCContext::createXCOFFSymbolImpl(const MCSymbolTableEntry *Name,
496 bool IsTemporary) {
497 if (!Name)
498 return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
499
500 StringRef OriginalName = Name->first();
501 if (OriginalName.starts_with("._Renamed..") ||
502 OriginalName.starts_with("_Renamed.."))
503 reportError(SMLoc(), "invalid symbol name from source");
504
505 if (MAI->isValidUnquotedName(OriginalName))
506 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
507
508 // Now we have a name that contains invalid character(s) for XCOFF symbol.
509 // Let's replace with something valid, but save the original name so that
510 // we could still use the original name in the symbol table.
511 SmallString<128> InvalidName(OriginalName);
512
513 // If it's an entry point symbol, we will keep the '.'
514 // in front for the convention purpose. Otherwise, add "_Renamed.."
515 // as prefix to signal this is an renamed symbol.
516 const bool IsEntryPoint = InvalidName.starts_with(".");
517 SmallString<128> ValidName =
518 StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
519
520 // Append the hex values of '_' and invalid characters with "_Renamed..";
521 // at the same time replace invalid characters with '_'.
522 for (char &C : InvalidName) {
523 if (!MAI->isAcceptableChar(C) || C == '_') {
524 raw_svector_ostream(ValidName).write_hex(C);
525 C = '_';
526 }
527 }
528
529 // Skip entry point symbol's '.' as we already have a '.' in front of
530 // "_Renamed".
531 if (IsEntryPoint)
532 ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
533 else
534 ValidName.append(InvalidName);
535
536 MCSymbolTableEntry &NameEntry = getSymbolTableEntry(ValidName.str());
537 assert(!NameEntry.second.Used && "This name is used somewhere else.");
538 NameEntry.second.Used = true;
539 // Have the MCSymbol object itself refer to the copy of the string
540 // that is embedded in the symbol table entry.
541 MCSymbolXCOFF *XSym =
542 new (&NameEntry, *this) MCSymbolXCOFF(&NameEntry, IsTemporary);
544 return XSym;
545}
546
547//===----------------------------------------------------------------------===//
548// Section Management
549//===----------------------------------------------------------------------===//
550
552 unsigned TypeAndAttributes,
553 unsigned Reserved2, SectionKind Kind,
554 const char *BeginSymName) {
555 // We unique sections by their segment/section pair. The returned section
556 // may not have the same flags as the requested section, if so this should be
557 // diagnosed by the client as an error.
558
559 // Form the name to look up.
560 assert(Section.size() <= 16 && "section name is too long");
561 assert(!memchr(Section.data(), '\0', Section.size()) &&
562 "section name cannot contain NUL");
563
564 // Do the lookup, if we have a hit, return it.
565 auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
566 if (!R.second)
567 return R.first->second;
568
569 MCSymbol *Begin = nullptr;
570 if (BeginSymName)
571 Begin = createTempSymbol(BeginSymName, false);
572
573 // Otherwise, return a new section.
574 StringRef Name = R.first->first();
575 auto *Ret = new (MachOAllocator.Allocate())
576 MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
577 TypeAndAttributes, Reserved2, Kind, Begin);
578 R.first->second = Ret;
579 return Ret;
580}
581
582MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
583 unsigned Flags,
584 unsigned EntrySize,
585 const MCSymbolELF *Group,
586 bool Comdat, unsigned UniqueID,
587 const MCSymbolELF *LinkedToSym) {
588 auto *R = getOrCreateSectionSymbol<MCSymbolELF>(Section);
589 return new (ELFAllocator.Allocate()) MCSectionELF(
590 Section, Type, Flags, EntrySize, Group, Comdat, UniqueID, R, LinkedToSym);
591}
592
594MCContext::createELFRelSection(const Twine &Name, unsigned Type, unsigned Flags,
595 unsigned EntrySize, const MCSymbolELF *Group,
596 const MCSectionELF *RelInfoSection) {
598 bool Inserted;
599 std::tie(I, Inserted) = RelSecNames.insert(std::make_pair(Name.str(), true));
600
601 return createELFSectionImpl(
602 I->getKey(), Type, Flags, EntrySize, Group, true, true,
603 static_cast<const MCSymbolELF *>(RelInfoSection->getBeginSymbol()));
604}
605
607 const Twine &Suffix, unsigned Type,
608 unsigned Flags,
609 unsigned EntrySize) {
610 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
611 /*IsComdat=*/true);
612}
613
615 unsigned Flags, unsigned EntrySize,
616 const Twine &Group, bool IsComdat,
617 unsigned UniqueID,
618 const MCSymbolELF *LinkedToSym) {
619 MCSymbolELF *GroupSym = nullptr;
620 if (!Group.isTriviallyEmpty() && !Group.str().empty())
621 GroupSym = static_cast<MCSymbolELF *>(getOrCreateSymbol(Group));
622
623 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
624 UniqueID, LinkedToSym);
625}
626
628 unsigned Flags, unsigned EntrySize,
629 const MCSymbolELF *GroupSym,
630 bool IsComdat, unsigned UniqueID,
631 const MCSymbolELF *LinkedToSym) {
632 assert(!(LinkedToSym && LinkedToSym->getName().empty()));
633
634 // Sections are differentiated by the quadruple (section_name, group_name,
635 // unique_id, link_to_symbol_name). Sections sharing the same quadruple are
636 // combined into one section. As an optimization, non-unique sections without
637 // group or linked-to symbol have a shorter unique-ing key.
638 std::pair<StringMap<MCSectionELF *>::iterator, bool> EntryNewPair;
639 // Length of the section name, which are the first SectionLen bytes of the key
640 unsigned SectionLen;
641 if (GroupSym || LinkedToSym || UniqueID != MCSection::NonUniqueID) {
642 SmallString<128> Buffer;
643 Section.toVector(Buffer);
644 SectionLen = Buffer.size();
645 Buffer.push_back(0); // separator which cannot occur in the name
646 if (GroupSym)
647 Buffer.append(GroupSym->getName());
648 Buffer.push_back(0); // separator which cannot occur in the name
649 if (LinkedToSym)
650 Buffer.append(LinkedToSym->getName());
652 StringRef UniqueMapKey = StringRef(Buffer);
653 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
654 } else if (!Section.isSingleStringRef()) {
655 SmallString<128> Buffer;
656 StringRef UniqueMapKey = Section.toStringRef(Buffer);
657 SectionLen = UniqueMapKey.size();
658 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
659 } else {
660 StringRef UniqueMapKey = Section.getSingleStringRef();
661 SectionLen = UniqueMapKey.size();
662 EntryNewPair = ELFUniquingMap.try_emplace(UniqueMapKey);
663 }
664
665 if (!EntryNewPair.second)
666 return EntryNewPair.first->second;
667
668 StringRef CachedName = EntryNewPair.first->getKey().take_front(SectionLen);
669
670 MCSectionELF *Result =
671 createELFSectionImpl(CachedName, Type, Flags, EntrySize, GroupSym,
672 IsComdat, UniqueID, LinkedToSym);
673 EntryNewPair.first->second = Result;
674
675 recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
676 Result->getUniqueID(), Result->getEntrySize());
677
678 return Result;
679}
680
682 bool IsComdat) {
683 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0, 4, Group, IsComdat,
684 MCSection::NonUniqueID, nullptr);
685}
686
688 unsigned Flags, unsigned UniqueID,
689 unsigned EntrySize) {
690 bool IsMergeable = Flags & ELF::SHF_MERGE;
692 ELFSeenGenericMergeableSections.insert(SectionName);
693 // Minor performance optimization: avoid hash map lookup in
694 // isELFGenericMergeableSection, which will return true for SectionName.
695 IsMergeable = true;
696 }
697
698 // For mergeable sections or non-mergeable sections with a generic mergeable
699 // section name we enter their Unique ID into the ELFEntrySizeMap so that
700 // compatible globals can be assigned to the same section.
701
702 if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
703 ELFEntrySizeMap.insert(std::make_pair(
704 std::make_tuple(SectionName, Flags, EntrySize), UniqueID));
705 }
706}
707
709 return SectionName.starts_with(".rodata.str") ||
710 SectionName.starts_with(".rodata.cst");
711}
712
717
718std::optional<unsigned>
720 unsigned EntrySize) {
721 auto I = ELFEntrySizeMap.find(std::make_tuple(SectionName, Flags, EntrySize));
722 return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second)
723 : std::nullopt;
724}
725
726template <typename TAttr>
727MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
728 TAttr Attributes, MCSection *Parent,
729 bool IsVirtual) {
730 std::string UniqueName(Name);
731 if (Parent) {
732 UniqueName.append("/").append(Parent->getName());
733 if (auto *P = static_cast<MCSectionGOFF *>(Parent)->getParent())
734 UniqueName.append("/").append(P->getName());
735 }
736 // Do the lookup. If we don't have a hit, return a new section.
737 auto [Iter, Inserted] = GOFFUniquingMap.try_emplace(UniqueName);
738 if (!Inserted)
739 return Iter->second;
740
741 StringRef CachedName = StringRef(Iter->first.c_str(), Name.size());
742 MCSectionGOFF *GOFFSection = new (GOFFAllocator.Allocate())
743 MCSectionGOFF(CachedName, Kind, IsVirtual, Attributes,
744 static_cast<MCSectionGOFF *>(Parent));
745 Iter->second = GOFFSection;
746 return GOFFSection;
747}
748
749MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
750 GOFF::SDAttr SDAttributes) {
751 return getGOFFSection<GOFF::SDAttr>(Kind, Name, SDAttributes, nullptr,
752 /*IsVirtual=*/true);
753}
754
755MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
756 GOFF::EDAttr EDAttributes,
757 MCSection *Parent) {
758 return getGOFFSection<GOFF::EDAttr>(
759 Kind, Name, EDAttributes, Parent,
760 /*IsVirtual=*/EDAttributes.BindAlgorithm == GOFF::ESD_BA_Merge);
761}
762
763MCSectionGOFF *MCContext::getGOFFSection(SectionKind Kind, StringRef Name,
764 GOFF::PRAttr PRAttributes,
765 MCSection *Parent) {
766 return getGOFFSection<GOFF::PRAttr>(Kind, Name, PRAttributes, Parent,
767 /*IsVirtual=*/false);
768}
769
771 unsigned Characteristics,
772 StringRef COMDATSymName, int Selection,
773 unsigned UniqueID) {
774 MCSymbol *COMDATSymbol = nullptr;
775 if (!COMDATSymName.empty()) {
776 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
777 assert(COMDATSymbol && "COMDATSymbol is null");
778 COMDATSymName = COMDATSymbol->getName();
779 // A non-associative COMDAT is considered to define the COMDAT symbol. Check
780 // the redefinition error.
782 COMDATSymbol->isDefined() &&
783 (!COMDATSymbol->isInSection() ||
784 static_cast<const MCSectionCOFF &>(COMDATSymbol->getSection())
785 .getCOMDATSymbol() != COMDATSymbol))
786 reportError(SMLoc(), "invalid symbol redefinition");
787 }
788
789 // Do the lookup, if we have a hit, return it.
790 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
791 auto [Iter, Inserted] = COFFUniquingMap.try_emplace(T);
792 if (!Inserted)
793 return Iter->second;
794
795 StringRef CachedName = Iter->first.SectionName;
796 MCSymbol *Begin = getOrCreateSectionSymbol<MCSymbolCOFF>(Section);
797 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
798 CachedName, Characteristics, COMDATSymbol, Selection, UniqueID, Begin);
799 Iter->second = Result;
800 Begin->setFragment(&Result->getDummyFragment());
801 return Result;
802}
803
805 unsigned Characteristics) {
806 return getCOFFSection(Section, Characteristics, "", 0,
808}
809
811 const MCSymbol *KeySym,
812 unsigned UniqueID) {
813 // Return the normal section if we don't have to be associative or unique.
814 if (!KeySym && UniqueID == MCSection::NonUniqueID)
815 return Sec;
816
817 // If we have a key symbol, make an associative section with the same name and
818 // kind as the normal section.
819 unsigned Characteristics = Sec->getCharacteristics();
820 if (KeySym) {
821 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
822 return getCOFFSection(Sec->getName(), Characteristics, KeySym->getName(),
824 }
825
826 return getCOFFSection(Sec->getName(), Characteristics, "", 0, UniqueID);
827}
828
830 unsigned Flags, const Twine &Group,
831 unsigned UniqueID) {
832 MCSymbolWasm *GroupSym = nullptr;
833 if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
834 GroupSym = static_cast<MCSymbolWasm *>(getOrCreateSymbol(Group));
835 GroupSym->setComdat(true);
836 if (K.isMetadata() && !GroupSym->getType().has_value()) {
837 // Comdat group symbol associated with a custom section is a section
838 // symbol (not a data symbol).
840 }
841 }
842
843 return getWasmSection(Section, K, Flags, GroupSym, UniqueID);
844}
845
847 unsigned Flags,
848 const MCSymbolWasm *GroupSym,
849 unsigned UniqueID) {
850 StringRef Group = "";
851 if (GroupSym)
852 Group = GroupSym->getName();
853 // Do the lookup, if we have a hit, return it.
854 auto IterBool = WasmUniquingMap.insert(
855 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
856 auto &Entry = *IterBool.first;
857 if (!IterBool.second)
858 return Entry.second;
859
860 StringRef CachedName = Entry.first.SectionName;
861
862 MCSymbol *Begin = createRenamableSymbol(CachedName, true, false);
863 // Begin always has a different name than CachedName... see #48596.
864 getSymbolTableEntry(Begin->getName()).second.Symbol = Begin;
865 static_cast<MCSymbolWasm *>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
866
867 MCSectionWasm *Result = new (WasmAllocator.Allocate())
868 MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
869 Entry.second = Result;
870
871 return Result;
872}
873
875 XCOFF::CsectProperties CsectProp) const {
876 return XCOFFUniquingMap.count(
877 XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
878}
879
881 StringRef Section, SectionKind Kind,
882 std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
883 std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
884 bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
885 assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
886
887 // Do the lookup. If we have a hit, return it.
888 auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
889 IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)
890 : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
891 nullptr));
892 auto &Entry = *IterBool.first;
893 if (!IterBool.second) {
894 MCSectionXCOFF *ExistedEntry = Entry.second;
895 if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
896 report_fatal_error("section's multiply symbols policy does not match");
897
898 return ExistedEntry;
899 }
900
901 // Otherwise, return a new section.
902 StringRef CachedName = Entry.first.SectionName;
903 MCSymbolXCOFF *QualName = nullptr;
904 // Debug section don't have storage class attribute.
905 if (IsDwarfSec)
906 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(CachedName));
907 else
908 QualName = static_cast<MCSymbolXCOFF *>(getOrCreateSymbol(
909 CachedName + "[" +
910 XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
911
912 // QualName->getUnqualifiedName() and CachedName are the same except when
913 // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
914 MCSectionXCOFF *Result = nullptr;
915 if (IsDwarfSec)
916 Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
917 QualName->getUnqualifiedName(), Kind, QualName,
918 *DwarfSectionSubtypeFlags, QualName, CachedName, MultiSymbolsAllowed);
919 else
920 Result = new (XCOFFAllocator.Allocate())
921 MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
922 CsectProp->Type, Kind, QualName, nullptr, CachedName,
923 MultiSymbolsAllowed);
924
925 Entry.second = Result;
926 return Result;
927}
928
930 MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate()) MCSectionSPIRV();
931 return Result;
932}
933
935 SectionKind K) {
936 // Do the lookup, if we have a hit, return it.
937 auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);
938 if (!ItInsertedPair.second)
939 return ItInsertedPair.first->second;
940
941 auto MapIt = ItInsertedPair.first;
942 // Grab the name from the StringMap. Since the Section is going to keep a
943 // copy of this StringRef we need to make sure the underlying string stays
944 // alive as long as we need it.
945 StringRef Name = MapIt->first();
946 MapIt->second =
947 new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);
948
949 // The first fragment will store the header
950 return MapIt->second;
951}
952
954 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
955}
956
957void MCContext::addDebugPrefixMapEntry(const std::string &From,
958 const std::string &To) {
959 DebugPrefixMap.emplace_back(From, To);
960}
961
963 for (const auto &[From, To] : llvm::reverse(DebugPrefixMap))
964 if (llvm::sys::path::replace_path_prefix(Path, From, To))
965 break;
966}
967
969 const auto &DebugPrefixMap = this->DebugPrefixMap;
970 if (DebugPrefixMap.empty())
971 return;
972
973 // Remap compilation directory.
974 remapDebugPath(CompilationDir);
975
976 // Remap MCDwarfDirs and RootFile.Name in all compilation units.
978 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {
979 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {
980 P = Dir;
982 Dir = std::string(P);
983 }
984
985 // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
986 // DW_AT_decl_file for DWARF v5 generated for assembly source.
987 P = CUIDTablePair.second.getRootFile().Name;
989 CUIDTablePair.second.getRootFile().Name = std::string(P);
990 }
991}
992
993//===----------------------------------------------------------------------===//
994// Dwarf Management
995//===----------------------------------------------------------------------===//
996
1000
1004
1006 // MCDwarf needs the root file as well as the compilation directory.
1007 // If we find a '.file 0' directive that will supersede these values.
1008 std::optional<MD5::MD5Result> Cksum;
1009 if (getDwarfVersion() >= 5) {
1010 MD5 Hash;
1011 MD5::MD5Result Sum;
1012 Hash.update(Buffer);
1013 Hash.final(Sum);
1014 Cksum = Sum;
1015 }
1016 // Canonicalize the root filename. It cannot be empty, and should not
1017 // repeat the compilation dir.
1018 // The MCContext ctor initializes MainFileName to the name associated with
1019 // the SrcMgr's main file ID, which might be the same as InputFileName (and
1020 // possibly include directory components).
1021 // Or, MainFileName might have been overridden by a -main-file-name option,
1022 // which is supposed to be just a base filename with no directory component.
1023 // So, if the InputFileName and MainFileName are not equal, assume
1024 // MainFileName is a substitute basename and replace the last component.
1025 SmallString<1024> FileNameBuf = InputFileName;
1026 if (FileNameBuf.empty() || FileNameBuf == "-")
1027 FileNameBuf = "<stdin>";
1028 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
1031 }
1032 StringRef FileName = FileNameBuf;
1033 if (FileName.consume_front(getCompilationDir()))
1034 if (llvm::sys::path::is_separator(FileName.front()))
1035 FileName = FileName.drop_front();
1036 assert(!FileName.empty());
1038 /*CUID=*/0, getCompilationDir(), FileName, Cksum, std::nullopt);
1039}
1040
1041/// getDwarfFile - takes a file name and number to place in the dwarf file and
1042/// directory tables. If the file number has already been allocated it is an
1043/// error and zero is returned and the client reports the error, else the
1044/// allocated file number is returned. The file numbers may be in any order.
1047 unsigned FileNumber,
1048 std::optional<MD5::MD5Result> Checksum,
1049 std::optional<StringRef> Source, unsigned CUID) {
1050 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
1051 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
1052 FileNumber);
1053}
1054
1055/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
1056/// currently is assigned and false otherwise.
1057bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
1058 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
1059 if (FileNumber == 0)
1060 return getDwarfVersion() >= 5;
1061 if (FileNumber >= LineTable.getMCDwarfFiles().size())
1062 return false;
1063
1064 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
1065}
1066
1067/// Remove empty sections from SectionsForRanges, to avoid generating
1068/// useless debug info for them.
1070 SectionsForRanges.remove_if(
1071 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
1072}
1073
1075 if (!CVContext)
1076 CVContext.reset(new CodeViewContext(this));
1077 return *CVContext;
1078}
1079
1080//===----------------------------------------------------------------------===//
1081// Error Reporting
1082//===----------------------------------------------------------------------===//
1083
1085 assert(DiagHandler && "MCContext::DiagHandler is not set");
1086 bool UseInlineSrcMgr = false;
1087 const SourceMgr *SMP = nullptr;
1088 if (SrcMgr) {
1089 SMP = SrcMgr;
1090 } else if (InlineSrcMgr) {
1091 SMP = InlineSrcMgr.get();
1092 UseInlineSrcMgr = true;
1093 } else
1094 llvm_unreachable("Either SourceMgr should be available");
1095 DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
1096}
1097
1098void MCContext::reportCommon(
1099 SMLoc Loc,
1100 std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
1101 // * MCContext::SrcMgr is null when the MC layer emits machine code for input
1102 // other than assembly file, say, for .c/.cpp/.ll/.bc.
1103 // * MCContext::InlineSrcMgr is null when the inline asm is not used.
1104 // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
1105 // and MCContext::InlineSrcMgr are null.
1106 SourceMgr SM;
1107 const SourceMgr *SMP = &SM;
1108 bool UseInlineSrcMgr = false;
1109
1110 // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
1111 // For MC-only execution, only SrcMgr is used;
1112 // For non MC-only execution, InlineSrcMgr is only ctor'd if there is
1113 // inline asm in the IR.
1114 if (Loc.isValid()) {
1115 if (SrcMgr) {
1116 SMP = SrcMgr;
1117 } else if (InlineSrcMgr) {
1118 SMP = InlineSrcMgr.get();
1119 UseInlineSrcMgr = true;
1120 } else
1121 llvm_unreachable("Either SourceMgr should be available");
1122 }
1123
1124 SMDiagnostic D;
1125 GetMessage(D, SMP);
1126 DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
1127}
1128
1130 HadError = true;
1131 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1132 D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
1133 });
1134}
1135
1137 if (getTargetOptions().MCNoWarn)
1138 return;
1139 if (getTargetOptions().MCFatalWarnings) {
1140 reportError(Loc, Msg);
1141 } else {
1142 reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
1143 D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
1144 });
1145 }
1146}
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 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 void reportError(SMLoc L, const Twine &Msg)
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:569
static constexpr unsigned NonUniqueID
Definition MCSection.h:574
StringRef getName() const
Definition MCSection.h:639
MCSymbol * getBeginSymbol()
Definition MCSection.h:642
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:408
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