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 MCContext::MCContext(const MCAsmInfo *mai, const MCRegisterInfo *mri,
61                      const MCObjectFileInfo *mofi, const SourceMgr *mgr,
62                      MCTargetOptions const *TargetOpts, bool DoAutoReset)
63     : SrcMgr(mgr), InlineSrcMgr(nullptr), MAI(mai), MRI(mri), MOFI(mofi),
64       Symbols(Allocator), UsedNames(Allocator),
65       InlineAsmUsedLabelNames(Allocator),
66       CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
67       AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
68   SecureLogFile = AsSecureLogFileName;
69 
70   if (SrcMgr && SrcMgr->getNumBuffers())
71     MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
72                                    ->getBufferIdentifier());
73 }
74 
75 MCContext::~MCContext() {
76   if (AutoReset)
77     reset();
78 
79   // NOTE: The symbols are all allocated out of a bump pointer allocator,
80   // we don't need to free them here.
81 }
82 
83 //===----------------------------------------------------------------------===//
84 // Module Lifetime Management
85 //===----------------------------------------------------------------------===//
86 
87 void MCContext::reset() {
88   // Call the destructors so the fragments are freed
89   COFFAllocator.DestroyAll();
90   ELFAllocator.DestroyAll();
91   MachOAllocator.DestroyAll();
92   XCOFFAllocator.DestroyAll();
93 
94   MCSubtargetAllocator.DestroyAll();
95   InlineAsmUsedLabelNames.clear();
96   UsedNames.clear();
97   Symbols.clear();
98   Allocator.Reset();
99   Instances.clear();
100   CompilationDir.clear();
101   MainFileName.clear();
102   MCDwarfLineTablesCUMap.clear();
103   SectionsForRanges.clear();
104   MCGenDwarfLabelEntries.clear();
105   DwarfDebugFlags = StringRef();
106   DwarfCompileUnitID = 0;
107   CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
108 
109   CVContext.reset();
110 
111   MachOUniquingMap.clear();
112   ELFUniquingMap.clear();
113   COFFUniquingMap.clear();
114   WasmUniquingMap.clear();
115   XCOFFUniquingMap.clear();
116 
117   NextID.clear();
118   AllowTemporaryLabels = true;
119   DwarfLocSeen = false;
120   GenDwarfForAssembly = false;
121   GenDwarfFileNumber = 0;
122 
123   HadError = false;
124 }
125 
126 //===----------------------------------------------------------------------===//
127 // Symbol Manipulation
128 //===----------------------------------------------------------------------===//
129 
130 MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
131   SmallString<128> NameSV;
132   StringRef NameRef = Name.toStringRef(NameSV);
133 
134   assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
135 
136   MCSymbol *&Sym = Symbols[NameRef];
137   if (!Sym)
138     Sym = createSymbol(NameRef, false, false);
139 
140   return Sym;
141 }
142 
143 MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
144                                                  unsigned Idx) {
145   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
146                            "$frame_escape_" + Twine(Idx));
147 }
148 
149 MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
150   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
151                            "$parent_frame_offset");
152 }
153 
154 MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
155   return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
156                            FuncName);
157 }
158 
159 MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
160                                       bool IsTemporary) {
161   if (MOFI) {
162     switch (MOFI->getObjectFileType()) {
163     case MCObjectFileInfo::IsCOFF:
164       return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
165     case MCObjectFileInfo::IsELF:
166       return new (Name, *this) MCSymbolELF(Name, IsTemporary);
167     case MCObjectFileInfo::IsMachO:
168       return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
169     case MCObjectFileInfo::IsWasm:
170       return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
171     case MCObjectFileInfo::IsXCOFF:
172       return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
173     }
174   }
175   return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
176                                     IsTemporary);
177 }
178 
179 MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
180                                   bool CanBeUnnamed) {
181   if (CanBeUnnamed && !UseNamesOnTempLabels)
182     return createSymbolImpl(nullptr, true);
183 
184   // Determine whether this is a user written assembler temporary or normal
185   // label, if used.
186   bool IsTemporary = CanBeUnnamed;
187   if (AllowTemporaryLabels && !IsTemporary)
188     IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
189 
190   SmallString<128> NewName = Name;
191   bool AddSuffix = AlwaysAddSuffix;
192   unsigned &NextUniqueID = NextID[Name];
193   while (true) {
194     if (AddSuffix) {
195       NewName.resize(Name.size());
196       raw_svector_ostream(NewName) << NextUniqueID++;
197     }
198     auto NameEntry = UsedNames.insert(std::make_pair(NewName, true));
199     if (NameEntry.second || !NameEntry.first->second) {
200       // Ok, we found a name.
201       // Mark it as used for a non-section symbol.
202       NameEntry.first->second = true;
203       // Have the MCSymbol object itself refer to the copy of the string that is
204       // embedded in the UsedNames entry.
205       return createSymbolImpl(&*NameEntry.first, IsTemporary);
206     }
207     assert(IsTemporary && "Cannot rename non-temporary symbols");
208     AddSuffix = true;
209   }
210   llvm_unreachable("Infinite loop");
211 }
212 
213 MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
214                                       bool CanBeUnnamed) {
215   SmallString<128> NameSV;
216   raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
217   return createSymbol(NameSV, AlwaysAddSuffix, CanBeUnnamed);
218 }
219 
220 MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
221   SmallString<128> NameSV;
222   raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
223   return createSymbol(NameSV, true, false);
224 }
225 
226 MCSymbol *MCContext::createTempSymbol(bool CanBeUnnamed) {
227   return createTempSymbol("tmp", true, CanBeUnnamed);
228 }
229 
230 unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
231   MCLabel *&Label = Instances[LocalLabelVal];
232   if (!Label)
233     Label = new (*this) MCLabel(0);
234   return Label->incInstance();
235 }
236 
237 unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
238   MCLabel *&Label = Instances[LocalLabelVal];
239   if (!Label)
240     Label = new (*this) MCLabel(0);
241   return Label->getInstance();
242 }
243 
244 MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
245                                                        unsigned Instance) {
246   MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
247   if (!Sym)
248     Sym = createTempSymbol(false);
249   return Sym;
250 }
251 
252 MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
253   unsigned Instance = NextInstance(LocalLabelVal);
254   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
255 }
256 
257 MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
258                                                bool Before) {
259   unsigned Instance = GetInstance(LocalLabelVal);
260   if (!Before)
261     ++Instance;
262   return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
263 }
264 
265 MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
266   SmallString<128> NameSV;
267   StringRef NameRef = Name.toStringRef(NameSV);
268   return Symbols.lookup(NameRef);
269 }
270 
271 void MCContext::setSymbolValue(MCStreamer &Streamer,
272                               StringRef Sym,
273                               uint64_t Val) {
274   auto Symbol = getOrCreateSymbol(Sym);
275   Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
276 }
277 
278 void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
279   InlineAsmUsedLabelNames[Sym->getName()] = Sym;
280 }
281 
282 //===----------------------------------------------------------------------===//
283 // Section Management
284 //===----------------------------------------------------------------------===//
285 
286 MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
287                                            unsigned TypeAndAttributes,
288                                            unsigned Reserved2, SectionKind Kind,
289                                            const char *BeginSymName) {
290   // We unique sections by their segment/section pair.  The returned section
291   // may not have the same flags as the requested section, if so this should be
292   // diagnosed by the client as an error.
293 
294   // Form the name to look up.
295   SmallString<64> Name;
296   Name += Segment;
297   Name.push_back(',');
298   Name += Section;
299 
300   // Do the lookup, if we have a hit, return it.
301   MCSectionMachO *&Entry = MachOUniquingMap[Name];
302   if (Entry)
303     return Entry;
304 
305   MCSymbol *Begin = nullptr;
306   if (BeginSymName)
307     Begin = createTempSymbol(BeginSymName, false);
308 
309   // Otherwise, return a new section.
310   return Entry = new (MachOAllocator.Allocate()) MCSectionMachO(
311              Segment, Section, TypeAndAttributes, Reserved2, Kind, Begin);
312 }
313 
314 void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
315   StringRef GroupName;
316   if (const MCSymbol *Group = Section->getGroup())
317     GroupName = Group->getName();
318 
319   // This function is only used by .debug*, which should not have the
320   // SHF_LINK_ORDER flag.
321   unsigned UniqueID = Section->getUniqueID();
322   ELFUniquingMap.erase(
323       ELFSectionKey{Section->getSectionName(), GroupName, "", UniqueID});
324   auto I = ELFUniquingMap
325                .insert(std::make_pair(
326                    ELFSectionKey{Name, GroupName, "", UniqueID}, Section))
327                .first;
328   StringRef CachedName = I->first.SectionName;
329   const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
330 }
331 
332 MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
333                                               unsigned Flags, SectionKind K,
334                                               unsigned EntrySize,
335                                               const MCSymbolELF *Group,
336                                               unsigned UniqueID,
337                                               const MCSymbolELF *LinkedToSym) {
338   MCSymbolELF *R;
339   MCSymbol *&Sym = Symbols[Section];
340   // A section symbol can not redefine regular symbols. There may be multiple
341   // sections with the same name, in which case the first such section wins.
342   if (Sym && Sym->isDefined() &&
343       (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
344     reportError(SMLoc(), "invalid symbol redefinition");
345   if (Sym && Sym->isUndefined()) {
346     R = cast<MCSymbolELF>(Sym);
347   } else {
348     auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
349     R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
350     if (!Sym)
351       Sym = R;
352   }
353   R->setBinding(ELF::STB_LOCAL);
354   R->setType(ELF::STT_SECTION);
355 
356   auto *Ret = new (ELFAllocator.Allocate()) MCSectionELF(
357       Section, Type, Flags, K, EntrySize, Group, UniqueID, R, LinkedToSym);
358 
359   auto *F = new MCDataFragment();
360   Ret->getFragmentList().insert(Ret->begin(), F);
361   F->setParent(Ret);
362   R->setFragment(F);
363 
364   return Ret;
365 }
366 
367 MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
368                                              unsigned Flags, unsigned EntrySize,
369                                              const MCSymbolELF *Group,
370                                              const MCSectionELF *RelInfoSection) {
371   StringMap<bool>::iterator I;
372   bool Inserted;
373   std::tie(I, Inserted) =
374       RelSecNames.insert(std::make_pair(Name.str(), true));
375 
376   return createELFSectionImpl(
377       I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
378       true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
379 }
380 
381 MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
382                                             const Twine &Suffix, unsigned Type,
383                                             unsigned Flags,
384                                             unsigned EntrySize) {
385   return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix);
386 }
387 
388 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
389                                        unsigned Flags, unsigned EntrySize,
390                                        const Twine &Group, unsigned UniqueID,
391                                        const MCSymbolELF *LinkedToSym) {
392   MCSymbolELF *GroupSym = nullptr;
393   if (!Group.isTriviallyEmpty() && !Group.str().empty())
394     GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
395 
396   return getELFSection(Section, Type, Flags, EntrySize, GroupSym, UniqueID,
397                        LinkedToSym);
398 }
399 
400 MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
401                                        unsigned Flags, unsigned EntrySize,
402                                        const MCSymbolELF *GroupSym,
403                                        unsigned UniqueID,
404                                        const MCSymbolELF *LinkedToSym) {
405   StringRef Group = "";
406   if (GroupSym)
407     Group = GroupSym->getName();
408   // Do the lookup, if we have a hit, return it.
409   auto IterBool = ELFUniquingMap.insert(std::make_pair(
410       ELFSectionKey{Section.str(), Group,
411                     LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
412       nullptr));
413   auto &Entry = *IterBool.first;
414   if (!IterBool.second)
415     return Entry.second;
416 
417   StringRef CachedName = Entry.first.SectionName;
418 
419   SectionKind Kind;
420   if (Flags & ELF::SHF_ARM_PURECODE)
421     Kind = SectionKind::getExecuteOnly();
422   else if (Flags & ELF::SHF_EXECINSTR)
423     Kind = SectionKind::getText();
424   else
425     Kind = SectionKind::getReadOnly();
426 
427   MCSectionELF *Result =
428       createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
429                            UniqueID, LinkedToSym);
430   Entry.second = Result;
431   return Result;
432 }
433 
434 MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group) {
435   return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
436                               SectionKind::getReadOnly(), 4, Group,
437                               MCSection::NonUniqueID, nullptr);
438 }
439 
440 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
441                                          unsigned Characteristics,
442                                          SectionKind Kind,
443                                          StringRef COMDATSymName, int Selection,
444                                          unsigned UniqueID,
445                                          const char *BeginSymName) {
446   MCSymbol *COMDATSymbol = nullptr;
447   if (!COMDATSymName.empty()) {
448     COMDATSymbol = getOrCreateSymbol(COMDATSymName);
449     COMDATSymName = COMDATSymbol->getName();
450   }
451 
452 
453   // Do the lookup, if we have a hit, return it.
454   COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
455   auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
456   auto Iter = IterBool.first;
457   if (!IterBool.second)
458     return Iter->second;
459 
460   MCSymbol *Begin = nullptr;
461   if (BeginSymName)
462     Begin = createTempSymbol(BeginSymName, false);
463 
464   StringRef CachedName = Iter->first.SectionName;
465   MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
466       CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
467 
468   Iter->second = Result;
469   return Result;
470 }
471 
472 MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
473                                          unsigned Characteristics,
474                                          SectionKind Kind,
475                                          const char *BeginSymName) {
476   return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
477                         BeginSymName);
478 }
479 
480 MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
481                                                     const MCSymbol *KeySym,
482                                                     unsigned UniqueID) {
483   // Return the normal section if we don't have to be associative or unique.
484   if (!KeySym && UniqueID == GenericSectionID)
485     return Sec;
486 
487   // If we have a key symbol, make an associative section with the same name and
488   // kind as the normal section.
489   unsigned Characteristics = Sec->getCharacteristics();
490   if (KeySym) {
491     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
492     return getCOFFSection(Sec->getSectionName(), Characteristics,
493                           Sec->getKind(), KeySym->getName(),
494                           COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
495   }
496 
497   return getCOFFSection(Sec->getSectionName(), Characteristics, Sec->getKind(),
498                         "", 0, UniqueID);
499 }
500 
501 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
502                                          const Twine &Group, unsigned UniqueID,
503                                          const char *BeginSymName) {
504   MCSymbolWasm *GroupSym = nullptr;
505   if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
506     GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
507     GroupSym->setComdat(true);
508   }
509 
510   return getWasmSection(Section, K, GroupSym, UniqueID, BeginSymName);
511 }
512 
513 MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
514                                          const MCSymbolWasm *GroupSym,
515                                          unsigned UniqueID,
516                                          const char *BeginSymName) {
517   StringRef Group = "";
518   if (GroupSym)
519     Group = GroupSym->getName();
520   // Do the lookup, if we have a hit, return it.
521   auto IterBool = WasmUniquingMap.insert(
522       std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
523   auto &Entry = *IterBool.first;
524   if (!IterBool.second)
525     return Entry.second;
526 
527   StringRef CachedName = Entry.first.SectionName;
528 
529   MCSymbol *Begin = createSymbol(CachedName, false, false);
530   cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
531 
532   MCSectionWasm *Result = new (WasmAllocator.Allocate())
533       MCSectionWasm(CachedName, Kind, GroupSym, UniqueID, Begin);
534   Entry.second = Result;
535 
536   auto *F = new MCDataFragment();
537   Result->getFragmentList().insert(Result->begin(), F);
538   F->setParent(Result);
539   Begin->setFragment(F);
540 
541   return Result;
542 }
543 
544 MCSectionXCOFF *MCContext::getXCOFFSection(StringRef Section,
545                                            XCOFF::StorageMappingClass SMC,
546                                            XCOFF::SymbolType Type,
547                                            XCOFF::StorageClass SC,
548                                            SectionKind Kind,
549                                            const char *BeginSymName) {
550   // Do the lookup. If we have a hit, return it.
551   auto IterBool = XCOFFUniquingMap.insert(
552       std::make_pair(XCOFFSectionKey{Section.str(), SMC}, nullptr));
553   auto &Entry = *IterBool.first;
554   if (!IterBool.second)
555     return Entry.second;
556 
557   // Otherwise, return a new section.
558   StringRef CachedName = Entry.first.SectionName;
559   MCSymbol *QualName = getOrCreateSymbol(
560       CachedName + "[" + XCOFF::getMappingClassString(SMC) + "]");
561 
562   MCSymbol *Begin = nullptr;
563   if (BeginSymName)
564     Begin = createTempSymbol(BeginSymName, false);
565 
566   MCSectionXCOFF *Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
567       CachedName, SMC, Type, SC, Kind, cast<MCSymbolXCOFF>(QualName), Begin);
568   Entry.second = Result;
569 
570   auto *F = new MCDataFragment();
571   Result->getFragmentList().insert(Result->begin(), F);
572   F->setParent(Result);
573 
574   if (Begin)
575     Begin->setFragment(F);
576 
577   return Result;
578 }
579 
580 MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
581   return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
582 }
583 
584 void MCContext::addDebugPrefixMapEntry(const std::string &From,
585                                        const std::string &To) {
586   DebugPrefixMap.insert(std::make_pair(From, To));
587 }
588 
589 void MCContext::RemapDebugPaths() {
590   const auto &DebugPrefixMap = this->DebugPrefixMap;
591   const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
592     for (const auto &Entry : DebugPrefixMap)
593       if (StringRef(Path).startswith(Entry.first)) {
594         std::string RemappedPath =
595             (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
596         Path.swap(RemappedPath);
597       }
598   };
599 
600   // Remap compilation directory.
601   std::string CompDir = std::string(CompilationDir.str());
602   RemapDebugPath(CompDir);
603   CompilationDir = CompDir;
604 
605   // Remap MCDwarfDirs in all compilation units.
606   for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
607     for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
608       RemapDebugPath(Dir);
609 }
610 
611 //===----------------------------------------------------------------------===//
612 // Dwarf Management
613 //===----------------------------------------------------------------------===//
614 
615 void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
616   // MCDwarf needs the root file as well as the compilation directory.
617   // If we find a '.file 0' directive that will supersede these values.
618   Optional<MD5::MD5Result> Cksum;
619   if (getDwarfVersion() >= 5) {
620     MD5 Hash;
621     MD5::MD5Result Sum;
622     Hash.update(Buffer);
623     Hash.final(Sum);
624     Cksum = Sum;
625   }
626   // Canonicalize the root filename. It cannot be empty, and should not
627   // repeat the compilation dir.
628   // The MCContext ctor initializes MainFileName to the name associated with
629   // the SrcMgr's main file ID, which might be the same as InputFileName (and
630   // possibly include directory components).
631   // Or, MainFileName might have been overridden by a -main-file-name option,
632   // which is supposed to be just a base filename with no directory component.
633   // So, if the InputFileName and MainFileName are not equal, assume
634   // MainFileName is a substitute basename and replace the last component.
635   SmallString<1024> FileNameBuf = InputFileName;
636   if (FileNameBuf.empty() || FileNameBuf == "-")
637     FileNameBuf = "<stdin>";
638   if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
639     llvm::sys::path::remove_filename(FileNameBuf);
640     llvm::sys::path::append(FileNameBuf, getMainFileName());
641   }
642   StringRef FileName = FileNameBuf;
643   if (FileName.consume_front(getCompilationDir()))
644     if (llvm::sys::path::is_separator(FileName.front()))
645       FileName = FileName.drop_front();
646   assert(!FileName.empty());
647   setMCLineTableRootFile(
648       /*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
649 }
650 
651 /// getDwarfFile - takes a file name and number to place in the dwarf file and
652 /// directory tables.  If the file number has already been allocated it is an
653 /// error and zero is returned and the client reports the error, else the
654 /// allocated file number is returned.  The file numbers may be in any order.
655 Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
656                                            StringRef FileName,
657                                            unsigned FileNumber,
658                                            Optional<MD5::MD5Result> Checksum,
659                                            Optional<StringRef> Source,
660                                            unsigned CUID) {
661   MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
662   return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
663                           FileNumber);
664 }
665 
666 /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
667 /// currently is assigned and false otherwise.
668 bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
669   const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
670   if (FileNumber == 0)
671     return getDwarfVersion() >= 5;
672   if (FileNumber >= LineTable.getMCDwarfFiles().size())
673     return false;
674 
675   return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
676 }
677 
678 /// Remove empty sections from SectionsForRanges, to avoid generating
679 /// useless debug info for them.
680 void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
681   SectionsForRanges.remove_if(
682       [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
683 }
684 
685 CodeViewContext &MCContext::getCVContext() {
686   if (!CVContext.get())
687     CVContext.reset(new CodeViewContext);
688   return *CVContext.get();
689 }
690 
691 //===----------------------------------------------------------------------===//
692 // Error Reporting
693 //===----------------------------------------------------------------------===//
694 
695 void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
696   HadError = true;
697 
698   // If we have a source manager use it. Otherwise, try using the inline source
699   // manager.
700   // If that fails, use the generic report_fatal_error().
701   if (SrcMgr)
702     SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
703   else if (InlineSrcMgr)
704     InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
705   else
706     report_fatal_error(Msg, false);
707 }
708 
709 void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
710   if (TargetOptions && TargetOptions->MCNoWarn)
711     return;
712   if (TargetOptions && TargetOptions->MCFatalWarnings)
713     reportError(Loc, Msg);
714   else {
715     // If we have a source manager use it. Otherwise, try using the inline
716     // source manager.
717     if (SrcMgr)
718       SrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
719     else if (InlineSrcMgr)
720       InlineSrcMgr->PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
721   }
722 }
723 
724 void MCContext::reportFatalError(SMLoc Loc, const Twine &Msg) {
725   reportError(Loc, Msg);
726 
727   // If we reached here, we are failing ungracefully. Run the interrupt handlers
728   // to make sure any special cleanups get done, in particular that we remove
729   // files registered with RemoveFileOnSignal.
730   sys::RunInterruptHandlers();
731   exit(1);
732 }
733