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