[ARM] More MVE compare vector splat combines for ANDs
[llvm-complete.git] / lib / MC / MCContext.cpp
blobecd12fdc689ecd152ffa7510f8dc07cc7a5a5ae7
1 //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCContext.h"
10 #include "llvm/ADT/Optional.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/BinaryFormat/COFF.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCCodeView.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFragment.h"
23 #include "llvm/MC/MCLabel.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCSectionWasm.h"
29 #include "llvm/MC/MCSectionXCOFF.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCSymbolCOFF.h"
33 #include "llvm/MC/MCSymbolELF.h"
34 #include "llvm/MC/MCSymbolMachO.h"
35 #include "llvm/MC/MCSymbolWasm.h"
36 #include "llvm/MC/MCSymbolXCOFF.h"
37 #include "llvm/MC/SectionKind.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/SourceMgr.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <cassert>
47 #include <cstdlib>
48 #include <tuple>
49 #include <utility>
51 using namespace llvm;
53 static cl::opt<char*>
54 AsSecureLogFileName("as-secure-log-file-name",
55 cl::desc("As secure log file name (initialized from "
56 "AS_SECURE_LOG_FILE env variable)"),
57 cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
59 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
60 const MCObjectFileInfo *mofi, const SourceMgr *mgr,
61 bool DoAutoReset)
62 : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi),
63 Symbols(Allocator), UsedNames(Allocator),
64 CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
65 AutoReset(DoAutoReset) {
66 SecureLogFile = AsSecureLogFileName;
68 if (SrcMgr && SrcMgr->getNumBuffers())
69 MainFileName =
70 SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())->getBufferIdentifier();
73 MCContext::~MCContext() {
74 if (AutoReset)
75 reset();
77 // NOTE: The symbols are all allocated out of a bump pointer allocator,
78 // we don't need to free them here.
81 //===----------------------------------------------------------------------===//
82 // Module Lifetime Management
83 //===----------------------------------------------------------------------===//
85 void MCContext::reset() {
86 // Call the destructors so the fragments are freed
87 COFFAllocator.DestroyAll();
88 ELFAllocator.DestroyAll();
89 MachOAllocator.DestroyAll();
90 XCOFFAllocator.DestroyAll();
92 MCSubtargetAllocator.DestroyAll();
93 UsedNames.clear();
94 Symbols.clear();
95 Allocator.Reset();
96 Instances.clear();
97 CompilationDir.clear();
98 MainFileName.clear();
99 MCDwarfLineTablesCUMap.clear();
100 SectionsForRanges.clear();
101 MCGenDwarfLabelEntries.clear();
102 DwarfDebugFlags = StringRef();
103 DwarfCompileUnitID = 0;
104 CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
106 CVContext.reset();
108 MachOUniquingMap.clear();
109 ELFUniquingMap.clear();
110 COFFUniquingMap.clear();
111 WasmUniquingMap.clear();
112 XCOFFUniquingMap.clear();
114 NextID.clear();
115 AllowTemporaryLabels = true;
116 DwarfLocSeen = false;
117 GenDwarfForAssembly = false;
118 GenDwarfFileNumber = 0;
120 HadError = false;
123 //===----------------------------------------------------------------------===//
124 // Symbol Manipulation
125 //===----------------------------------------------------------------------===//
127 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
128 SmallString<128> NameSV;
129 StringRef NameRef = Name.toStringRef(NameSV);
131 assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
133 MCSymbol *&Sym = Symbols[NameRef];
134 if (!Sym)
135 Sym = createSymbol(NameRef, false, false);
137 return Sym;
140 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
141 unsigned Idx) {
142 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
143 "$frame_escape_" + Twine(Idx));
146 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
147 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
148 "$parent_frame_offset");
151 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
152 return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
153 FuncName);
156 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
157 bool IsTemporary) {
158 if (MOFI) {
159 switch (MOFI->getObjectFileType()) {
160 case MCObjectFileInfo::IsCOFF:
161 return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
162 case MCObjectFileInfo::IsELF:
163 return new (Name, *this) MCSymbolELF(Name, IsTemporary);
164 case MCObjectFileInfo::IsMachO:
165 return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
166 case MCObjectFileInfo::IsWasm:
167 return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
168 case MCObjectFileInfo::IsXCOFF:
169 return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
172 return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
173 IsTemporary);
176 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
177 bool CanBeUnnamed) {
178 if (CanBeUnnamed && !UseNamesOnTempLabels)
179 return createSymbolImpl(nullptr, true);
181 // Determine whether this is a user written assembler temporary or normal
182 // label, if used.
183 bool IsTemporary = CanBeUnnamed;
184 if (AllowTemporaryLabels && !IsTemporary)
185 IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
187 SmallString<128> NewName = Name;
188 bool AddSuffix = AlwaysAddSuffix;
189 unsigned &NextUniqueID = NextID[Name];
190 while (true) {
191 if (AddSuffix) {
192 NewName.resize(Name.size());
193 raw_svector_ostream(NewName) << NextUniqueID++;
195 auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
196 if (NameEntry.second || !NameEntry.first->second) {
197 // Ok, we found a name.
198 // Mark it as used for a non-section symbol.
199 NameEntry.first->second = true;
200 // Have the MCSymbol object itself refer to the copy of the string that is
201 // embedded in the UsedNames entry.
202 return createSymbolImpl(&*NameEntry.first, IsTemporary);
204 assert(IsTemporary && "Cannot rename non-temporary symbols");
205 AddSuffix = true;
207 llvm_unreachable("Infinite loop");
210 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
211 bool CanBeUnnamed) {
212 SmallString<128> NameSV;
213 raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
214 return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
217 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
218 SmallString<128> NameSV;
219 raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
220 return createSymbol(NameSV, true, false);
223 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
224 return createTempSymbol("tmp", true, CanBeUnnamed);
227 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
228 MCLabel *&Label = Instances[LocalLabelVal];
229 if (!Label)
230 Label = new (*this) MCLabel(0);
231 return Label->incInstance();
234 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
235 MCLabel *&Label = Instances[LocalLabelVal];
236 if (!Label)
237 Label = new (*this) MCLabel(0);
238 return Label->getInstance();
241 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
242 unsigned Instance) {
243 MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
244 if (!Sym)
245 Sym = createTempSymbol(false);
246 return Sym;
249 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
250 unsigned Instance = NextInstance(LocalLabelVal);
251 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
254 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
255 bool Before) {
256 unsigned Instance = GetInstance(LocalLabelVal);
257 if (!Before)
258 ++Instance;
259 return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
262 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
263 SmallString<128> NameSV;
264 StringRef NameRef = Name.toStringRef(NameSV);
265 return Symbols.lookup(NameRef);
268 void MCContext::setSymbolValue(MCStreamer &Streamer,
269 StringRef Sym,
270 uint64_t Val) {
271 auto Symbol = getOrCreateSymbol(Sym);
272 Streamer.EmitAssignment(Symbol, MCConstantExpr::create(Val, *this));
275 //===----------------------------------------------------------------------===//
276 // Section Management
277 //===----------------------------------------------------------------------===//
279 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
280 unsigned TypeAndAttributes,
281 unsigned Reserved2, SectionKind Kind,
282 const char *BeginSymName) {
283 // We unique sections by their segment/section pair. The returned section
284 // may not have the same flags as the requested section, if so this should be
285 // diagnosed by the client as an error.
287 // Form the name to look up.
288 SmallString<64> Name;
289 Name += Segment;
290 Name.push_back(',');
291 Name += Section;
293 // Do the lookup, if we have a hit, return it.
294 MCSectionMachO *&Entry = MachOUniquingMap[Name];
295 if (Entry)
296 return Entry;
298 MCSymbol *Begin = nullptr;
299 if (BeginSymName)
300 Begin = createTempSymbol(BeginSymName, false);
302 // Otherwise, return a new section.
303 return Entry = new (MachOAllocator.Allocate()) MCSectionMachO(
304 Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin);
307 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
308 StringRef GroupName;
309 if (const MCSymbol *Group = Section->getGroup())
310 GroupName = Group->getName();
312 unsigned UniqueID = Section->getUniqueID();
313 ELFUniquingMap.erase(
314 ELFSectionKey{Section->getSectionName(), GroupName, UniqueID});
315 auto I = ELFUniquingMap.insert(std::make_pair(
316 ELFSectionKey{Name, GroupName, UniqueID},
317 Section))
318 .first;
319 StringRef CachedName = I->first.SectionName;
320 const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
323 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
324 unsigned Flags, SectionKind K,
325 unsigned EntrySize,
326 const MCSymbolELF *Group,
327 unsigned UniqueID,
328 const MCSymbolELF *Associated) {
329 MCSymbolELF *R;
330 MCSymbol *&Sym = Symbols[Section];
331 // A section symbol can not redefine regular symbols. There may be multiple
332 // sections with the same name, in which case the first such section wins.
333 if (Sym && Sym->isDefined() &&
334 (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
335 reportError(SMLoc(), "invalid symbol redefinition");
336 if (Sym && Sym->isUndefined()) {
337 R = cast<MCSymbolELF>(Sym);
338 } else {
339 auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
340 R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
341 if (!Sym)
342 Sym = R;
344 R->setBinding(ELF::STB_LOCAL);
345 R->setType(ELF::STT_SECTION);
347 auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
348 Section, Type, Flags, K, EntrySize, Group, UniqueID, R, Associated);
350 auto *F = new MCDataFragment();
351 Ret->getFragmentList().insert(Ret->begin(), F);
352 F->setParent(Ret);
353 R->setFragment(F);
355 return Ret;
358 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
359 unsigned Flags, unsigned EntrySize,
360 const MCSymbolELF *Group,
361 const MCSectionELF *RelInfoSection) {
362 StringMap<bool>::iterator I;
363 bool Inserted;
364 std::tie(I, Inserted) =
365 RelSecNames.insert(std::make_pair(Name.str(), true));
367 return createELFSectionImpl(
368 I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
369 true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
372 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
373 const Twine &Suffix, unsigned Type,
374 unsigned Flags,
375 unsigned EntrySize) {
376 return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix);
379 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
380 unsigned Flags, unsigned EntrySize,
381 const Twine &Group, unsigned UniqueID,
382 const MCSymbolELF *Associated) {
383 MCSymbolELF *GroupSym = nullptr;
384 if (!Group.isTriviallyEmpty() && !Group.str().empty())
385 GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
387 return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
388 Associated);
391 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
392 unsigned Flags, unsigned EntrySize,
393 const MCSymbolELF *GroupSym,
394 unsigned UniqueID,
395 const MCSymbolELF *Associated) {
396 StringRef Group = "";
397 if (GroupSym)
398 Group = GroupSym->getName();
399 // Do the lookup, if we have a hit, return it.
400 auto IterBool = ELFUniquingMap.insert(
401 std::make_pair(ELFSectionKey{Section.str(), Group, UniqueID}, nullptr));
402 auto &Entry = *IterBool.first;
403 if (!IterBool.second)
404 return Entry.second;
406 StringRef CachedName = Entry.first.SectionName;
408 SectionKind Kind;
409 if (Flags & ELF::SHF_ARM_PURECODE)
410 Kind = SectionKind::getExecuteOnly();
411 else if (Flags & ELF::SHF_EXECINSTR)
412 Kind = SectionKind::getText();
413 else
414 Kind = SectionKind::getReadOnly();
416 MCSectionELF *Result = createELFSectionImpl(
417 CachedName, Type, Flags, Kind, EntrySize, GroupSym, UniqueID, Associated);
418 Entry.second = Result;
419 return Result;
422 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
423 return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
424 SectionKind::getReadOnly(), 4, Group, ~0,
425 nullptr);
428 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
429 unsigned Characteristics,
430 SectionKind Kind,
431 StringRef COMDATSymName, int Selection,
432 unsigned UniqueID,
433 const char *BeginSymName) {
434 MCSymbol *COMDATSymbol = nullptr;
435 if (!COMDATSymName.empty()) {
436 COMDATSymbol = getOrCreateSymbol(COMDATSymName);
437 COMDATSymName = COMDATSymbol->getName();
441 // Do the lookup, if we have a hit, return it.
442 COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
443 auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
444 auto Iter = IterBool.first;
445 if (!IterBool.second)
446 return Iter->second;
448 MCSymbol *Begin = nullptr;
449 if (BeginSymName)
450 Begin = createTempSymbol(BeginSymName, false);
452 StringRef CachedName = Iter->first.SectionName;
453 MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
454 CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
456 Iter->second = Result;
457 return Result;
460 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
461 unsigned Characteristics,
462 SectionKind Kind,
463 const char *BeginSymName) {
464 return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
465 BeginSymName);
468 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
469 const MCSymbol *KeySym,
470 unsigned UniqueID) {
471 // Return the normal section if we don't have to be associative or unique.
472 if (!KeySym && UniqueID == GenericSectionID)
473 return Sec;
475 // If we have a key symbol, make an associative section with the same name and
476 // kind as the normal section.
477 unsigned Characteristics = Sec->getCharacteristics();
478 if (KeySym) {
479 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
480 return getCOFFSection(Sec->getSectionName(), Characteristics,
481 Sec->getKind(), KeySym->getName(),
482 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
485 return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
486 "", 0, UniqueID);
489 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
490 const Twine &Group, unsigned UniqueID,
491 const char *BeginSymName) {
492 MCSymbolWasm *GroupSym = nullptr;
493 if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
494 GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
495 GroupSym->setComdat(true);
498 return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName);
501 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
502 const MCSymbolWasm *GroupSym,
503 unsigned UniqueID,
504 const char *BeginSymName) {
505 StringRef Group = "";
506 if (GroupSym)
507 Group = GroupSym->getName();
508 // Do the lookup, if we have a hit, return it.
509 auto IterBool = WasmUniquingMap.insert(
510 std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
511 auto &Entry = *IterBool.first;
512 if (!IterBool.second)
513 return Entry.second;
515 StringRef CachedName = Entry.first.SectionName;
517 MCSymbol *Begin = createSymbol(CachedName, false, false);
518 cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
520 MCSectionWasm *Result = new (WasmAllocator.Allocate())
521 MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin);
522 Entry.second = Result;
524 auto *F = new MCDataFragment();
525 Result->getFragmentList().insert(Result->begin(), F);
526 F->setParent(Result);
527 Begin->setFragment(F);
529 return Result;
532 MCSectionXCOFF *MCContext::getXCOFFSection(StringRef Section,
533 XCOFF::StorageMappingClass SMC,
534 XCOFF::SymbolType Type,
535 SectionKind Kind,
536 const char *BeginSymName) {
537 // Do the lookup. If we have a hit, return it.
538 auto IterBool = XCOFFUniquingMap.insert(
539 std::make_pair(XCOFFSectionKey{Section.str(), SMC}, nullptr));
540 auto &Entry = *IterBool.first;
541 if (!IterBool.second)
542 return Entry.second;
544 // Otherwise, return a new section.
545 StringRef CachedName = Entry.first.SectionName;
547 MCSymbol *Begin = nullptr;
548 if (BeginSymName)
549 Begin = createTempSymbol(BeginSymName, false);
551 MCSectionXCOFF *Result = new (XCOFFAllocator.Allocate())
552 MCSectionXCOFF(CachedName, SMC, Type, Kind, Begin);
553 Entry.second = Result;
555 auto *F = new MCDataFragment();
556 Result->getFragmentList().insert(Result->begin(), F);
557 F->setParent(Result);
559 if (Begin)
560 Begin->setFragment(F);
562 return Result;
565 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
566 return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
569 void MCContext::addDebugPrefixMapEntry(const std::string &From,
570 const std::string &To) {
571 DebugPrefixMap.insert(std::make_pair(From, To));
574 void MCContext::RemapDebugPaths() {
575 const auto &DebugPrefixMap = this->DebugPrefixMap;
576 const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
577 for (const auto &Entry : DebugPrefixMap)
578 if (StringRef(Path).startswith(Entry.first)) {
579 std::string RemappedPath =
580 (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
581 Path.swap(RemappedPath);
585 // Remap compilation directory.
586 std::string CompDir = CompilationDir.str();
587 RemapDebugPath(CompDir);
588 CompilationDir = CompDir;
590 // Remap MCDwarfDirs in all compilation units.
591 for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
592 for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
593 RemapDebugPath(Dir);
596 //===----------------------------------------------------------------------===//
597 // Dwarf Management
598 //===----------------------------------------------------------------------===//
600 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
601 // MCDwarf needs the root file as well as the compilation directory.
602 // If we find a '.file 0' directive that will supersede these values.
603 Optional<MD5::MD5Result> Cksum;
604 if (getDwarfVersion() >= 5) {
605 MD5 Hash;
606 MD5::MD5Result Sum;
607 Hash.update(Buffer);
608 Hash.final(Sum);
609 Cksum = Sum;
611 // Canonicalize the root filename. It cannot be empty, and should not
612 // repeat the compilation dir.
613 // The MCContext ctor initializes MainFileName to the name associated with
614 // the SrcMgr's main file ID, which might be the same as InputFileName (and
615 // possibly include directory components).
616 // Or, MainFileName might have been overridden by a -main-file-name option,
617 // which is supposed to be just a base filename with no directory component.
618 // So, if the InputFileName and MainFileName are not equal, assume
619 // MainFileName is a substitute basename and replace the last component.
620 SmallString<1024> FileNameBuf = InputFileName;
621 if (FileNameBuf.empty() || FileNameBuf == "-")
622 FileNameBuf = "<stdin>";
623 if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
624 llvm::sys::path::remove_filename(FileNameBuf);
625 llvm::sys::path::append(FileNameBuf, getMainFileName());
627 StringRef FileName = FileNameBuf;
628 if (FileName.consume_front(getCompilationDir()))
629 if (llvm::sys::path::is_separator(FileName.front()))
630 FileName = FileName.drop_front();
631 assert(!FileName.empty());
632 setMCLineTableRootFile(
633 /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
636 /// getDwarfFile - takes a file name and number to place in the dwarf file and
637 /// directory tables. If the file number has already been allocated it is an
638 /// error and zero is returned and the client reports the error, else the
639 /// allocated file number is returned. The file numbers may be in any order.
640 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
641 StringRef FileName,
642 unsigned FileNumber,
643 Optional<MD5::MD5Result> Checksum,
644 Optional<StringRef> Source,
645 unsigned CUID) {
646 MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
647 return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
648 FileNumber);
651 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
652 /// currently is assigned and false otherwise.
653 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
654 const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
655 if (FileNumber == 0)
656 return getDwarfVersion() >= 5;
657 if (FileNumber >= LineTable.getMCDwarfFiles().size())
658 return false;
660 return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
663 /// Remove empty sections from SectionsForRanges, to avoid generating
664 /// useless debug info for them.
665 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
666 SectionsForRanges.remove_if(
667 [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
670 CodeViewContext &MCContext::getCVContext() {
671 if (!CVContext.get())
672 CVContext.reset(new CodeViewContext);
673 return *CVContext.get();
676 //===----------------------------------------------------------------------===//
677 // Error Reporting
678 //===----------------------------------------------------------------------===//
680 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
681 HadError = true;
683 // If we have a source manager use it. Otherwise, try using the inline source
684 // manager.
685 // If that fails, use the generic report_fatal_error().
686 if (SrcMgr)
687 SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
688 else if (InlineSrcMgr)
689 InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
690 else
691 report_fatal_error(Msg, false);
694 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
695 reportError(Loc, Msg);
697 // If we reached here, we are failing ungracefully. Run the interrupt handlers
698 // to make sure any special cleanups get done, in particular that we remove
699 // files registered with RemoveFileOnSignal.
700 sys::RunInterruptHandlers();
701 exit(1);