MCObjectStreamer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/MC/MCObjectStreamer.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/MC/MCAsmBackend.h"
  12. #include "llvm/MC/MCAsmInfo.h"
  13. #include "llvm/MC/MCAssembler.h"
  14. #include "llvm/MC/MCCodeEmitter.h"
  15. #include "llvm/MC/MCContext.h"
  16. #include "llvm/MC/MCDwarf.h"
  17. #include "llvm/MC/MCExpr.h"
  18. #include "llvm/MC/MCObjectWriter.h"
  19. #include "llvm/MC/MCSection.h"
  20. #include "llvm/MC/MCSymbol.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/TargetRegistry.h"
  23. using namespace llvm;
  24. MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
  25. raw_pwrite_stream &OS,
  26. MCCodeEmitter *Emitter_)
  27. : MCStreamer(Context),
  28. Assembler(new MCAssembler(Context, TAB, *Emitter_,
  29. *TAB.createObjectWriter(OS), OS)),
  30. EmitEHFrame(true), EmitDebugFrame(false) {}
  31. MCObjectStreamer::~MCObjectStreamer() {
  32. delete &Assembler->getBackend();
  33. delete &Assembler->getEmitter();
  34. delete &Assembler->getWriter();
  35. delete Assembler;
  36. }
  37. void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
  38. if (PendingLabels.size()) {
  39. if (!F) {
  40. F = new MCDataFragment();
  41. MCSection *CurSection = getCurrentSectionOnly();
  42. CurSection->getFragmentList().insert(CurInsertionPoint, F);
  43. F->setParent(CurSection);
  44. }
  45. for (MCSymbol *Sym : PendingLabels) {
  46. Sym->setFragment(F);
  47. Sym->setOffset(FOffset);
  48. }
  49. PendingLabels.clear();
  50. }
  51. }
  52. void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
  53. const MCSymbol *Lo,
  54. unsigned Size) {
  55. // If not assigned to the same (valid) fragment, fallback.
  56. if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment()) {
  57. MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
  58. return;
  59. }
  60. assert(Hi->getOffset() >= Lo->getOffset() &&
  61. "Expected Hi to be greater than Lo");
  62. EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
  63. }
  64. void MCObjectStreamer::reset() {
  65. if (Assembler)
  66. Assembler->reset();
  67. CurInsertionPoint = MCSection::iterator();
  68. EmitEHFrame = true;
  69. EmitDebugFrame = false;
  70. PendingLabels.clear();
  71. MCStreamer::reset();
  72. }
  73. void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
  74. if (!getNumFrameInfos())
  75. return;
  76. if (EmitEHFrame)
  77. MCDwarfFrameEmitter::Emit(*this, MAB, true);
  78. if (EmitDebugFrame)
  79. MCDwarfFrameEmitter::Emit(*this, MAB, false);
  80. }
  81. MCFragment *MCObjectStreamer::getCurrentFragment() const {
  82. assert(getCurrentSectionOnly() && "No current section!");
  83. if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
  84. return std::prev(CurInsertionPoint);
  85. return nullptr;
  86. }
  87. MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
  88. MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
  89. // When bundling is enabled, we don't want to add data to a fragment that
  90. // already has instructions (see MCELFStreamer::EmitInstToData for details)
  91. if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
  92. F->hasInstructions())) {
  93. F = new MCDataFragment();
  94. insert(F);
  95. }
  96. return F;
  97. }
  98. void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
  99. Assembler->registerSymbol(Sym);
  100. }
  101. void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
  102. MCStreamer::EmitCFISections(EH, Debug);
  103. EmitEHFrame = EH;
  104. EmitDebugFrame = Debug;
  105. }
  106. void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
  107. const SMLoc &Loc) {
  108. MCStreamer::EmitValueImpl(Value, Size, Loc);
  109. MCDataFragment *DF = getOrCreateDataFragment();
  110. flushPendingLabels(DF, DF->getContents().size());
  111. MCLineEntry::Make(this, getCurrentSection().first);
  112. // Avoid fixups when possible.
  113. int64_t AbsValue;
  114. if (Value->evaluateAsAbsolute(AbsValue, getAssembler())) {
  115. EmitIntValue(AbsValue, Size);
  116. return;
  117. }
  118. DF->getFixups().push_back(
  119. MCFixup::create(DF->getContents().size(), Value,
  120. MCFixup::getKindForSize(Size, false), Loc));
  121. DF->getContents().resize(DF->getContents().size() + Size, 0);
  122. }
  123. void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
  124. // We need to create a local symbol to avoid relocations.
  125. Frame.Begin = getContext().createTempSymbol();
  126. EmitLabel(Frame.Begin);
  127. }
  128. void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
  129. Frame.End = getContext().createTempSymbol();
  130. EmitLabel(Frame.End);
  131. }
  132. void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
  133. MCStreamer::EmitLabel(Symbol);
  134. getAssembler().registerSymbol(*Symbol);
  135. assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
  136. // If there is a current fragment, mark the symbol as pointing into it.
  137. // Otherwise queue the label and set its fragment pointer when we emit the
  138. // next fragment.
  139. auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
  140. if (F && !(getAssembler().isBundlingEnabled() &&
  141. getAssembler().getRelaxAll())) {
  142. Symbol->setFragment(F);
  143. Symbol->setOffset(F->getContents().size());
  144. } else {
  145. PendingLabels.push_back(Symbol);
  146. }
  147. }
  148. void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
  149. int64_t IntValue;
  150. if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
  151. EmitULEB128IntValue(IntValue);
  152. return;
  153. }
  154. insert(new MCLEBFragment(*Value, false));
  155. }
  156. void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
  157. int64_t IntValue;
  158. if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
  159. EmitSLEB128IntValue(IntValue);
  160. return;
  161. }
  162. insert(new MCLEBFragment(*Value, true));
  163. }
  164. void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
  165. const MCSymbol *Symbol) {
  166. report_fatal_error("This file format doesn't support weak aliases.");
  167. }
  168. void MCObjectStreamer::ChangeSection(MCSection *Section,
  169. const MCExpr *Subsection) {
  170. changeSectionImpl(Section, Subsection);
  171. }
  172. bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
  173. const MCExpr *Subsection) {
  174. assert(Section && "Cannot switch to a null section!");
  175. flushPendingLabels(nullptr);
  176. bool Created = getAssembler().registerSection(*Section);
  177. int64_t IntSubsection = 0;
  178. if (Subsection &&
  179. !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler()))
  180. report_fatal_error("Cannot evaluate subsection number");
  181. if (IntSubsection < 0 || IntSubsection > 8192)
  182. report_fatal_error("Subsection number out of range");
  183. CurInsertionPoint =
  184. Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
  185. return Created;
  186. }
  187. void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
  188. getAssembler().registerSymbol(*Symbol);
  189. MCStreamer::EmitAssignment(Symbol, Value);
  190. }
  191. bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
  192. return Sec.hasInstructions();
  193. }
  194. void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
  195. const MCSubtargetInfo &STI) {
  196. MCStreamer::EmitInstruction(Inst, STI);
  197. MCSection *Sec = getCurrentSectionOnly();
  198. Sec->setHasInstructions(true);
  199. // Now that a machine instruction has been assembled into this section, make
  200. // a line entry for any .loc directive that has been seen.
  201. MCLineEntry::Make(this, getCurrentSection().first);
  202. // If this instruction doesn't need relaxation, just emit it as data.
  203. MCAssembler &Assembler = getAssembler();
  204. if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
  205. EmitInstToData(Inst, STI);
  206. return;
  207. }
  208. // Otherwise, relax and emit it as data if either:
  209. // - The RelaxAll flag was passed
  210. // - Bundling is enabled and this instruction is inside a bundle-locked
  211. // group. We want to emit all such instructions into the same data
  212. // fragment.
  213. if (Assembler.getRelaxAll() ||
  214. (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
  215. MCInst Relaxed;
  216. getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
  217. while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
  218. getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
  219. EmitInstToData(Relaxed, STI);
  220. return;
  221. }
  222. // Otherwise emit to a separate fragment.
  223. EmitInstToFragment(Inst, STI);
  224. }
  225. void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
  226. const MCSubtargetInfo &STI) {
  227. if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
  228. llvm_unreachable("All instructions should have already been relaxed");
  229. // Always create a new, separate fragment here, because its size can change
  230. // during relaxation.
  231. MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
  232. insert(IF);
  233. SmallString<128> Code;
  234. raw_svector_ostream VecOS(Code);
  235. getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
  236. STI);
  237. VecOS.flush();
  238. IF->getContents().append(Code.begin(), Code.end());
  239. }
  240. static const char *const BundlingNotImplementedMsg =
  241. "Aligned bundling is not implemented for this object format";
  242. void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
  243. llvm_unreachable(BundlingNotImplementedMsg);
  244. }
  245. void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
  246. llvm_unreachable(BundlingNotImplementedMsg);
  247. }
  248. void MCObjectStreamer::EmitBundleUnlock() {
  249. llvm_unreachable(BundlingNotImplementedMsg);
  250. }
  251. void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
  252. unsigned Column, unsigned Flags,
  253. unsigned Isa,
  254. unsigned Discriminator,
  255. StringRef FileName) {
  256. // In case we see two .loc directives in a row, make sure the
  257. // first one gets a line entry.
  258. MCLineEntry::Make(this, getCurrentSection().first);
  259. this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
  260. Isa, Discriminator, FileName);
  261. }
  262. static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
  263. const MCSymbol *B) {
  264. MCContext &Context = OS.getContext();
  265. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  266. const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
  267. const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
  268. const MCExpr *AddrDelta =
  269. MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
  270. return AddrDelta;
  271. }
  272. static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
  273. const MCSymbol *Label, int PointerSize) {
  274. // emit the sequence to set the address
  275. OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
  276. OS.EmitULEB128IntValue(PointerSize + 1);
  277. OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
  278. OS.EmitSymbolValue(Label, PointerSize);
  279. // emit the sequence for the LineDelta (from 1) and a zero address delta.
  280. MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
  281. }
  282. void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
  283. const MCSymbol *LastLabel,
  284. const MCSymbol *Label,
  285. unsigned PointerSize) {
  286. if (!LastLabel) {
  287. emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
  288. return;
  289. }
  290. const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
  291. int64_t Res;
  292. if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
  293. MCDwarfLineAddr::Emit(this, LineDelta, Res);
  294. return;
  295. }
  296. insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
  297. }
  298. void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
  299. const MCSymbol *Label) {
  300. const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
  301. int64_t Res;
  302. if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
  303. MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
  304. return;
  305. }
  306. insert(new MCDwarfCallFrameFragment(*AddrDelta));
  307. }
  308. void MCObjectStreamer::EmitBytes(StringRef Data) {
  309. MCLineEntry::Make(this, getCurrentSection().first);
  310. MCDataFragment *DF = getOrCreateDataFragment();
  311. flushPendingLabels(DF, DF->getContents().size());
  312. DF->getContents().append(Data.begin(), Data.end());
  313. }
  314. void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
  315. int64_t Value,
  316. unsigned ValueSize,
  317. unsigned MaxBytesToEmit) {
  318. if (MaxBytesToEmit == 0)
  319. MaxBytesToEmit = ByteAlignment;
  320. insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
  321. // Update the maximum alignment on the current section if necessary.
  322. MCSection *CurSec = getCurrentSection().first;
  323. if (ByteAlignment > CurSec->getAlignment())
  324. CurSec->setAlignment(ByteAlignment);
  325. }
  326. void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
  327. unsigned MaxBytesToEmit) {
  328. EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
  329. cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
  330. }
  331. bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
  332. unsigned char Value) {
  333. int64_t Res;
  334. if (Offset->evaluateAsAbsolute(Res, getAssembler())) {
  335. insert(new MCOrgFragment(*Offset, Value));
  336. return false;
  337. }
  338. MCSymbol *CurrentPos = getContext().createTempSymbol();
  339. EmitLabel(CurrentPos);
  340. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  341. const MCExpr *Ref =
  342. MCSymbolRefExpr::create(CurrentPos, Variant, getContext());
  343. const MCExpr *Delta =
  344. MCBinaryExpr::create(MCBinaryExpr::Sub, Offset, Ref, getContext());
  345. if (!Delta->evaluateAsAbsolute(Res, getAssembler()))
  346. return true;
  347. EmitFill(Res, Value);
  348. return false;
  349. }
  350. // Associate GPRel32 fixup with data and resize data area
  351. void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
  352. MCDataFragment *DF = getOrCreateDataFragment();
  353. flushPendingLabels(DF, DF->getContents().size());
  354. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  355. Value, FK_GPRel_4));
  356. DF->getContents().resize(DF->getContents().size() + 4, 0);
  357. }
  358. // Associate GPRel32 fixup with data and resize data area
  359. void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
  360. MCDataFragment *DF = getOrCreateDataFragment();
  361. flushPendingLabels(DF, DF->getContents().size());
  362. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  363. Value, FK_GPRel_4));
  364. DF->getContents().resize(DF->getContents().size() + 8, 0);
  365. }
  366. void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
  367. // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
  368. // problems evaluating expressions across multiple fragments.
  369. MCDataFragment *DF = getOrCreateDataFragment();
  370. flushPendingLabels(DF, DF->getContents().size());
  371. DF->getContents().append(NumBytes, FillValue);
  372. }
  373. void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
  374. const MCSection *Sec = getCurrentSection().first;
  375. assert(Sec && "need a section");
  376. unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
  377. insert(new MCFillFragment(0, ItemSize, NumBytes));
  378. }
  379. void MCObjectStreamer::FinishImpl() {
  380. // If we are generating dwarf for assembly source files dump out the sections.
  381. if (getContext().getGenDwarfForAssembly())
  382. MCGenDwarfInfo::Emit(this);
  383. // Dump out the dwarf file & directory tables and line tables.
  384. MCDwarfLineTable::Emit(this);
  385. flushPendingLabels(nullptr);
  386. getAssembler().Finish();
  387. }