Home | History | Annotate | Line # | Download | only in MC
      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/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/BinaryFormat/XCOFF.h"
     19 #include "llvm/MC/MCAsmInfo.h"
     20 #include "llvm/MC/MCCodeView.h"
     21 #include "llvm/MC/MCDwarf.h"
     22 #include "llvm/MC/MCExpr.h"
     23 #include "llvm/MC/MCFragment.h"
     24 #include "llvm/MC/MCLabel.h"
     25 #include "llvm/MC/MCObjectFileInfo.h"
     26 #include "llvm/MC/MCSectionCOFF.h"
     27 #include "llvm/MC/MCSectionELF.h"
     28 #include "llvm/MC/MCSectionMachO.h"
     29 #include "llvm/MC/MCSectionWasm.h"
     30 #include "llvm/MC/MCSectionXCOFF.h"
     31 #include "llvm/MC/MCStreamer.h"
     32 #include "llvm/MC/MCSymbol.h"
     33 #include "llvm/MC/MCSymbolCOFF.h"
     34 #include "llvm/MC/MCSymbolELF.h"
     35 #include "llvm/MC/MCSymbolMachO.h"
     36 #include "llvm/MC/MCSymbolWasm.h"
     37 #include "llvm/MC/MCSymbolXCOFF.h"
     38 #include "llvm/MC/SectionKind.h"
     39 #include "llvm/Support/Casting.h"
     40 #include "llvm/Support/CommandLine.h"
     41 #include "llvm/Support/ErrorHandling.h"
     42 #include "llvm/Support/MemoryBuffer.h"
     43 #include "llvm/Support/Path.h"
     44 #include "llvm/Support/Signals.h"
     45 #include "llvm/Support/SourceMgr.h"
     46 #include "llvm/Support/raw_ostream.h"
     47 #include <cassert>
     48 #include <cstdlib>
     49 #include <tuple>
     50 #include <utility>
     51 
     52 using namespace llvm;
     53 
     54 static cl::opt<char*>
     55 AsSecureLogFileName("as-secure-log-file-name",
     56         cl::desc("As secure log file name (initialized from "
     57                  "AS_SECURE_LOG_FILE env variable)"),
     58         cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
     59 
     60 static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
     61                                std::vector<const MDNode *> &) {
     62   SMD.print(nullptr, errs());
     63 }
     64 
     65 MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,
     66                      const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
     67                      const SourceMgr *mgr, MCTargetOptions const *TargetOpts,
     68                      bool DoAutoReset)
     69     : TT(TheTriple), SrcMgr(mgr), InlineSrcMgr(nullptr),
     70       DiagHandler(defaultDiagHandler), MAI(mai), MRI(mri), MSTI(msti),
     71       Symbols(Allocator), UsedNames(Allocator),
     72       InlineAsmUsedLabelNames(Allocator),
     73       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
     74       AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
     75   SecureLogFile = AsSecureLogFileName;
     76 
     77   if (SrcMgr && SrcMgr->getNumBuffers())
     78     MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
     79                                    ->getBufferIdentifier());
     80 
     81   switch (TheTriple.getObjectFormat()) {
     82   case Triple::MachO:
     83     Env = IsMachO;
     84     break;
     85   case Triple::COFF:
     86     if (!TheTriple.isOSWindows())
     87       report_fatal_error(
     88           "Cannot initialize MC for non-Windows COFF object files.");
     89 
     90     Env = IsCOFF;
     91     break;
     92   case Triple::ELF:
     93     Env = IsELF;
     94     break;
     95   case Triple::Wasm:
     96     Env = IsWasm;
     97     break;
     98   case Triple::XCOFF:
     99     Env = IsXCOFF;
    100     break;
    101   case Triple::GOFF:
    102     report_fatal_error("Cannot initialize MC for GOFF object file format");
    103     break;
    104   case Triple::UnknownObjectFormat:
    105     report_fatal_error("Cannot initialize MC for unknown object file format.");
    106     break;
    107   }
    108 }
    109 
    110 MCContext::~MCContext() {
    111   if (AutoReset)
    112     reset();
    113 
    114   // NOTE: The symbols are all allocated out of a bump pointer allocator,
    115   // we don't need to free them here.
    116 }
    117 
    118 void MCContext::initInlineSourceManager() {
    119   if (!InlineSrcMgr)
    120     InlineSrcMgr.reset(new SourceMgr());
    121 }
    122 
    123 //===----------------------------------------------------------------------===//
    124 // Module Lifetime Management
    125 //===----------------------------------------------------------------------===//
    126 
    127 void MCContext::reset() {
    128   SrcMgr = nullptr;
    129   InlineSrcMgr.reset();
    130   LocInfos.clear();
    131   DiagHandler = defaultDiagHandler;
    132 
    133   // Call the destructors so the fragments are freed
    134   COFFAllocator.DestroyAll();
    135   ELFAllocator.DestroyAll();
    136   MachOAllocator.DestroyAll();
    137   XCOFFAllocator.DestroyAll();
    138   MCInstAllocator.DestroyAll();
    139 
    140   MCSubtargetAllocator.DestroyAll();
    141   InlineAsmUsedLabelNames.clear();
    142   UsedNames.clear();
    143   Symbols.clear();
    144   Allocator.Reset();
    145   Instances.clear();
    146   CompilationDir.clear();
    147   MainFileName.clear();
    148   MCDwarfLineTablesCUMap.clear();
    149   SectionsForRanges.clear();
    150   MCGenDwarfLabelEntries.clear();
    151   DwarfDebugFlags = StringRef();
    152   DwarfCompileUnitID = 0;
    153   CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
    154 
    155   CVContext.reset();
    156 
    157   MachOUniquingMap.clear();
    158   ELFUniquingMap.clear();
    159   COFFUniquingMap.clear();
    160   WasmUniquingMap.clear();
    161   XCOFFUniquingMap.clear();
    162 
    163   ELFEntrySizeMap.clear();
    164   ELFSeenGenericMergeableSections.clear();
    165 
    166   NextID.clear();
    167   AllowTemporaryLabels = true;
    168   DwarfLocSeen = false;
    169   GenDwarfForAssembly = false;
    170   GenDwarfFileNumber = 0;
    171 
    172   HadError = false;
    173 }
    174 
    175 //===----------------------------------------------------------------------===//
    176 // MCInst Management
    177 //===----------------------------------------------------------------------===//
    178 
    179 MCInst *MCContext::createMCInst() {
    180   return new (MCInstAllocator.Allocate()) MCInst;
    181 }
    182 
    183 //===----------------------------------------------------------------------===//
    184 // Symbol Manipulation
    185 //===----------------------------------------------------------------------===//
    186 
    187 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
    188   SmallString<128> NameSV;
    189   StringRef NameRef = Name.toStringRef(NameSV);
    190 
    191   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
    192 
    193   MCSymbol *&Sym = Symbols[NameRef];
    194   if (!Sym)
    195     Sym = createSymbol(NameRef, false, false);
    196 
    197   return Sym;
    198 }
    199 
    200 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
    201                                                  unsigned Idx) {
    202   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
    203                            "$frame_escape_" + Twine(Idx));
    204 }
    205 
    206 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
    207   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
    208                            "$parent_frame_offset");
    209 }
    210 
    211 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
    212   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
    213                            FuncName);
    214 }
    215 
    216 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
    217                                       bool IsTemporary) {
    218   static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
    219                 "MCSymbol classes must be trivially destructible");
    220   static_assert(std::is_trivially_destructible<MCSymbolELF>(),
    221                 "MCSymbol classes must be trivially destructible");
    222   static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
    223                 "MCSymbol classes must be trivially destructible");
    224   static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
    225                 "MCSymbol classes must be trivially destructible");
    226   static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
    227                 "MCSymbol classes must be trivially destructible");
    228 
    229   switch (getObjectFileType()) {
    230   case MCContext::IsCOFF:
    231     return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
    232   case MCContext::IsELF:
    233     return new (Name, *this) MCSymbolELF(Name, IsTemporary);
    234   case MCContext::IsMachO:
    235     return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
    236   case MCContext::IsWasm:
    237     return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
    238   case MCContext::IsXCOFF:
    239     return createXCOFFSymbolImpl(Name, IsTemporary);
    240   }
    241   return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
    242                                     IsTemporary);
    243 }
    244 
    245 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
    246                                   bool CanBeUnnamed) {
    247   if (CanBeUnnamed && !UseNamesOnTempLabels)
    248     return createSymbolImpl(nullptr, true);
    249 
    250   // Determine whether this is a user written assembler temporary or normal
    251   // label, if used.
    252   bool IsTemporary = CanBeUnnamed;
    253   if (AllowTemporaryLabels && !IsTemporary)
    254     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
    255 
    256   SmallString<128> NewName = Name;
    257   bool AddSuffix = AlwaysAddSuffix;
    258   unsigned &NextUniqueID = NextID[Name];
    259   while (true) {
    260     if (AddSuffix) {
    261       NewName.resize(Name.size());
    262       raw_svector_ostream(NewName) << NextUniqueID++;
    263     }
    264     auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
    265     if (NameEntry.second || !NameEntry.first->second) {
    266       // Ok, we found a name.
    267       // Mark it as used for a non-section symbol.
    268       NameEntry.first->second = true;
    269       // Have the MCSymbol object itself refer to the copy of the string that is
    270       // embedded in the UsedNames entry.
    271       return createSymbolImpl(&*NameEntry.first, IsTemporary);
    272     }
    273     assert(IsTemporary && "Cannot rename non-temporary symbols");
    274     AddSuffix = true;
    275   }
    276   llvm_unreachable("Infinite loop");
    277 }
    278 
    279 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
    280   SmallString<128> NameSV;
    281   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
    282   return createSymbol(NameSV, AlwaysAddSuffix, true);
    283 }
    284 
    285 MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {
    286   SmallString<128> NameSV;
    287   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
    288   return createSymbol(NameSV, true, false);
    289 }
    290 
    291 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
    292   SmallString<128> NameSV;
    293   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
    294   return createSymbol(NameSV, true, false);
    295 }
    296 
    297 MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
    298 
    299 MCSymbol *MCContext::createNamedTempSymbol() {
    300   return createNamedTempSymbol("tmp");
    301 }
    302 
    303 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
    304   MCLabel *&Label = Instances[LocalLabelVal];
    305   if (!Label)
    306     Label = new (*this) MCLabel(0);
    307   return Label->incInstance();
    308 }
    309 
    310 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
    311   MCLabel *&Label = Instances[LocalLabelVal];
    312   if (!Label)
    313     Label = new (*this) MCLabel(0);
    314   return Label->getInstance();
    315 }
    316 
    317 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
    318                                                        unsigned Instance) {
    319   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
    320   if (!Sym)
    321     Sym = createNamedTempSymbol();
    322   return Sym;
    323 }
    324 
    325 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
    326   unsigned Instance = NextInstance(LocalLabelVal);
    327   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
    328 }
    329 
    330 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
    331                                                bool Before) {
    332   unsigned Instance = GetInstance(LocalLabelVal);
    333   if (!Before)
    334     ++Instance;
    335   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
    336 }
    337 
    338 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
    339   SmallString<128> NameSV;
    340   StringRef NameRef = Name.toStringRef(NameSV);
    341   return Symbols.lookup(NameRef);
    342 }
    343 
    344 void MCContext::setSymbolValue(MCStreamer &Streamer,
    345                               StringRef Sym,
    346                               uint64_t Val) {
    347   auto Symbol = getOrCreateSymbol(Sym);
    348   Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
    349 }
    350 
    351 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
    352   InlineAsmUsedLabelNames[Sym->getName()] = Sym;
    353 }
    354 
    355 MCSymbolXCOFF *
    356 MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
    357                                  bool IsTemporary) {
    358   if (!Name)
    359     return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
    360 
    361   StringRef OriginalName = Name->first();
    362   if (OriginalName.startswith("._Renamed..") ||
    363       OriginalName.startswith("_Renamed.."))
    364     reportError(SMLoc(), "invalid symbol name from source");
    365 
    366   if (MAI->isValidUnquotedName(OriginalName))
    367     return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
    368 
    369   // Now we have a name that contains invalid character(s) for XCOFF symbol.
    370   // Let's replace with something valid, but save the original name so that
    371   // we could still use the original name in the symbol table.
    372   SmallString<128> InvalidName(OriginalName);
    373 
    374   // If it's an entry point symbol, we will keep the '.'
    375   // in front for the convention purpose. Otherwise, add "_Renamed.."
    376   // as prefix to signal this is an renamed symbol.
    377   const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.';
    378   SmallString<128> ValidName =
    379       StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
    380 
    381   // Append the hex values of '_' and invalid characters with "_Renamed..";
    382   // at the same time replace invalid characters with '_'.
    383   for (size_t I = 0; I < InvalidName.size(); ++I) {
    384     if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
    385       raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
    386       InvalidName[I] = '_';
    387     }
    388   }
    389 
    390   // Skip entry point symbol's '.' as we already have a '.' in front of
    391   // "_Renamed".
    392   if (IsEntryPoint)
    393     ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
    394   else
    395     ValidName.append(InvalidName);
    396 
    397   auto NameEntry = UsedNames.insert(std::make_pair(ValidName, true));
    398   assert((NameEntry.second || !NameEntry.first->second) &&
    399          "This name is used somewhere else.");
    400   // Mark the name as used for a non-section symbol.
    401   NameEntry.first->second = true;
    402   // Have the MCSymbol object itself refer to the copy of the string
    403   // that is embedded in the UsedNames entry.
    404   MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this)
    405       MCSymbolXCOFF(&*NameEntry.first, IsTemporary);
    406   XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
    407   return XSym;
    408 }
    409 
    410 //===----------------------------------------------------------------------===//
    411 // Section Management
    412 //===----------------------------------------------------------------------===//
    413 
    414 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
    415                                            unsigned TypeAndAttributes,
    416                                            unsigned Reserved2, SectionKind Kind,
    417                                            const char *BeginSymName) {
    418   // We unique sections by their segment/section pair.  The returned section
    419   // may not have the same flags as the requested section, if so this should be
    420   // diagnosed by the client as an error.
    421 
    422   // Form the name to look up.
    423   assert(Section.size() <= 16 && "section name is too long");
    424   assert(!memchr(Section.data(), '\0', Section.size()) &&
    425          "section name cannot contain NUL");
    426 
    427   // Do the lookup, if we have a hit, return it.
    428   auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
    429   if (!R.second)
    430     return R.first->second;
    431 
    432   MCSymbol *Begin = nullptr;
    433   if (BeginSymName)
    434     Begin = createTempSymbol(BeginSymName, false);
    435 
    436   // Otherwise, return a new section.
    437   StringRef Name = R.first->first();
    438   R.first->second = new (MachOAllocator.Allocate())
    439       MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
    440                      TypeAndAttributes, Reserved2, Kind, Begin);
    441   return R.first->second;
    442 }
    443 
    444 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
    445   StringRef GroupName;
    446   if (const MCSymbol *Group = Section->getGroup())
    447     GroupName = Group->getName();
    448 
    449   // This function is only used by .debug*, which should not have the
    450   // SHF_LINK_ORDER flag.
    451   unsigned UniqueID = Section->getUniqueID();
    452   ELFUniquingMap.erase(
    453       ELFSectionKey{Section->getName(), GroupName, "", UniqueID});
    454   auto I = ELFUniquingMap
    455                .insert(std::make_pair(
    456                    ELFSectionKey{Name, GroupName, "", UniqueID}, Section))
    457                .first;
    458   StringRef CachedName = I->first.SectionName;
    459   const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
    460 }
    461 
    462 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
    463                                               unsigned Flags, SectionKind K,
    464                                               unsigned EntrySize,
    465                                               const MCSymbolELF *Group,
    466                                               bool Comdat, unsigned UniqueID,
    467                                               const MCSymbolELF *LinkedToSym) {
    468   MCSymbolELF *R;
    469   MCSymbol *&Sym = Symbols[Section];
    470   // A section symbol can not redefine regular symbols. There may be multiple
    471   // sections with the same name, in which case the first such section wins.
    472   if (Sym && Sym->isDefined() &&
    473       (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
    474     reportError(SMLoc(), "invalid symbol redefinition");
    475   if (Sym && Sym->isUndefined()) {
    476     R = cast<MCSymbolELF>(Sym);
    477   } else {
    478     auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
    479     R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
    480     if (!Sym)
    481       Sym = R;
    482   }
    483   R->setBinding(ELF::STB_LOCAL);
    484   R->setType(ELF::STT_SECTION);
    485 
    486   auto *Ret = new (ELFAllocator.Allocate())
    487       MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
    488                    R, LinkedToSym);
    489 
    490   auto *F = new MCDataFragment();
    491   Ret->getFragmentList().insert(Ret->begin(), F);
    492   F->setParent(Ret);
    493   R->setFragment(F);
    494 
    495   return Ret;
    496 }
    497 
    498 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
    499                                              unsigned Flags, unsigned EntrySize,
    500                                              const MCSymbolELF *Group,
    501                                              const MCSectionELF *RelInfoSection) {
    502   StringMap<bool>::iterator I;
    503   bool Inserted;
    504   std::tie(I, Inserted) =
    505       RelSecNames.insert(std::make_pair(Name.str(), true));
    506 
    507   return createELFSectionImpl(
    508       I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
    509       true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
    510 }
    511 
    512 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
    513                                             const Twine &Suffix, unsigned Type,
    514                                             unsigned Flags,
    515                                             unsigned EntrySize) {
    516   return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
    517                        /*IsComdat=*/true);
    518 }
    519 
    520 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
    521                                        unsigned Flags, unsigned EntrySize,
    522                                        const Twine &Group, bool IsComdat,
    523                                        unsigned UniqueID,
    524                                        const MCSymbolELF *LinkedToSym) {
    525   MCSymbolELF *GroupSym = nullptr;
    526   if (!Group.isTriviallyEmpty() && !Group.str().empty())
    527     GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
    528 
    529   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
    530                        UniqueID, LinkedToSym);
    531 }
    532 
    533 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
    534                                        unsigned Flags, unsigned EntrySize,
    535                                        const MCSymbolELF *GroupSym,
    536                                        bool IsComdat, unsigned UniqueID,
    537                                        const MCSymbolELF *LinkedToSym) {
    538   StringRef Group = "";
    539   if (GroupSym)
    540     Group = GroupSym->getName();
    541   assert(!(LinkedToSym && LinkedToSym->getName().empty()));
    542   // Do the lookup, if we have a hit, return it.
    543   auto IterBool = ELFUniquingMap.insert(std::make_pair(
    544       ELFSectionKey{Section.str(), Group,
    545                     LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
    546       nullptr));
    547   auto &Entry = *IterBool.first;
    548   if (!IterBool.second)
    549     return Entry.second;
    550 
    551   StringRef CachedName = Entry.first.SectionName;
    552 
    553   SectionKind Kind;
    554   if (Flags & ELF::SHF_ARM_PURECODE)
    555     Kind = SectionKind::getExecuteOnly();
    556   else if (Flags & ELF::SHF_EXECINSTR)
    557     Kind = SectionKind::getText();
    558   else
    559     Kind = SectionKind::getReadOnly();
    560 
    561   MCSectionELF *Result =
    562       createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
    563                            IsComdat, UniqueID, LinkedToSym);
    564   Entry.second = Result;
    565 
    566   recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
    567                                 Result->getUniqueID(), Result->getEntrySize());
    568 
    569   return Result;
    570 }
    571 
    572 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
    573                                                bool IsComdat) {
    574   return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
    575                               SectionKind::getReadOnly(), 4, Group, IsComdat,
    576                               MCSection::NonUniqueID, nullptr);
    577 }
    578 
    579 void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
    580                                               unsigned Flags, unsigned UniqueID,
    581                                               unsigned EntrySize) {
    582   bool IsMergeable = Flags & ELF::SHF_MERGE;
    583   if (IsMergeable && (UniqueID == GenericSectionID))
    584     ELFSeenGenericMergeableSections.insert(SectionName);
    585 
    586   // For mergeable sections or non-mergeable sections with a generic mergeable
    587   // section name we enter their Unique ID into the ELFEntrySizeMap so that
    588   // compatible globals can be assigned to the same section.
    589   if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
    590     ELFEntrySizeMap.insert(std::make_pair(
    591         ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
    592   }
    593 }
    594 
    595 bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
    596   return SectionName.startswith(".rodata.str") ||
    597          SectionName.startswith(".rodata.cst");
    598 }
    599 
    600 bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
    601   return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
    602          ELFSeenGenericMergeableSections.count(SectionName);
    603 }
    604 
    605 Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName,
    606                                                        unsigned Flags,
    607                                                        unsigned EntrySize) {
    608   auto I = ELFEntrySizeMap.find(
    609       MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
    610   return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None;
    611 }
    612 
    613 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
    614                                          unsigned Characteristics,
    615                                          SectionKind Kind,
    616                                          StringRef COMDATSymName, int Selection,
    617                                          unsigned UniqueID,
    618                                          const char *BeginSymName) {
    619   MCSymbol *COMDATSymbol = nullptr;
    620   if (!COMDATSymName.empty()) {
    621     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
    622     COMDATSymName = COMDATSymbol->getName();
    623   }
    624 
    625 
    626   // Do the lookup, if we have a hit, return it.
    627   COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
    628   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
    629   auto Iter = IterBool.first;
    630   if (!IterBool.second)
    631     return Iter->second;
    632 
    633   MCSymbol *Begin = nullptr;
    634   if (BeginSymName)
    635     Begin = createTempSymbol(BeginSymName, false);
    636 
    637   StringRef CachedName = Iter->first.SectionName;
    638   MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
    639       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
    640 
    641   Iter->second = Result;
    642   return Result;
    643 }
    644 
    645 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
    646                                          unsigned Characteristics,
    647                                          SectionKind Kind,
    648                                          const char *BeginSymName) {
    649   return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
    650                         BeginSymName);
    651 }
    652 
    653 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
    654                                                     const MCSymbol *KeySym,
    655                                                     unsigned UniqueID) {
    656   // Return the normal section if we don't have to be associative or unique.
    657   if (!KeySym && UniqueID == GenericSectionID)
    658     return Sec;
    659 
    660   // If we have a key symbol, make an associative section with the same name and
    661   // kind as the normal section.
    662   unsigned Characteristics = Sec->getCharacteristics();
    663   if (KeySym) {
    664     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
    665     return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
    666                           KeySym->getName(),
    667                           COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
    668   }
    669 
    670   return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
    671                         UniqueID);
    672 }
    673 
    674 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
    675                                          unsigned Flags, const Twine &Group,
    676                                          unsigned UniqueID,
    677                                          const char *BeginSymName) {
    678   MCSymbolWasm *GroupSym = nullptr;
    679   if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
    680     GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
    681     GroupSym->setComdat(true);
    682   }
    683 
    684   return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
    685 }
    686 
    687 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
    688                                          unsigned Flags,
    689                                          const MCSymbolWasm *GroupSym,
    690                                          unsigned UniqueID,
    691                                          const char *BeginSymName) {
    692   StringRef Group = "";
    693   if (GroupSym)
    694     Group = GroupSym->getName();
    695   // Do the lookup, if we have a hit, return it.
    696   auto IterBool = WasmUniquingMap.insert(
    697       std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
    698   auto &Entry = *IterBool.first;
    699   if (!IterBool.second)
    700     return Entry.second;
    701 
    702   StringRef CachedName = Entry.first.SectionName;
    703 
    704   MCSymbol *Begin = createSymbol(CachedName, true, false);
    705   Symbols[Begin->getName()] = Begin;
    706   cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
    707 
    708   MCSectionWasm *Result = new (WasmAllocator.Allocate())
    709       MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
    710   Entry.second = Result;
    711 
    712   auto *F = new MCDataFragment();
    713   Result->getFragmentList().insert(Result->begin(), F);
    714   F->setParent(Result);
    715   Begin->setFragment(F);
    716 
    717   return Result;
    718 }
    719 
    720 MCSectionXCOFF *MCContext::getXCOFFSection(
    721     StringRef Section, SectionKind Kind,
    722     Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
    723     const char *BeginSymName,
    724     Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
    725   bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue();
    726   assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!");
    727 
    728   // Do the lookup. If we have a hit, return it.
    729   auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
    730       IsDwarfSec
    731           ? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue())
    732           : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
    733       nullptr));
    734   auto &Entry = *IterBool.first;
    735   if (!IterBool.second) {
    736     MCSectionXCOFF *ExistedEntry = Entry.second;
    737     if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
    738       report_fatal_error("section's multiply symbols policy does not match");
    739 
    740     return ExistedEntry;
    741   }
    742 
    743   // Otherwise, return a new section.
    744   StringRef CachedName = Entry.first.SectionName;
    745   MCSymbolXCOFF *QualName = nullptr;
    746   // Debug section don't have storage class attribute.
    747   if (IsDwarfSec)
    748     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
    749   else
    750     QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
    751         CachedName + "[" +
    752         XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
    753 
    754   MCSymbol *Begin = nullptr;
    755   if (BeginSymName)
    756     Begin = createTempSymbol(BeginSymName, false);
    757 
    758   // QualName->getUnqualifiedName() and CachedName are the same except when
    759   // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
    760   MCSectionXCOFF *Result = nullptr;
    761   if (IsDwarfSec)
    762     Result = new (XCOFFAllocator.Allocate())
    763         MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName,
    764                        DwarfSectionSubtypeFlags.getValue(), Begin, CachedName,
    765                        MultiSymbolsAllowed);
    766   else
    767     Result = new (XCOFFAllocator.Allocate())
    768         MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
    769                        CsectProp->Type, Kind, QualName, Begin, CachedName,
    770                        MultiSymbolsAllowed);
    771 
    772   Entry.second = Result;
    773 
    774   auto *F = new MCDataFragment();
    775   Result->getFragmentList().insert(Result->begin(), F);
    776   F->setParent(Result);
    777 
    778   if (Begin)
    779     Begin->setFragment(F);
    780 
    781   return Result;
    782 }
    783 
    784 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
    785   return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
    786 }
    787 
    788 void MCContext::addDebugPrefixMapEntry(const std::string &From,
    789                                        const std::string &To) {
    790   DebugPrefixMap.insert(std::make_pair(From, To));
    791 }
    792 
    793 void MCContext::RemapDebugPaths() {
    794   const auto &DebugPrefixMap = this->DebugPrefixMap;
    795   if (DebugPrefixMap.empty())
    796     return;
    797 
    798   const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
    799     SmallString<256> P(Path);
    800     for (const auto &Entry : DebugPrefixMap) {
    801       if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second)) {
    802         Path = P.str().str();
    803         break;
    804       }
    805     }
    806   };
    807 
    808   // Remap compilation directory.
    809   std::string CompDir = std::string(CompilationDir.str());
    810   RemapDebugPath(CompDir);
    811   CompilationDir = CompDir;
    812 
    813   // Remap MCDwarfDirs in all compilation units.
    814   for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
    815     for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
    816       RemapDebugPath(Dir);
    817 }
    818 
    819 //===----------------------------------------------------------------------===//
    820 // Dwarf Management
    821 //===----------------------------------------------------------------------===//
    822 
    823 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
    824   // MCDwarf needs the root file as well as the compilation directory.
    825   // If we find a '.file 0' directive that will supersede these values.
    826   Optional<MD5::MD5Result> Cksum;
    827   if (getDwarfVersion() >= 5) {
    828     MD5 Hash;
    829     MD5::MD5Result Sum;
    830     Hash.update(Buffer);
    831     Hash.final(Sum);
    832     Cksum = Sum;
    833   }
    834   // Canonicalize the root filename. It cannot be empty, and should not
    835   // repeat the compilation dir.
    836   // The MCContext ctor initializes MainFileName to the name associated with
    837   // the SrcMgr's main file ID, which might be the same as InputFileName (and
    838   // possibly include directory components).
    839   // Or, MainFileName might have been overridden by a -main-file-name option,
    840   // which is supposed to be just a base filename with no directory component.
    841   // So, if the InputFileName and MainFileName are not equal, assume
    842   // MainFileName is a substitute basename and replace the last component.
    843   SmallString<1024> FileNameBuf = InputFileName;
    844   if (FileNameBuf.empty() || FileNameBuf == "-")
    845     FileNameBuf = "<stdin>";
    846   if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
    847     llvm::sys::path::remove_filename(FileNameBuf);
    848     llvm::sys::path::append(FileNameBuf, getMainFileName());
    849   }
    850   StringRef FileName = FileNameBuf;
    851   if (FileName.consume_front(getCompilationDir()))
    852     if (llvm::sys::path::is_separator(FileName.front()))
    853       FileName = FileName.drop_front();
    854   assert(!FileName.empty());
    855   setMCLineTableRootFile(
    856       /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
    857 }
    858 
    859 /// getDwarfFile - takes a file name and number to place in the dwarf file and
    860 /// directory tables.  If the file number has already been allocated it is an
    861 /// error and zero is returned and the client reports the error, else the
    862 /// allocated file number is returned.  The file numbers may be in any order.
    863 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
    864                                            StringRef FileName,
    865                                            unsigned FileNumber,
    866                                            Optional<MD5::MD5Result> Checksum,
    867                                            Optional<StringRef> Source,
    868                                            unsigned CUID) {
    869   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
    870   return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
    871                           FileNumber);
    872 }
    873 
    874 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
    875 /// currently is assigned and false otherwise.
    876 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
    877   const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
    878   if (FileNumber == 0)
    879     return getDwarfVersion() >= 5;
    880   if (FileNumber >= LineTable.getMCDwarfFiles().size())
    881     return false;
    882 
    883   return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
    884 }
    885 
    886 /// Remove empty sections from SectionsForRanges, to avoid generating
    887 /// useless debug info for them.
    888 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
    889   SectionsForRanges.remove_if(
    890       [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
    891 }
    892 
    893 CodeViewContext &MCContext::getCVContext() {
    894   if (!CVContext.get())
    895     CVContext.reset(new CodeViewContext);
    896   return *CVContext.get();
    897 }
    898 
    899 //===----------------------------------------------------------------------===//
    900 // Error Reporting
    901 //===----------------------------------------------------------------------===//
    902 
    903 void MCContext::diagnose(const SMDiagnostic &SMD) {
    904   assert(DiagHandler && "MCContext::DiagHandler is not set");
    905   bool UseInlineSrcMgr = false;
    906   const SourceMgr *SMP = nullptr;
    907   if (SrcMgr) {
    908     SMP = SrcMgr;
    909   } else if (InlineSrcMgr) {
    910     SMP = InlineSrcMgr.get();
    911     UseInlineSrcMgr = true;
    912   } else
    913     llvm_unreachable("Either SourceMgr should be available");
    914   DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
    915 }
    916 
    917 void MCContext::reportCommon(
    918     SMLoc Loc,
    919     std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
    920   // * MCContext::SrcMgr is null when the MC layer emits machine code for input
    921   //   other than assembly file, say, for .c/.cpp/.ll/.bc.
    922   // * MCContext::InlineSrcMgr is null when the inline asm is not used.
    923   // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
    924   //   and MCContext::InlineSrcMgr are null.
    925   SourceMgr SM;
    926   const SourceMgr *SMP = &SM;
    927   bool UseInlineSrcMgr = false;
    928 
    929   // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
    930   //        For MC-only execution, only SrcMgr is used;
    931   //        For non MC-only execution, InlineSrcMgr is only ctor'd if there is
    932   //        inline asm in the IR.
    933   if (Loc.isValid()) {
    934     if (SrcMgr) {
    935       SMP = SrcMgr;
    936     } else if (InlineSrcMgr) {
    937       SMP = InlineSrcMgr.get();
    938       UseInlineSrcMgr = true;
    939     } else
    940       llvm_unreachable("Either SourceMgr should be available");
    941   }
    942 
    943   SMDiagnostic D;
    944   GetMessage(D, SMP);
    945   DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
    946 }
    947 
    948 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
    949   HadError = true;
    950   reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
    951     D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
    952   });
    953 }
    954 
    955 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
    956   if (TargetOptions && TargetOptions->MCNoWarn)
    957     return;
    958   if (TargetOptions && TargetOptions->MCFatalWarnings) {
    959     reportError(Loc, Msg);
    960   } else {
    961     reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
    962       D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
    963     });
    964   }
    965 }
    966 
    967 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
    968   reportError(Loc, Msg);
    969 
    970   // If we reached here, we are failing ungracefully. Run the interrupt handlers
    971   // to make sure any special cleanups get done, in particular that we remove
    972   // files registered with RemoveFileOnSignal.
    973   sys::RunInterruptHandlers();
    974   exit(1);
    975 }
    976