MCContext.cpp 36 KB

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