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