MCWinCOFFStreamer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. //===- llvm/MC/MCWinCOFFStreamer.cpp --------------------------------------===//
  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 contains an implementation of a Windows COFF object file streamer.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/SmallString.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/Triple.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include "llvm/BinaryFormat/COFF.h"
  17. #include "llvm/MC/MCAsmBackend.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/MCObjectStreamer.h"
  26. #include "llvm/MC/MCObjectWriter.h"
  27. #include "llvm/MC/MCSection.h"
  28. #include "llvm/MC/MCSymbolCOFF.h"
  29. #include "llvm/MC/MCWinCOFFStreamer.h"
  30. #include "llvm/Support/Casting.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/MathExtras.h"
  33. #include "llvm/Support/SMLoc.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <algorithm>
  36. #include <cassert>
  37. #include <cstdint>
  38. using namespace llvm;
  39. #define DEBUG_TYPE "WinCOFFStreamer"
  40. MCWinCOFFStreamer::MCWinCOFFStreamer(MCContext &Context,
  41. std::unique_ptr<MCAsmBackend> MAB,
  42. std::unique_ptr<MCCodeEmitter> CE,
  43. std::unique_ptr<MCObjectWriter> OW)
  44. : MCObjectStreamer(Context, std::move(MAB), std::move(OW), std::move(CE)),
  45. CurSymbol(nullptr) {}
  46. void MCWinCOFFStreamer::emitInstToData(const MCInst &Inst,
  47. const MCSubtargetInfo &STI) {
  48. MCDataFragment *DF = getOrCreateDataFragment();
  49. SmallVector<MCFixup, 4> Fixups;
  50. SmallString<256> Code;
  51. raw_svector_ostream VecOS(Code);
  52. getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
  53. // Add the fixups and data.
  54. for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
  55. Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
  56. DF->getFixups().push_back(Fixups[i]);
  57. }
  58. DF->setHasInstructions(STI);
  59. DF->getContents().append(Code.begin(), Code.end());
  60. }
  61. void MCWinCOFFStreamer::initSections(bool NoExecStack,
  62. const MCSubtargetInfo &STI) {
  63. // FIXME: this is identical to the ELF one.
  64. // This emulates the same behavior of GNU as. This makes it easier
  65. // to compare the output as the major sections are in the same order.
  66. SwitchSection(getContext().getObjectFileInfo()->getTextSection());
  67. emitCodeAlignment(4, &STI);
  68. SwitchSection(getContext().getObjectFileInfo()->getDataSection());
  69. emitCodeAlignment(4, &STI);
  70. SwitchSection(getContext().getObjectFileInfo()->getBSSSection());
  71. emitCodeAlignment(4, &STI);
  72. SwitchSection(getContext().getObjectFileInfo()->getTextSection());
  73. }
  74. void MCWinCOFFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
  75. auto *Symbol = cast<MCSymbolCOFF>(S);
  76. MCObjectStreamer::emitLabel(Symbol, Loc);
  77. }
  78. void MCWinCOFFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
  79. // Let the target do whatever target specific stuff it needs to do.
  80. getAssembler().getBackend().handleAssemblerFlag(Flag);
  81. switch (Flag) {
  82. // None of these require COFF specific handling.
  83. case MCAF_SyntaxUnified:
  84. case MCAF_Code16:
  85. case MCAF_Code32:
  86. case MCAF_Code64:
  87. break;
  88. case MCAF_SubsectionsViaSymbols:
  89. llvm_unreachable("COFF doesn't support .subsections_via_symbols");
  90. }
  91. }
  92. void MCWinCOFFStreamer::emitThumbFunc(MCSymbol *Func) {
  93. llvm_unreachable("not implemented");
  94. }
  95. bool MCWinCOFFStreamer::emitSymbolAttribute(MCSymbol *S,
  96. MCSymbolAttr Attribute) {
  97. auto *Symbol = cast<MCSymbolCOFF>(S);
  98. getAssembler().registerSymbol(*Symbol);
  99. switch (Attribute) {
  100. default: return false;
  101. case MCSA_WeakReference:
  102. case MCSA_Weak:
  103. Symbol->setIsWeakExternal();
  104. Symbol->setExternal(true);
  105. break;
  106. case MCSA_Global:
  107. Symbol->setExternal(true);
  108. break;
  109. case MCSA_AltEntry:
  110. llvm_unreachable("COFF doesn't support the .alt_entry attribute");
  111. }
  112. return true;
  113. }
  114. void MCWinCOFFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
  115. llvm_unreachable("not implemented");
  116. }
  117. void MCWinCOFFStreamer::BeginCOFFSymbolDef(MCSymbol const *S) {
  118. auto *Symbol = cast<MCSymbolCOFF>(S);
  119. if (CurSymbol)
  120. Error("starting a new symbol definition without completing the "
  121. "previous one");
  122. CurSymbol = Symbol;
  123. }
  124. void MCWinCOFFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
  125. if (!CurSymbol) {
  126. Error("storage class specified outside of symbol definition");
  127. return;
  128. }
  129. if (StorageClass & ~COFF::SSC_Invalid) {
  130. Error("storage class value '" + Twine(StorageClass) +
  131. "' out of range");
  132. return;
  133. }
  134. getAssembler().registerSymbol(*CurSymbol);
  135. cast<MCSymbolCOFF>(CurSymbol)->setClass((uint16_t)StorageClass);
  136. }
  137. void MCWinCOFFStreamer::EmitCOFFSymbolType(int Type) {
  138. if (!CurSymbol) {
  139. Error("symbol type specified outside of a symbol definition");
  140. return;
  141. }
  142. if (Type & ~0xffff) {
  143. Error("type value '" + Twine(Type) + "' out of range");
  144. return;
  145. }
  146. getAssembler().registerSymbol(*CurSymbol);
  147. cast<MCSymbolCOFF>(CurSymbol)->setType((uint16_t)Type);
  148. }
  149. void MCWinCOFFStreamer::EndCOFFSymbolDef() {
  150. if (!CurSymbol)
  151. Error("ending symbol definition without starting one");
  152. CurSymbol = nullptr;
  153. }
  154. void MCWinCOFFStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {
  155. // SafeSEH is a feature specific to 32-bit x86. It does not exist (and is
  156. // unnecessary) on all platforms which use table-based exception dispatch.
  157. if (getContext().getTargetTriple().getArch() != Triple::x86)
  158. return;
  159. const MCSymbolCOFF *CSymbol = cast<MCSymbolCOFF>(Symbol);
  160. if (CSymbol->isSafeSEH())
  161. return;
  162. MCSection *SXData = getContext().getObjectFileInfo()->getSXDataSection();
  163. getAssembler().registerSection(*SXData);
  164. if (SXData->getAlignment() < 4)
  165. SXData->setAlignment(Align(4));
  166. new MCSymbolIdFragment(Symbol, SXData);
  167. getAssembler().registerSymbol(*Symbol);
  168. CSymbol->setIsSafeSEH();
  169. // The Microsoft linker requires that the symbol type of a handler be
  170. // function. Go ahead and oblige it here.
  171. CSymbol->setType(COFF::IMAGE_SYM_DTYPE_FUNCTION
  172. << COFF::SCT_COMPLEX_TYPE_SHIFT);
  173. }
  174. void MCWinCOFFStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {
  175. MCSection *Sec = getCurrentSectionOnly();
  176. getAssembler().registerSection(*Sec);
  177. if (Sec->getAlignment() < 4)
  178. Sec->setAlignment(Align(4));
  179. new MCSymbolIdFragment(Symbol, getCurrentSectionOnly());
  180. getAssembler().registerSymbol(*Symbol);
  181. }
  182. void MCWinCOFFStreamer::EmitCOFFSectionIndex(const MCSymbol *Symbol) {
  183. visitUsedSymbol(*Symbol);
  184. MCDataFragment *DF = getOrCreateDataFragment();
  185. const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Symbol, getContext());
  186. MCFixup Fixup = MCFixup::create(DF->getContents().size(), SRE, FK_SecRel_2);
  187. DF->getFixups().push_back(Fixup);
  188. DF->getContents().resize(DF->getContents().size() + 2, 0);
  189. }
  190. void MCWinCOFFStreamer::EmitCOFFSecRel32(const MCSymbol *Symbol,
  191. uint64_t Offset) {
  192. visitUsedSymbol(*Symbol);
  193. MCDataFragment *DF = getOrCreateDataFragment();
  194. // Create Symbol A for the relocation relative reference.
  195. const MCExpr *MCE = MCSymbolRefExpr::create(Symbol, getContext());
  196. // Add the constant offset, if given.
  197. if (Offset)
  198. MCE = MCBinaryExpr::createAdd(
  199. MCE, MCConstantExpr::create(Offset, getContext()), getContext());
  200. // Build the secrel32 relocation.
  201. MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_SecRel_4);
  202. // Record the relocation.
  203. DF->getFixups().push_back(Fixup);
  204. // Emit 4 bytes (zeros) to the object file.
  205. DF->getContents().resize(DF->getContents().size() + 4, 0);
  206. }
  207. void MCWinCOFFStreamer::EmitCOFFImgRel32(const MCSymbol *Symbol,
  208. int64_t Offset) {
  209. visitUsedSymbol(*Symbol);
  210. MCDataFragment *DF = getOrCreateDataFragment();
  211. // Create Symbol A for the relocation relative reference.
  212. const MCExpr *MCE = MCSymbolRefExpr::create(
  213. Symbol, MCSymbolRefExpr::VK_COFF_IMGREL32, getContext());
  214. // Add the constant offset, if given.
  215. if (Offset)
  216. MCE = MCBinaryExpr::createAdd(
  217. MCE, MCConstantExpr::create(Offset, getContext()), getContext());
  218. // Build the imgrel relocation.
  219. MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_Data_4);
  220. // Record the relocation.
  221. DF->getFixups().push_back(Fixup);
  222. // Emit 4 bytes (zeros) to the object file.
  223. DF->getContents().resize(DF->getContents().size() + 4, 0);
  224. }
  225. void MCWinCOFFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
  226. unsigned ByteAlignment) {
  227. auto *Symbol = cast<MCSymbolCOFF>(S);
  228. const Triple &T = getContext().getTargetTriple();
  229. if (T.isWindowsMSVCEnvironment()) {
  230. if (ByteAlignment > 32)
  231. report_fatal_error("alignment is limited to 32-bytes");
  232. // Round size up to alignment so that we will honor the alignment request.
  233. Size = std::max(Size, static_cast<uint64_t>(ByteAlignment));
  234. }
  235. getAssembler().registerSymbol(*Symbol);
  236. Symbol->setExternal(true);
  237. Symbol->setCommon(Size, ByteAlignment);
  238. if (!T.isWindowsMSVCEnvironment() && ByteAlignment > 1) {
  239. SmallString<128> Directive;
  240. raw_svector_ostream OS(Directive);
  241. const MCObjectFileInfo *MFI = getContext().getObjectFileInfo();
  242. OS << " -aligncomm:\"" << Symbol->getName() << "\","
  243. << Log2_32_Ceil(ByteAlignment);
  244. PushSection();
  245. SwitchSection(MFI->getDrectveSection());
  246. emitBytes(Directive);
  247. PopSection();
  248. }
  249. }
  250. void MCWinCOFFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
  251. unsigned ByteAlignment) {
  252. auto *Symbol = cast<MCSymbolCOFF>(S);
  253. MCSection *Section = getContext().getObjectFileInfo()->getBSSSection();
  254. PushSection();
  255. SwitchSection(Section);
  256. emitValueToAlignment(ByteAlignment, 0, 1, 0);
  257. emitLabel(Symbol);
  258. Symbol->setExternal(false);
  259. emitZeros(Size);
  260. PopSection();
  261. }
  262. void MCWinCOFFStreamer::emitWeakReference(MCSymbol *AliasS,
  263. const MCSymbol *Symbol) {
  264. auto *Alias = cast<MCSymbolCOFF>(AliasS);
  265. emitSymbolAttribute(Alias, MCSA_Weak);
  266. getAssembler().registerSymbol(*Symbol);
  267. Alias->setVariableValue(MCSymbolRefExpr::create(
  268. Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext()));
  269. }
  270. void MCWinCOFFStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
  271. uint64_t Size, unsigned ByteAlignment,
  272. SMLoc Loc) {
  273. llvm_unreachable("not implemented");
  274. }
  275. void MCWinCOFFStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  276. uint64_t Size, unsigned ByteAlignment) {
  277. llvm_unreachable("not implemented");
  278. }
  279. // TODO: Implement this if you want to emit .comment section in COFF obj files.
  280. void MCWinCOFFStreamer::emitIdent(StringRef IdentString) {
  281. llvm_unreachable("not implemented");
  282. }
  283. void MCWinCOFFStreamer::EmitWinEHHandlerData(SMLoc Loc) {
  284. llvm_unreachable("not implemented");
  285. }
  286. void MCWinCOFFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
  287. const MCSymbolRefExpr *To,
  288. uint64_t Count) {
  289. // Ignore temporary symbols for now.
  290. if (!From->getSymbol().isTemporary() && !To->getSymbol().isTemporary())
  291. getAssembler().CGProfile.push_back({From, To, Count});
  292. }
  293. void MCWinCOFFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE) {
  294. const MCSymbol *S = &SRE->getSymbol();
  295. bool Created;
  296. getAssembler().registerSymbol(*S, &Created);
  297. if (Created)
  298. cast<MCSymbolCOFF>(S)->setExternal(true);
  299. }
  300. void MCWinCOFFStreamer::finalizeCGProfile() {
  301. for (MCAssembler::CGProfileEntry &E : getAssembler().CGProfile) {
  302. finalizeCGProfileEntry(E.From);
  303. finalizeCGProfileEntry(E.To);
  304. }
  305. }
  306. void MCWinCOFFStreamer::finishImpl() {
  307. finalizeCGProfile();
  308. MCObjectStreamer::finishImpl();
  309. }
  310. void MCWinCOFFStreamer::Error(const Twine &Msg) const {
  311. getContext().reportError(SMLoc(), Msg);
  312. }