MCELFStreamer.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. //===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
  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. // This file assembles .s files and emits ELF .o object files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/MC/MCELFStreamer.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/BinaryFormat/ELF.h"
  16. #include "llvm/MC/MCAsmBackend.h"
  17. #include "llvm/MC/MCAsmInfo.h"
  18. #include "llvm/MC/MCAssembler.h"
  19. #include "llvm/MC/MCCodeEmitter.h"
  20. #include "llvm/MC/MCContext.h"
  21. #include "llvm/MC/MCExpr.h"
  22. #include "llvm/MC/MCFixup.h"
  23. #include "llvm/MC/MCFragment.h"
  24. #include "llvm/MC/MCObjectFileInfo.h"
  25. #include "llvm/MC/MCObjectWriter.h"
  26. #include "llvm/MC/MCSection.h"
  27. #include "llvm/MC/MCSectionELF.h"
  28. #include "llvm/MC/MCStreamer.h"
  29. #include "llvm/MC/MCSymbol.h"
  30. #include "llvm/MC/MCSymbolELF.h"
  31. #include "llvm/MC/TargetRegistry.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/LEB128.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <cassert>
  37. #include <cstdint>
  38. using namespace llvm;
  39. MCELFStreamer::MCELFStreamer(MCContext &Context,
  40. std::unique_ptr<MCAsmBackend> TAB,
  41. std::unique_ptr<MCObjectWriter> OW,
  42. std::unique_ptr<MCCodeEmitter> Emitter)
  43. : MCObjectStreamer(Context, std::move(TAB), std::move(OW),
  44. std::move(Emitter)) {}
  45. bool MCELFStreamer::isBundleLocked() const {
  46. return getCurrentSectionOnly()->isBundleLocked();
  47. }
  48. void MCELFStreamer::mergeFragment(MCDataFragment *DF,
  49. MCDataFragment *EF) {
  50. MCAssembler &Assembler = getAssembler();
  51. if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
  52. uint64_t FSize = EF->getContents().size();
  53. if (FSize > Assembler.getBundleAlignSize())
  54. report_fatal_error("Fragment can't be larger than a bundle size");
  55. uint64_t RequiredBundlePadding = computeBundlePadding(
  56. Assembler, EF, DF->getContents().size(), FSize);
  57. if (RequiredBundlePadding > UINT8_MAX)
  58. report_fatal_error("Padding cannot exceed 255 bytes");
  59. if (RequiredBundlePadding > 0) {
  60. SmallString<256> Code;
  61. raw_svector_ostream VecOS(Code);
  62. EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
  63. Assembler.writeFragmentPadding(VecOS, *EF, FSize);
  64. DF->getContents().append(Code.begin(), Code.end());
  65. }
  66. }
  67. flushPendingLabels(DF, DF->getContents().size());
  68. for (unsigned i = 0, e = EF->getFixups().size(); i != e; ++i) {
  69. EF->getFixups()[i].setOffset(EF->getFixups()[i].getOffset() +
  70. DF->getContents().size());
  71. DF->getFixups().push_back(EF->getFixups()[i]);
  72. }
  73. if (DF->getSubtargetInfo() == nullptr && EF->getSubtargetInfo())
  74. DF->setHasInstructions(*EF->getSubtargetInfo());
  75. DF->getContents().append(EF->getContents().begin(), EF->getContents().end());
  76. }
  77. void MCELFStreamer::initSections(bool NoExecStack, const MCSubtargetInfo &STI) {
  78. MCContext &Ctx = getContext();
  79. SwitchSection(Ctx.getObjectFileInfo()->getTextSection());
  80. emitCodeAlignment(Ctx.getObjectFileInfo()->getTextSectionAlignment(), &STI);
  81. if (NoExecStack)
  82. SwitchSection(Ctx.getAsmInfo()->getNonexecutableStackSection(Ctx));
  83. }
  84. void MCELFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
  85. auto *Symbol = cast<MCSymbolELF>(S);
  86. MCObjectStreamer::emitLabel(Symbol, Loc);
  87. const MCSectionELF &Section =
  88. static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
  89. if (Section.getFlags() & ELF::SHF_TLS)
  90. Symbol->setType(ELF::STT_TLS);
  91. }
  92. void MCELFStreamer::emitLabelAtPos(MCSymbol *S, SMLoc Loc, MCFragment *F,
  93. uint64_t Offset) {
  94. auto *Symbol = cast<MCSymbolELF>(S);
  95. MCObjectStreamer::emitLabelAtPos(Symbol, Loc, F, Offset);
  96. const MCSectionELF &Section =
  97. static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
  98. if (Section.getFlags() & ELF::SHF_TLS)
  99. Symbol->setType(ELF::STT_TLS);
  100. }
  101. void MCELFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
  102. // Let the target do whatever target specific stuff it needs to do.
  103. getAssembler().getBackend().handleAssemblerFlag(Flag);
  104. // Do any generic stuff we need to do.
  105. switch (Flag) {
  106. case MCAF_SyntaxUnified: return; // no-op here.
  107. case MCAF_Code16: return; // Change parsing mode; no-op here.
  108. case MCAF_Code32: return; // Change parsing mode; no-op here.
  109. case MCAF_Code64: return; // Change parsing mode; no-op here.
  110. case MCAF_SubsectionsViaSymbols:
  111. getAssembler().setSubsectionsViaSymbols(true);
  112. return;
  113. }
  114. llvm_unreachable("invalid assembler flag!");
  115. }
  116. // If bundle alignment is used and there are any instructions in the section, it
  117. // needs to be aligned to at least the bundle size.
  118. static void setSectionAlignmentForBundling(const MCAssembler &Assembler,
  119. MCSection *Section) {
  120. if (Section && Assembler.isBundlingEnabled() && Section->hasInstructions() &&
  121. Section->getAlignment() < Assembler.getBundleAlignSize())
  122. Section->setAlignment(Align(Assembler.getBundleAlignSize()));
  123. }
  124. void MCELFStreamer::changeSection(MCSection *Section,
  125. const MCExpr *Subsection) {
  126. MCSection *CurSection = getCurrentSectionOnly();
  127. if (CurSection && isBundleLocked())
  128. report_fatal_error("Unterminated .bundle_lock when changing a section");
  129. MCAssembler &Asm = getAssembler();
  130. // Ensure the previous section gets aligned if necessary.
  131. setSectionAlignmentForBundling(Asm, CurSection);
  132. auto *SectionELF = static_cast<const MCSectionELF *>(Section);
  133. const MCSymbol *Grp = SectionELF->getGroup();
  134. if (Grp)
  135. Asm.registerSymbol(*Grp);
  136. if (SectionELF->getFlags() & ELF::SHF_GNU_RETAIN)
  137. Asm.getWriter().markGnuAbi();
  138. changeSectionImpl(Section, Subsection);
  139. Asm.registerSymbol(*Section->getBeginSymbol());
  140. }
  141. void MCELFStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
  142. getAssembler().registerSymbol(*Symbol);
  143. const MCExpr *Value = MCSymbolRefExpr::create(
  144. Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
  145. Alias->setVariableValue(Value);
  146. }
  147. // When GNU as encounters more than one .type declaration for an object it seems
  148. // to use a mechanism similar to the one below to decide which type is actually
  149. // used in the object file. The greater of T1 and T2 is selected based on the
  150. // following ordering:
  151. // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
  152. // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
  153. // provided type).
  154. static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
  155. for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
  156. ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
  157. if (T1 == Type)
  158. return T2;
  159. if (T2 == Type)
  160. return T1;
  161. }
  162. return T2;
  163. }
  164. bool MCELFStreamer::emitSymbolAttribute(MCSymbol *S, MCSymbolAttr Attribute) {
  165. auto *Symbol = cast<MCSymbolELF>(S);
  166. // Adding a symbol attribute always introduces the symbol, note that an
  167. // important side effect of calling registerSymbol here is to register
  168. // the symbol with the assembler.
  169. getAssembler().registerSymbol(*Symbol);
  170. // The implementation of symbol attributes is designed to match 'as', but it
  171. // leaves much to desired. It doesn't really make sense to arbitrarily add and
  172. // remove flags, but 'as' allows this (in particular, see .desc).
  173. //
  174. // In the future it might be worth trying to make these operations more well
  175. // defined.
  176. switch (Attribute) {
  177. case MCSA_Cold:
  178. case MCSA_Extern:
  179. case MCSA_LazyReference:
  180. case MCSA_Reference:
  181. case MCSA_SymbolResolver:
  182. case MCSA_PrivateExtern:
  183. case MCSA_WeakDefinition:
  184. case MCSA_WeakDefAutoPrivate:
  185. case MCSA_Invalid:
  186. case MCSA_IndirectSymbol:
  187. return false;
  188. case MCSA_NoDeadStrip:
  189. // Ignore for now.
  190. break;
  191. case MCSA_ELF_TypeGnuUniqueObject:
  192. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  193. Symbol->setBinding(ELF::STB_GNU_UNIQUE);
  194. getAssembler().getWriter().markGnuAbi();
  195. break;
  196. case MCSA_Global:
  197. // For `.weak x; .global x`, GNU as sets the binding to STB_WEAK while we
  198. // traditionally set the binding to STB_GLOBAL. This is error-prone, so we
  199. // error on such cases. Note, we also disallow changed binding from .local.
  200. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_GLOBAL)
  201. getContext().reportError(getStartTokLoc(),
  202. Symbol->getName() +
  203. " changed binding to STB_GLOBAL");
  204. Symbol->setBinding(ELF::STB_GLOBAL);
  205. break;
  206. case MCSA_WeakReference:
  207. case MCSA_Weak:
  208. // For `.global x; .weak x`, both MC and GNU as set the binding to STB_WEAK.
  209. // We emit a warning for now but may switch to an error in the future.
  210. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_WEAK)
  211. getContext().reportWarning(
  212. getStartTokLoc(), Symbol->getName() + " changed binding to STB_WEAK");
  213. Symbol->setBinding(ELF::STB_WEAK);
  214. break;
  215. case MCSA_Local:
  216. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_LOCAL)
  217. getContext().reportError(getStartTokLoc(),
  218. Symbol->getName() +
  219. " changed binding to STB_LOCAL");
  220. Symbol->setBinding(ELF::STB_LOCAL);
  221. break;
  222. case MCSA_ELF_TypeFunction:
  223. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_FUNC));
  224. break;
  225. case MCSA_ELF_TypeIndFunction:
  226. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_GNU_IFUNC));
  227. break;
  228. case MCSA_ELF_TypeObject:
  229. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  230. break;
  231. case MCSA_ELF_TypeTLS:
  232. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_TLS));
  233. break;
  234. case MCSA_ELF_TypeCommon:
  235. // TODO: Emit these as a common symbol.
  236. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  237. break;
  238. case MCSA_ELF_TypeNoType:
  239. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_NOTYPE));
  240. break;
  241. case MCSA_Protected:
  242. Symbol->setVisibility(ELF::STV_PROTECTED);
  243. break;
  244. case MCSA_Hidden:
  245. Symbol->setVisibility(ELF::STV_HIDDEN);
  246. break;
  247. case MCSA_Internal:
  248. Symbol->setVisibility(ELF::STV_INTERNAL);
  249. break;
  250. case MCSA_AltEntry:
  251. llvm_unreachable("ELF doesn't support the .alt_entry attribute");
  252. case MCSA_LGlobal:
  253. llvm_unreachable("ELF doesn't support the .lglobl attribute");
  254. }
  255. return true;
  256. }
  257. void MCELFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
  258. unsigned ByteAlignment) {
  259. auto *Symbol = cast<MCSymbolELF>(S);
  260. getAssembler().registerSymbol(*Symbol);
  261. if (!Symbol->isBindingSet())
  262. Symbol->setBinding(ELF::STB_GLOBAL);
  263. Symbol->setType(ELF::STT_OBJECT);
  264. if (Symbol->getBinding() == ELF::STB_LOCAL) {
  265. MCSection &Section = *getAssembler().getContext().getELFSection(
  266. ".bss", ELF::SHT_NOBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
  267. MCSectionSubPair P = getCurrentSection();
  268. SwitchSection(&Section);
  269. emitValueToAlignment(ByteAlignment, 0, 1, 0);
  270. emitLabel(Symbol);
  271. emitZeros(Size);
  272. SwitchSection(P.first, P.second);
  273. } else {
  274. if(Symbol->declareCommon(Size, ByteAlignment))
  275. report_fatal_error(Twine("Symbol: ") + Symbol->getName() +
  276. " redeclared as different type");
  277. }
  278. cast<MCSymbolELF>(Symbol)
  279. ->setSize(MCConstantExpr::create(Size, getContext()));
  280. }
  281. void MCELFStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
  282. cast<MCSymbolELF>(Symbol)->setSize(Value);
  283. }
  284. void MCELFStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
  285. StringRef Name,
  286. bool KeepOriginalSym) {
  287. getAssembler().Symvers.push_back(MCAssembler::Symver{
  288. getStartTokLoc(), OriginalSym, Name, KeepOriginalSym});
  289. }
  290. void MCELFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
  291. unsigned ByteAlignment) {
  292. auto *Symbol = cast<MCSymbolELF>(S);
  293. // FIXME: Should this be caught and done earlier?
  294. getAssembler().registerSymbol(*Symbol);
  295. Symbol->setBinding(ELF::STB_LOCAL);
  296. emitCommonSymbol(Symbol, Size, ByteAlignment);
  297. }
  298. void MCELFStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
  299. SMLoc Loc) {
  300. if (isBundleLocked())
  301. report_fatal_error("Emitting values inside a locked bundle is forbidden");
  302. fixSymbolsInTLSFixups(Value);
  303. MCObjectStreamer::emitValueImpl(Value, Size, Loc);
  304. }
  305. void MCELFStreamer::emitValueToAlignment(unsigned ByteAlignment,
  306. int64_t Value,
  307. unsigned ValueSize,
  308. unsigned MaxBytesToEmit) {
  309. if (isBundleLocked())
  310. report_fatal_error("Emitting values inside a locked bundle is forbidden");
  311. MCObjectStreamer::emitValueToAlignment(ByteAlignment, Value,
  312. ValueSize, MaxBytesToEmit);
  313. }
  314. void MCELFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
  315. const MCSymbolRefExpr *To,
  316. uint64_t Count) {
  317. getAssembler().CGProfile.push_back({From, To, Count});
  318. }
  319. void MCELFStreamer::emitIdent(StringRef IdentString) {
  320. MCSection *Comment = getAssembler().getContext().getELFSection(
  321. ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
  322. PushSection();
  323. SwitchSection(Comment);
  324. if (!SeenIdent) {
  325. emitInt8(0);
  326. SeenIdent = true;
  327. }
  328. emitBytes(IdentString);
  329. emitInt8(0);
  330. PopSection();
  331. }
  332. void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
  333. switch (expr->getKind()) {
  334. case MCExpr::Target:
  335. cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
  336. break;
  337. case MCExpr::Constant:
  338. break;
  339. case MCExpr::Binary: {
  340. const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
  341. fixSymbolsInTLSFixups(be->getLHS());
  342. fixSymbolsInTLSFixups(be->getRHS());
  343. break;
  344. }
  345. case MCExpr::SymbolRef: {
  346. const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
  347. switch (symRef.getKind()) {
  348. default:
  349. return;
  350. case MCSymbolRefExpr::VK_GOTTPOFF:
  351. case MCSymbolRefExpr::VK_INDNTPOFF:
  352. case MCSymbolRefExpr::VK_NTPOFF:
  353. case MCSymbolRefExpr::VK_GOTNTPOFF:
  354. case MCSymbolRefExpr::VK_TLSCALL:
  355. case MCSymbolRefExpr::VK_TLSDESC:
  356. case MCSymbolRefExpr::VK_TLSGD:
  357. case MCSymbolRefExpr::VK_TLSLD:
  358. case MCSymbolRefExpr::VK_TLSLDM:
  359. case MCSymbolRefExpr::VK_TPOFF:
  360. case MCSymbolRefExpr::VK_TPREL:
  361. case MCSymbolRefExpr::VK_DTPOFF:
  362. case MCSymbolRefExpr::VK_DTPREL:
  363. case MCSymbolRefExpr::VK_PPC_DTPMOD:
  364. case MCSymbolRefExpr::VK_PPC_TPREL_LO:
  365. case MCSymbolRefExpr::VK_PPC_TPREL_HI:
  366. case MCSymbolRefExpr::VK_PPC_TPREL_HA:
  367. case MCSymbolRefExpr::VK_PPC_TPREL_HIGH:
  368. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHA:
  369. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
  370. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
  371. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
  372. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
  373. case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
  374. case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
  375. case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
  376. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGH:
  377. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHA:
  378. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
  379. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
  380. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
  381. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
  382. case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
  383. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
  384. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
  385. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
  386. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_PCREL:
  387. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
  388. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
  389. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
  390. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
  391. case MCSymbolRefExpr::VK_PPC_TLS:
  392. case MCSymbolRefExpr::VK_PPC_TLS_PCREL:
  393. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
  394. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
  395. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
  396. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
  397. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_PCREL:
  398. case MCSymbolRefExpr::VK_PPC_TLSGD:
  399. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
  400. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
  401. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
  402. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
  403. case MCSymbolRefExpr::VK_PPC_TLSLD:
  404. break;
  405. }
  406. getAssembler().registerSymbol(symRef.getSymbol());
  407. cast<MCSymbolELF>(symRef.getSymbol()).setType(ELF::STT_TLS);
  408. break;
  409. }
  410. case MCExpr::Unary:
  411. fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
  412. break;
  413. }
  414. }
  415. void MCELFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE,
  416. uint64_t Offset) {
  417. const MCSymbol *S = &SRE->getSymbol();
  418. if (S->isTemporary()) {
  419. if (!S->isInSection()) {
  420. getContext().reportError(
  421. SRE->getLoc(), Twine("Reference to undefined temporary symbol ") +
  422. "`" + S->getName() + "`");
  423. return;
  424. }
  425. S = S->getSection().getBeginSymbol();
  426. S->setUsedInReloc();
  427. SRE = MCSymbolRefExpr::create(S, MCSymbolRefExpr::VK_None, getContext(),
  428. SRE->getLoc());
  429. }
  430. const MCConstantExpr *MCOffset = MCConstantExpr::create(Offset, getContext());
  431. MCObjectStreamer::visitUsedExpr(*SRE);
  432. if (Optional<std::pair<bool, std::string>> Err =
  433. MCObjectStreamer::emitRelocDirective(
  434. *MCOffset, "BFD_RELOC_NONE", SRE, SRE->getLoc(),
  435. *getContext().getSubtargetInfo()))
  436. report_fatal_error("Relocation for CG Profile could not be created: " +
  437. Twine(Err->second));
  438. }
  439. void MCELFStreamer::finalizeCGProfile() {
  440. MCAssembler &Asm = getAssembler();
  441. if (Asm.CGProfile.empty())
  442. return;
  443. MCSection *CGProfile = getAssembler().getContext().getELFSection(
  444. ".llvm.call-graph-profile", ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
  445. ELF::SHF_EXCLUDE, /*sizeof(Elf_CGProfile_Impl<>)=*/8);
  446. PushSection();
  447. SwitchSection(CGProfile);
  448. uint64_t Offset = 0;
  449. for (MCAssembler::CGProfileEntry &E : Asm.CGProfile) {
  450. finalizeCGProfileEntry(E.From, Offset);
  451. finalizeCGProfileEntry(E.To, Offset);
  452. emitIntValue(E.Count, sizeof(uint64_t));
  453. Offset += sizeof(uint64_t);
  454. }
  455. PopSection();
  456. }
  457. void MCELFStreamer::emitInstToFragment(const MCInst &Inst,
  458. const MCSubtargetInfo &STI) {
  459. this->MCObjectStreamer::emitInstToFragment(Inst, STI);
  460. MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
  461. for (auto &Fixup : F.getFixups())
  462. fixSymbolsInTLSFixups(Fixup.getValue());
  463. }
  464. // A fragment can only have one Subtarget, and when bundling is enabled we
  465. // sometimes need to use the same fragment. We give an error if there
  466. // are conflicting Subtargets.
  467. static void CheckBundleSubtargets(const MCSubtargetInfo *OldSTI,
  468. const MCSubtargetInfo *NewSTI) {
  469. if (OldSTI && NewSTI && OldSTI != NewSTI)
  470. report_fatal_error("A Bundle can only have one Subtarget.");
  471. }
  472. void MCELFStreamer::emitInstToData(const MCInst &Inst,
  473. const MCSubtargetInfo &STI) {
  474. MCAssembler &Assembler = getAssembler();
  475. SmallVector<MCFixup, 4> Fixups;
  476. SmallString<256> Code;
  477. raw_svector_ostream VecOS(Code);
  478. Assembler.getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
  479. for (auto &Fixup : Fixups)
  480. fixSymbolsInTLSFixups(Fixup.getValue());
  481. // There are several possibilities here:
  482. //
  483. // If bundling is disabled, append the encoded instruction to the current data
  484. // fragment (or create a new such fragment if the current fragment is not a
  485. // data fragment, or the Subtarget has changed).
  486. //
  487. // If bundling is enabled:
  488. // - If we're not in a bundle-locked group, emit the instruction into a
  489. // fragment of its own. If there are no fixups registered for the
  490. // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
  491. // MCDataFragment.
  492. // - If we're in a bundle-locked group, append the instruction to the current
  493. // data fragment because we want all the instructions in a group to get into
  494. // the same fragment. Be careful not to do that for the first instruction in
  495. // the group, though.
  496. MCDataFragment *DF;
  497. if (Assembler.isBundlingEnabled()) {
  498. MCSection &Sec = *getCurrentSectionOnly();
  499. if (Assembler.getRelaxAll() && isBundleLocked()) {
  500. // If the -mc-relax-all flag is used and we are bundle-locked, we re-use
  501. // the current bundle group.
  502. DF = BundleGroups.back();
  503. CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
  504. }
  505. else if (Assembler.getRelaxAll() && !isBundleLocked())
  506. // When not in a bundle-locked group and the -mc-relax-all flag is used,
  507. // we create a new temporary fragment which will be later merged into
  508. // the current fragment.
  509. DF = new MCDataFragment();
  510. else if (isBundleLocked() && !Sec.isBundleGroupBeforeFirstInst()) {
  511. // If we are bundle-locked, we re-use the current fragment.
  512. // The bundle-locking directive ensures this is a new data fragment.
  513. DF = cast<MCDataFragment>(getCurrentFragment());
  514. CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
  515. }
  516. else if (!isBundleLocked() && Fixups.size() == 0) {
  517. // Optimize memory usage by emitting the instruction to a
  518. // MCCompactEncodedInstFragment when not in a bundle-locked group and
  519. // there are no fixups registered.
  520. MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
  521. insert(CEIF);
  522. CEIF->getContents().append(Code.begin(), Code.end());
  523. CEIF->setHasInstructions(STI);
  524. return;
  525. } else {
  526. DF = new MCDataFragment();
  527. insert(DF);
  528. }
  529. if (Sec.getBundleLockState() == MCSection::BundleLockedAlignToEnd) {
  530. // If this fragment is for a group marked "align_to_end", set a flag
  531. // in the fragment. This can happen after the fragment has already been
  532. // created if there are nested bundle_align groups and an inner one
  533. // is the one marked align_to_end.
  534. DF->setAlignToBundleEnd(true);
  535. }
  536. // We're now emitting an instruction in a bundle group, so this flag has
  537. // to be turned off.
  538. Sec.setBundleGroupBeforeFirstInst(false);
  539. } else {
  540. DF = getOrCreateDataFragment(&STI);
  541. }
  542. // Add the fixups and data.
  543. for (auto &Fixup : Fixups) {
  544. Fixup.setOffset(Fixup.getOffset() + DF->getContents().size());
  545. DF->getFixups().push_back(Fixup);
  546. }
  547. DF->setHasInstructions(STI);
  548. DF->getContents().append(Code.begin(), Code.end());
  549. if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
  550. if (!isBundleLocked()) {
  551. mergeFragment(getOrCreateDataFragment(&STI), DF);
  552. delete DF;
  553. }
  554. }
  555. }
  556. void MCELFStreamer::emitBundleAlignMode(unsigned AlignPow2) {
  557. assert(AlignPow2 <= 30 && "Invalid bundle alignment");
  558. MCAssembler &Assembler = getAssembler();
  559. if (AlignPow2 > 0 && (Assembler.getBundleAlignSize() == 0 ||
  560. Assembler.getBundleAlignSize() == 1U << AlignPow2))
  561. Assembler.setBundleAlignSize(1U << AlignPow2);
  562. else
  563. report_fatal_error(".bundle_align_mode cannot be changed once set");
  564. }
  565. void MCELFStreamer::emitBundleLock(bool AlignToEnd) {
  566. MCSection &Sec = *getCurrentSectionOnly();
  567. if (!getAssembler().isBundlingEnabled())
  568. report_fatal_error(".bundle_lock forbidden when bundling is disabled");
  569. if (!isBundleLocked())
  570. Sec.setBundleGroupBeforeFirstInst(true);
  571. if (getAssembler().getRelaxAll() && !isBundleLocked()) {
  572. // TODO: drop the lock state and set directly in the fragment
  573. MCDataFragment *DF = new MCDataFragment();
  574. BundleGroups.push_back(DF);
  575. }
  576. Sec.setBundleLockState(AlignToEnd ? MCSection::BundleLockedAlignToEnd
  577. : MCSection::BundleLocked);
  578. }
  579. void MCELFStreamer::emitBundleUnlock() {
  580. MCSection &Sec = *getCurrentSectionOnly();
  581. if (!getAssembler().isBundlingEnabled())
  582. report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
  583. else if (!isBundleLocked())
  584. report_fatal_error(".bundle_unlock without matching lock");
  585. else if (Sec.isBundleGroupBeforeFirstInst())
  586. report_fatal_error("Empty bundle-locked group is forbidden");
  587. // When the -mc-relax-all flag is used, we emit instructions to fragments
  588. // stored on a stack. When the bundle unlock is emitted, we pop a fragment
  589. // from the stack a merge it to the one below.
  590. if (getAssembler().getRelaxAll()) {
  591. assert(!BundleGroups.empty() && "There are no bundle groups");
  592. MCDataFragment *DF = BundleGroups.back();
  593. // FIXME: Use BundleGroups to track the lock state instead.
  594. Sec.setBundleLockState(MCSection::NotBundleLocked);
  595. // FIXME: Use more separate fragments for nested groups.
  596. if (!isBundleLocked()) {
  597. mergeFragment(getOrCreateDataFragment(DF->getSubtargetInfo()), DF);
  598. BundleGroups.pop_back();
  599. delete DF;
  600. }
  601. if (Sec.getBundleLockState() != MCSection::BundleLockedAlignToEnd)
  602. getOrCreateDataFragment()->setAlignToBundleEnd(false);
  603. } else
  604. Sec.setBundleLockState(MCSection::NotBundleLocked);
  605. }
  606. void MCELFStreamer::finishImpl() {
  607. // Emit the .gnu attributes section if any attributes have been added.
  608. if (!GNUAttributes.empty()) {
  609. MCSection *DummyAttributeSection = nullptr;
  610. createAttributesSection("gnu", ".gnu.attributes", ELF::SHT_GNU_ATTRIBUTES,
  611. DummyAttributeSection, GNUAttributes);
  612. }
  613. // Ensure the last section gets aligned if necessary.
  614. MCSection *CurSection = getCurrentSectionOnly();
  615. setSectionAlignmentForBundling(getAssembler(), CurSection);
  616. finalizeCGProfile();
  617. emitFrames(nullptr);
  618. this->MCObjectStreamer::finishImpl();
  619. }
  620. void MCELFStreamer::emitThumbFunc(MCSymbol *Func) {
  621. llvm_unreachable("Generic ELF doesn't support this directive");
  622. }
  623. void MCELFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
  624. llvm_unreachable("ELF doesn't support this directive");
  625. }
  626. void MCELFStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
  627. uint64_t Size, unsigned ByteAlignment,
  628. SMLoc Loc) {
  629. llvm_unreachable("ELF doesn't support this directive");
  630. }
  631. void MCELFStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  632. uint64_t Size, unsigned ByteAlignment) {
  633. llvm_unreachable("ELF doesn't support this directive");
  634. }
  635. void MCELFStreamer::setAttributeItem(unsigned Attribute, unsigned Value,
  636. bool OverwriteExisting) {
  637. // Look for existing attribute item
  638. if (AttributeItem *Item = getAttributeItem(Attribute)) {
  639. if (!OverwriteExisting)
  640. return;
  641. Item->Type = AttributeItem::NumericAttribute;
  642. Item->IntValue = Value;
  643. return;
  644. }
  645. // Create new attribute item
  646. AttributeItem Item = {AttributeItem::NumericAttribute, Attribute, Value,
  647. std::string(StringRef(""))};
  648. Contents.push_back(Item);
  649. }
  650. void MCELFStreamer::setAttributeItem(unsigned Attribute, StringRef Value,
  651. bool OverwriteExisting) {
  652. // Look for existing attribute item
  653. if (AttributeItem *Item = getAttributeItem(Attribute)) {
  654. if (!OverwriteExisting)
  655. return;
  656. Item->Type = AttributeItem::TextAttribute;
  657. Item->StringValue = std::string(Value);
  658. return;
  659. }
  660. // Create new attribute item
  661. AttributeItem Item = {AttributeItem::TextAttribute, Attribute, 0,
  662. std::string(Value)};
  663. Contents.push_back(Item);
  664. }
  665. void MCELFStreamer::setAttributeItems(unsigned Attribute, unsigned IntValue,
  666. StringRef StringValue,
  667. bool OverwriteExisting) {
  668. // Look for existing attribute item
  669. if (AttributeItem *Item = getAttributeItem(Attribute)) {
  670. if (!OverwriteExisting)
  671. return;
  672. Item->Type = AttributeItem::NumericAndTextAttributes;
  673. Item->IntValue = IntValue;
  674. Item->StringValue = std::string(StringValue);
  675. return;
  676. }
  677. // Create new attribute item
  678. AttributeItem Item = {AttributeItem::NumericAndTextAttributes, Attribute,
  679. IntValue, std::string(StringValue)};
  680. Contents.push_back(Item);
  681. }
  682. MCELFStreamer::AttributeItem *
  683. MCELFStreamer::getAttributeItem(unsigned Attribute) {
  684. for (size_t I = 0; I < Contents.size(); ++I)
  685. if (Contents[I].Tag == Attribute)
  686. return &Contents[I];
  687. return nullptr;
  688. }
  689. size_t
  690. MCELFStreamer::calculateContentSize(SmallVector<AttributeItem, 64> &AttrsVec) {
  691. size_t Result = 0;
  692. for (size_t I = 0; I < AttrsVec.size(); ++I) {
  693. AttributeItem Item = AttrsVec[I];
  694. switch (Item.Type) {
  695. case AttributeItem::HiddenAttribute:
  696. break;
  697. case AttributeItem::NumericAttribute:
  698. Result += getULEB128Size(Item.Tag);
  699. Result += getULEB128Size(Item.IntValue);
  700. break;
  701. case AttributeItem::TextAttribute:
  702. Result += getULEB128Size(Item.Tag);
  703. Result += Item.StringValue.size() + 1; // string + '\0'
  704. break;
  705. case AttributeItem::NumericAndTextAttributes:
  706. Result += getULEB128Size(Item.Tag);
  707. Result += getULEB128Size(Item.IntValue);
  708. Result += Item.StringValue.size() + 1; // string + '\0';
  709. break;
  710. }
  711. }
  712. return Result;
  713. }
  714. void MCELFStreamer::createAttributesSection(
  715. StringRef Vendor, const Twine &Section, unsigned Type,
  716. MCSection *&AttributeSection, SmallVector<AttributeItem, 64> &AttrsVec) {
  717. // <format-version>
  718. // [ <section-length> "vendor-name"
  719. // [ <file-tag> <size> <attribute>*
  720. // | <section-tag> <size> <section-number>* 0 <attribute>*
  721. // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
  722. // ]+
  723. // ]*
  724. // Switch section to AttributeSection or get/create the section.
  725. if (AttributeSection) {
  726. SwitchSection(AttributeSection);
  727. } else {
  728. AttributeSection = getContext().getELFSection(Section, Type, 0);
  729. SwitchSection(AttributeSection);
  730. // Format version
  731. emitInt8(0x41);
  732. }
  733. // Vendor size + Vendor name + '\0'
  734. const size_t VendorHeaderSize = 4 + Vendor.size() + 1;
  735. // Tag + Tag Size
  736. const size_t TagHeaderSize = 1 + 4;
  737. const size_t ContentsSize = calculateContentSize(AttrsVec);
  738. emitInt32(VendorHeaderSize + TagHeaderSize + ContentsSize);
  739. emitBytes(Vendor);
  740. emitInt8(0); // '\0'
  741. emitInt8(ARMBuildAttrs::File);
  742. emitInt32(TagHeaderSize + ContentsSize);
  743. // Size should have been accounted for already, now
  744. // emit each field as its type (ULEB or String)
  745. for (size_t I = 0; I < AttrsVec.size(); ++I) {
  746. AttributeItem Item = AttrsVec[I];
  747. emitULEB128IntValue(Item.Tag);
  748. switch (Item.Type) {
  749. default:
  750. llvm_unreachable("Invalid attribute type");
  751. case AttributeItem::NumericAttribute:
  752. emitULEB128IntValue(Item.IntValue);
  753. break;
  754. case AttributeItem::TextAttribute:
  755. emitBytes(Item.StringValue);
  756. emitInt8(0); // '\0'
  757. break;
  758. case AttributeItem::NumericAndTextAttributes:
  759. emitULEB128IntValue(Item.IntValue);
  760. emitBytes(Item.StringValue);
  761. emitInt8(0); // '\0'
  762. break;
  763. }
  764. }
  765. AttrsVec.clear();
  766. }
  767. MCStreamer *llvm::createELFStreamer(MCContext &Context,
  768. std::unique_ptr<MCAsmBackend> &&MAB,
  769. std::unique_ptr<MCObjectWriter> &&OW,
  770. std::unique_ptr<MCCodeEmitter> &&CE,
  771. bool RelaxAll) {
  772. MCELFStreamer *S =
  773. new MCELFStreamer(Context, std::move(MAB), std::move(OW), std::move(CE));
  774. if (RelaxAll)
  775. S->getAssembler().setRelaxAll(true);
  776. return S;
  777. }