MCObjectStreamer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
  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/MCObjectStreamer.h"
  9. #include "llvm/MC/MCAsmBackend.h"
  10. #include "llvm/MC/MCAsmInfo.h"
  11. #include "llvm/MC/MCAssembler.h"
  12. #include "llvm/MC/MCCodeEmitter.h"
  13. #include "llvm/MC/MCCodeView.h"
  14. #include "llvm/MC/MCContext.h"
  15. #include "llvm/MC/MCDwarf.h"
  16. #include "llvm/MC/MCExpr.h"
  17. #include "llvm/MC/MCObjectFileInfo.h"
  18. #include "llvm/MC/MCObjectWriter.h"
  19. #include "llvm/MC/MCSection.h"
  20. #include "llvm/MC/MCSymbol.h"
  21. #include "llvm/MC/MCValue.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include "llvm/Support/SourceMgr.h"
  24. using namespace llvm;
  25. MCObjectStreamer::MCObjectStreamer(MCContext &Context,
  26. std::unique_ptr<MCAsmBackend> TAB,
  27. std::unique_ptr<MCObjectWriter> OW,
  28. std::unique_ptr<MCCodeEmitter> Emitter)
  29. : MCStreamer(Context),
  30. Assembler(std::make_unique<MCAssembler>(
  31. Context, std::move(TAB), std::move(Emitter), std::move(OW))),
  32. EmitEHFrame(true), EmitDebugFrame(false) {
  33. if (Assembler->getBackendPtr())
  34. setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
  35. }
  36. MCObjectStreamer::~MCObjectStreamer() = default;
  37. // AssemblerPtr is used for evaluation of expressions and causes
  38. // difference between asm and object outputs. Return nullptr to in
  39. // inline asm mode to limit divergence to assembly inputs.
  40. MCAssembler *MCObjectStreamer::getAssemblerPtr() {
  41. if (getUseAssemblerInfoForParsing())
  42. return Assembler.get();
  43. return nullptr;
  44. }
  45. void MCObjectStreamer::addPendingLabel(MCSymbol* S) {
  46. MCSection *CurSection = getCurrentSectionOnly();
  47. if (CurSection) {
  48. // Register labels that have not yet been assigned to a Section.
  49. if (!PendingLabels.empty()) {
  50. for (MCSymbol* Sym : PendingLabels)
  51. CurSection->addPendingLabel(Sym);
  52. PendingLabels.clear();
  53. }
  54. // Add this label to the current Section / Subsection.
  55. CurSection->addPendingLabel(S, CurSubsectionIdx);
  56. // Add this Section to the list of PendingLabelSections.
  57. PendingLabelSections.insert(CurSection);
  58. } else
  59. // There is no Section / Subsection for this label yet.
  60. PendingLabels.push_back(S);
  61. }
  62. void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
  63. MCSection *CurSection = getCurrentSectionOnly();
  64. if (!CurSection) {
  65. assert(PendingLabels.empty());
  66. return;
  67. }
  68. // Register labels that have not yet been assigned to a Section.
  69. if (!PendingLabels.empty()) {
  70. for (MCSymbol* Sym : PendingLabels)
  71. CurSection->addPendingLabel(Sym, CurSubsectionIdx);
  72. PendingLabels.clear();
  73. }
  74. // Associate a fragment with this label, either the supplied fragment
  75. // or an empty data fragment.
  76. if (F)
  77. CurSection->flushPendingLabels(F, FOffset, CurSubsectionIdx);
  78. else
  79. CurSection->flushPendingLabels(nullptr, 0, CurSubsectionIdx);
  80. }
  81. void MCObjectStreamer::flushPendingLabels() {
  82. // Register labels that have not yet been assigned to a Section.
  83. if (!PendingLabels.empty()) {
  84. MCSection *CurSection = getCurrentSectionOnly();
  85. assert(CurSection);
  86. for (MCSymbol* Sym : PendingLabels)
  87. CurSection->addPendingLabel(Sym, CurSubsectionIdx);
  88. PendingLabels.clear();
  89. }
  90. // Assign an empty data fragment to all remaining pending labels.
  91. for (MCSection* Section : PendingLabelSections)
  92. Section->flushPendingLabels();
  93. }
  94. // When fixup's offset is a forward declared label, e.g.:
  95. //
  96. // .reloc 1f, R_MIPS_JALR, foo
  97. // 1: nop
  98. //
  99. // postpone adding it to Fixups vector until the label is defined and its offset
  100. // is known.
  101. void MCObjectStreamer::resolvePendingFixups() {
  102. for (PendingMCFixup &PendingFixup : PendingFixups) {
  103. if (!PendingFixup.Sym || PendingFixup.Sym->isUndefined ()) {
  104. getContext().reportError(PendingFixup.Fixup.getLoc(),
  105. "unresolved relocation offset");
  106. continue;
  107. }
  108. flushPendingLabels(PendingFixup.DF, PendingFixup.DF->getContents().size());
  109. PendingFixup.Fixup.setOffset(PendingFixup.Sym->getOffset() +
  110. PendingFixup.Fixup.getOffset());
  111. // If the location symbol to relocate is in MCEncodedFragmentWithFixups,
  112. // put the Fixup into location symbol's fragment. Otherwise
  113. // put into PendingFixup.DF
  114. MCFragment *SymFragment = PendingFixup.Sym->getFragment();
  115. switch (SymFragment->getKind()) {
  116. case MCFragment::FT_Relaxable:
  117. case MCFragment::FT_Dwarf:
  118. case MCFragment::FT_PseudoProbe:
  119. cast<MCEncodedFragmentWithFixups<8, 1>>(SymFragment)
  120. ->getFixups()
  121. .push_back(PendingFixup.Fixup);
  122. break;
  123. case MCFragment::FT_Data:
  124. case MCFragment::FT_CVDefRange:
  125. cast<MCEncodedFragmentWithFixups<32, 4>>(SymFragment)
  126. ->getFixups()
  127. .push_back(PendingFixup.Fixup);
  128. break;
  129. default:
  130. PendingFixup.DF->getFixups().push_back(PendingFixup.Fixup);
  131. break;
  132. }
  133. }
  134. PendingFixups.clear();
  135. }
  136. // As a compile-time optimization, avoid allocating and evaluating an MCExpr
  137. // tree for (Hi - Lo) when Hi and Lo are offsets into the same fragment.
  138. static std::optional<uint64_t> absoluteSymbolDiff(const MCSymbol *Hi,
  139. const MCSymbol *Lo) {
  140. assert(Hi && Lo);
  141. if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() ||
  142. Hi->isVariable() || Lo->isVariable())
  143. return std::nullopt;
  144. return Hi->getOffset() - Lo->getOffset();
  145. }
  146. void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
  147. const MCSymbol *Lo,
  148. unsigned Size) {
  149. if (!getAssembler().getContext().getTargetTriple().isRISCV())
  150. if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo))
  151. return emitIntValue(*Diff, Size);
  152. MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
  153. }
  154. void MCObjectStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
  155. const MCSymbol *Lo) {
  156. if (!getAssembler().getContext().getTargetTriple().isRISCV())
  157. if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo)) {
  158. emitULEB128IntValue(*Diff);
  159. return;
  160. }
  161. MCStreamer::emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
  162. }
  163. void MCObjectStreamer::reset() {
  164. if (Assembler)
  165. Assembler->reset();
  166. CurInsertionPoint = MCSection::iterator();
  167. EmitEHFrame = true;
  168. EmitDebugFrame = false;
  169. PendingLabels.clear();
  170. PendingLabelSections.clear();
  171. MCStreamer::reset();
  172. }
  173. void MCObjectStreamer::emitFrames(MCAsmBackend *MAB) {
  174. if (!getNumFrameInfos())
  175. return;
  176. if (EmitEHFrame)
  177. MCDwarfFrameEmitter::Emit(*this, MAB, true);
  178. if (EmitDebugFrame)
  179. MCDwarfFrameEmitter::Emit(*this, MAB, false);
  180. }
  181. MCFragment *MCObjectStreamer::getCurrentFragment() const {
  182. assert(getCurrentSectionOnly() && "No current section!");
  183. if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
  184. return &*std::prev(CurInsertionPoint);
  185. return nullptr;
  186. }
  187. static bool canReuseDataFragment(const MCDataFragment &F,
  188. const MCAssembler &Assembler,
  189. const MCSubtargetInfo *STI) {
  190. if (!F.hasInstructions())
  191. return true;
  192. // When bundling is enabled, we don't want to add data to a fragment that
  193. // already has instructions (see MCELFStreamer::emitInstToData for details)
  194. if (Assembler.isBundlingEnabled())
  195. return Assembler.getRelaxAll();
  196. // If the subtarget is changed mid fragment we start a new fragment to record
  197. // the new STI.
  198. return !STI || F.getSubtargetInfo() == STI;
  199. }
  200. MCDataFragment *
  201. MCObjectStreamer::getOrCreateDataFragment(const MCSubtargetInfo *STI) {
  202. MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
  203. if (!F || !canReuseDataFragment(*F, *Assembler, STI)) {
  204. F = new MCDataFragment();
  205. insert(F);
  206. }
  207. return F;
  208. }
  209. void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
  210. Assembler->registerSymbol(Sym);
  211. }
  212. void MCObjectStreamer::emitCFISections(bool EH, bool Debug) {
  213. MCStreamer::emitCFISections(EH, Debug);
  214. EmitEHFrame = EH;
  215. EmitDebugFrame = Debug;
  216. }
  217. void MCObjectStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
  218. SMLoc Loc) {
  219. MCStreamer::emitValueImpl(Value, Size, Loc);
  220. MCDataFragment *DF = getOrCreateDataFragment();
  221. flushPendingLabels(DF, DF->getContents().size());
  222. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  223. // Avoid fixups when possible.
  224. int64_t AbsValue;
  225. if (Value->evaluateAsAbsolute(AbsValue, getAssemblerPtr())) {
  226. if (!isUIntN(8 * Size, AbsValue) && !isIntN(8 * Size, AbsValue)) {
  227. getContext().reportError(
  228. Loc, "value evaluated as " + Twine(AbsValue) + " is out of range.");
  229. return;
  230. }
  231. emitIntValue(AbsValue, Size);
  232. return;
  233. }
  234. DF->getFixups().push_back(
  235. MCFixup::create(DF->getContents().size(), Value,
  236. MCFixup::getKindForSize(Size, false), Loc));
  237. DF->getContents().resize(DF->getContents().size() + Size, 0);
  238. }
  239. MCSymbol *MCObjectStreamer::emitCFILabel() {
  240. MCSymbol *Label = getContext().createTempSymbol("cfi");
  241. emitLabel(Label);
  242. return Label;
  243. }
  244. void MCObjectStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
  245. // We need to create a local symbol to avoid relocations.
  246. Frame.Begin = getContext().createTempSymbol();
  247. emitLabel(Frame.Begin);
  248. }
  249. void MCObjectStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
  250. Frame.End = getContext().createTempSymbol();
  251. emitLabel(Frame.End);
  252. }
  253. void MCObjectStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
  254. MCStreamer::emitLabel(Symbol, Loc);
  255. getAssembler().registerSymbol(*Symbol);
  256. // If there is a current fragment, mark the symbol as pointing into it.
  257. // Otherwise queue the label and set its fragment pointer when we emit the
  258. // next fragment.
  259. auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
  260. if (F && !(getAssembler().isBundlingEnabled() &&
  261. getAssembler().getRelaxAll())) {
  262. Symbol->setFragment(F);
  263. Symbol->setOffset(F->getContents().size());
  264. } else {
  265. // Assign all pending labels to offset 0 within the dummy "pending"
  266. // fragment. (They will all be reassigned to a real fragment in
  267. // flushPendingLabels())
  268. Symbol->setOffset(0);
  269. addPendingLabel(Symbol);
  270. }
  271. emitPendingAssignments(Symbol);
  272. }
  273. void MCObjectStreamer::emitPendingAssignments(MCSymbol *Symbol) {
  274. auto Assignments = pendingAssignments.find(Symbol);
  275. if (Assignments != pendingAssignments.end()) {
  276. for (const PendingAssignment &A : Assignments->second)
  277. emitAssignment(A.Symbol, A.Value);
  278. pendingAssignments.erase(Assignments);
  279. }
  280. }
  281. // Emit a label at a previously emitted fragment/offset position. This must be
  282. // within the currently-active section.
  283. void MCObjectStreamer::emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc,
  284. MCFragment *F, uint64_t Offset) {
  285. assert(F->getParent() == getCurrentSectionOnly());
  286. MCStreamer::emitLabel(Symbol, Loc);
  287. getAssembler().registerSymbol(*Symbol);
  288. auto *DF = dyn_cast_or_null<MCDataFragment>(F);
  289. Symbol->setOffset(Offset);
  290. if (DF) {
  291. Symbol->setFragment(F);
  292. } else {
  293. assert(isa<MCDummyFragment>(F) &&
  294. "F must either be an MCDataFragment or the pending MCDummyFragment");
  295. assert(Offset == 0);
  296. addPendingLabel(Symbol);
  297. }
  298. }
  299. void MCObjectStreamer::emitULEB128Value(const MCExpr *Value) {
  300. int64_t IntValue;
  301. if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) {
  302. emitULEB128IntValue(IntValue);
  303. return;
  304. }
  305. insert(new MCLEBFragment(*Value, false));
  306. }
  307. void MCObjectStreamer::emitSLEB128Value(const MCExpr *Value) {
  308. int64_t IntValue;
  309. if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) {
  310. emitSLEB128IntValue(IntValue);
  311. return;
  312. }
  313. insert(new MCLEBFragment(*Value, true));
  314. }
  315. void MCObjectStreamer::emitWeakReference(MCSymbol *Alias,
  316. const MCSymbol *Symbol) {
  317. report_fatal_error("This file format doesn't support weak aliases.");
  318. }
  319. void MCObjectStreamer::changeSection(MCSection *Section,
  320. const MCExpr *Subsection) {
  321. changeSectionImpl(Section, Subsection);
  322. }
  323. bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
  324. const MCExpr *Subsection) {
  325. assert(Section && "Cannot switch to a null section!");
  326. getContext().clearDwarfLocSeen();
  327. bool Created = getAssembler().registerSection(*Section);
  328. int64_t IntSubsection = 0;
  329. if (Subsection &&
  330. !Subsection->evaluateAsAbsolute(IntSubsection, getAssemblerPtr()))
  331. report_fatal_error("Cannot evaluate subsection number");
  332. if (IntSubsection < 0 || IntSubsection > 8192)
  333. report_fatal_error("Subsection number out of range");
  334. CurSubsectionIdx = unsigned(IntSubsection);
  335. CurInsertionPoint =
  336. Section->getSubsectionInsertionPoint(CurSubsectionIdx);
  337. return Created;
  338. }
  339. void MCObjectStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
  340. getAssembler().registerSymbol(*Symbol);
  341. MCStreamer::emitAssignment(Symbol, Value);
  342. emitPendingAssignments(Symbol);
  343. }
  344. void MCObjectStreamer::emitConditionalAssignment(MCSymbol *Symbol,
  345. const MCExpr *Value) {
  346. const MCSymbol *Target = &cast<MCSymbolRefExpr>(*Value).getSymbol();
  347. // If the symbol already exists, emit the assignment. Otherwise, emit it
  348. // later only if the symbol is also emitted.
  349. if (Target->isRegistered())
  350. emitAssignment(Symbol, Value);
  351. else
  352. pendingAssignments[Target].push_back({Symbol, Value});
  353. }
  354. bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
  355. return Sec.hasInstructions();
  356. }
  357. void MCObjectStreamer::emitInstruction(const MCInst &Inst,
  358. const MCSubtargetInfo &STI) {
  359. const MCSection &Sec = *getCurrentSectionOnly();
  360. if (Sec.isVirtualSection()) {
  361. getContext().reportError(Inst.getLoc(), Twine(Sec.getVirtualSectionKind()) +
  362. " section '" + Sec.getName() +
  363. "' cannot have instructions");
  364. return;
  365. }
  366. getAssembler().getBackend().emitInstructionBegin(*this, Inst, STI);
  367. emitInstructionImpl(Inst, STI);
  368. getAssembler().getBackend().emitInstructionEnd(*this, Inst);
  369. }
  370. void MCObjectStreamer::emitInstructionImpl(const MCInst &Inst,
  371. const MCSubtargetInfo &STI) {
  372. MCStreamer::emitInstruction(Inst, STI);
  373. MCSection *Sec = getCurrentSectionOnly();
  374. Sec->setHasInstructions(true);
  375. // Now that a machine instruction has been assembled into this section, make
  376. // a line entry for any .loc directive that has been seen.
  377. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  378. // If this instruction doesn't need relaxation, just emit it as data.
  379. MCAssembler &Assembler = getAssembler();
  380. MCAsmBackend &Backend = Assembler.getBackend();
  381. if (!(Backend.mayNeedRelaxation(Inst, STI) ||
  382. Backend.allowEnhancedRelaxation())) {
  383. emitInstToData(Inst, STI);
  384. return;
  385. }
  386. // Otherwise, relax and emit it as data if either:
  387. // - The RelaxAll flag was passed
  388. // - Bundling is enabled and this instruction is inside a bundle-locked
  389. // group. We want to emit all such instructions into the same data
  390. // fragment.
  391. if (Assembler.getRelaxAll() ||
  392. (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
  393. MCInst Relaxed = Inst;
  394. while (Backend.mayNeedRelaxation(Relaxed, STI))
  395. Backend.relaxInstruction(Relaxed, STI);
  396. emitInstToData(Relaxed, STI);
  397. return;
  398. }
  399. // Otherwise emit to a separate fragment.
  400. emitInstToFragment(Inst, STI);
  401. }
  402. void MCObjectStreamer::emitInstToFragment(const MCInst &Inst,
  403. const MCSubtargetInfo &STI) {
  404. if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
  405. llvm_unreachable("All instructions should have already been relaxed");
  406. // Always create a new, separate fragment here, because its size can change
  407. // during relaxation.
  408. MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
  409. insert(IF);
  410. SmallString<128> Code;
  411. raw_svector_ostream VecOS(Code);
  412. getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
  413. STI);
  414. IF->getContents().append(Code.begin(), Code.end());
  415. }
  416. #ifndef NDEBUG
  417. static const char *const BundlingNotImplementedMsg =
  418. "Aligned bundling is not implemented for this object format";
  419. #endif
  420. void MCObjectStreamer::emitBundleAlignMode(Align Alignment) {
  421. llvm_unreachable(BundlingNotImplementedMsg);
  422. }
  423. void MCObjectStreamer::emitBundleLock(bool AlignToEnd) {
  424. llvm_unreachable(BundlingNotImplementedMsg);
  425. }
  426. void MCObjectStreamer::emitBundleUnlock() {
  427. llvm_unreachable(BundlingNotImplementedMsg);
  428. }
  429. void MCObjectStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
  430. unsigned Column, unsigned Flags,
  431. unsigned Isa,
  432. unsigned Discriminator,
  433. StringRef FileName) {
  434. // In case we see two .loc directives in a row, make sure the
  435. // first one gets a line entry.
  436. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  437. this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
  438. Discriminator, FileName);
  439. }
  440. static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
  441. const MCSymbol *B) {
  442. MCContext &Context = OS.getContext();
  443. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  444. const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
  445. const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
  446. const MCExpr *AddrDelta =
  447. MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
  448. return AddrDelta;
  449. }
  450. static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
  451. MCDwarfLineTableParams Params,
  452. int64_t LineDelta, const MCSymbol *Label,
  453. int PointerSize) {
  454. // emit the sequence to set the address
  455. OS.emitIntValue(dwarf::DW_LNS_extended_op, 1);
  456. OS.emitULEB128IntValue(PointerSize + 1);
  457. OS.emitIntValue(dwarf::DW_LNE_set_address, 1);
  458. OS.emitSymbolValue(Label, PointerSize);
  459. // emit the sequence for the LineDelta (from 1) and a zero address delta.
  460. MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
  461. }
  462. void MCObjectStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta,
  463. const MCSymbol *LastLabel,
  464. const MCSymbol *Label,
  465. unsigned PointerSize) {
  466. if (!LastLabel) {
  467. emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta,
  468. Label, PointerSize);
  469. return;
  470. }
  471. const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
  472. int64_t Res;
  473. if (AddrDelta->evaluateAsAbsolute(Res, getAssemblerPtr())) {
  474. MCDwarfLineAddr::Emit(this, Assembler->getDWARFLinetableParams(), LineDelta,
  475. Res);
  476. return;
  477. }
  478. insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
  479. }
  480. void MCObjectStreamer::emitDwarfLineEndEntry(MCSection *Section,
  481. MCSymbol *LastLabel) {
  482. // Emit a DW_LNE_end_sequence for the end of the section.
  483. // Use the section end label to compute the address delta and use INT64_MAX
  484. // as the line delta which is the signal that this is actually a
  485. // DW_LNE_end_sequence.
  486. MCSymbol *SectionEnd = endSection(Section);
  487. // Switch back the dwarf line section, in case endSection had to switch the
  488. // section.
  489. MCContext &Ctx = getContext();
  490. switchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
  491. const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
  492. emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
  493. AsmInfo->getCodePointerSize());
  494. }
  495. void MCObjectStreamer::emitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
  496. const MCSymbol *Label) {
  497. const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
  498. int64_t Res;
  499. if (AddrDelta->evaluateAsAbsolute(Res, getAssemblerPtr())) {
  500. MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
  501. return;
  502. }
  503. insert(new MCDwarfCallFrameFragment(*AddrDelta));
  504. }
  505. void MCObjectStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
  506. unsigned Line, unsigned Column,
  507. bool PrologueEnd, bool IsStmt,
  508. StringRef FileName, SMLoc Loc) {
  509. // Validate the directive.
  510. if (!checkCVLocSection(FunctionId, FileNo, Loc))
  511. return;
  512. // Emit a label at the current position and record it in the CodeViewContext.
  513. MCSymbol *LineSym = getContext().createTempSymbol();
  514. emitLabel(LineSym);
  515. getContext().getCVContext().recordCVLoc(getContext(), LineSym, FunctionId,
  516. FileNo, Line, Column, PrologueEnd,
  517. IsStmt);
  518. }
  519. void MCObjectStreamer::emitCVLinetableDirective(unsigned FunctionId,
  520. const MCSymbol *Begin,
  521. const MCSymbol *End) {
  522. getContext().getCVContext().emitLineTableForFunction(*this, FunctionId, Begin,
  523. End);
  524. this->MCStreamer::emitCVLinetableDirective(FunctionId, Begin, End);
  525. }
  526. void MCObjectStreamer::emitCVInlineLinetableDirective(
  527. unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum,
  528. const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) {
  529. getContext().getCVContext().emitInlineLineTableForFunction(
  530. *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym,
  531. FnEndSym);
  532. this->MCStreamer::emitCVInlineLinetableDirective(
  533. PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
  534. }
  535. void MCObjectStreamer::emitCVDefRangeDirective(
  536. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  537. StringRef FixedSizePortion) {
  538. MCFragment *Frag =
  539. getContext().getCVContext().emitDefRange(*this, Ranges, FixedSizePortion);
  540. // Attach labels that were pending before we created the defrange fragment to
  541. // the beginning of the new fragment.
  542. flushPendingLabels(Frag, 0);
  543. this->MCStreamer::emitCVDefRangeDirective(Ranges, FixedSizePortion);
  544. }
  545. void MCObjectStreamer::emitCVStringTableDirective() {
  546. getContext().getCVContext().emitStringTable(*this);
  547. }
  548. void MCObjectStreamer::emitCVFileChecksumsDirective() {
  549. getContext().getCVContext().emitFileChecksums(*this);
  550. }
  551. void MCObjectStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
  552. getContext().getCVContext().emitFileChecksumOffset(*this, FileNo);
  553. }
  554. void MCObjectStreamer::emitBytes(StringRef Data) {
  555. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  556. MCDataFragment *DF = getOrCreateDataFragment();
  557. flushPendingLabels(DF, DF->getContents().size());
  558. DF->getContents().append(Data.begin(), Data.end());
  559. }
  560. void MCObjectStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
  561. unsigned ValueSize,
  562. unsigned MaxBytesToEmit) {
  563. if (MaxBytesToEmit == 0)
  564. MaxBytesToEmit = Alignment.value();
  565. insert(new MCAlignFragment(Alignment, Value, ValueSize, MaxBytesToEmit));
  566. // Update the maximum alignment on the current section if necessary.
  567. MCSection *CurSec = getCurrentSectionOnly();
  568. CurSec->ensureMinAlignment(Alignment);
  569. }
  570. void MCObjectStreamer::emitCodeAlignment(Align Alignment,
  571. const MCSubtargetInfo *STI,
  572. unsigned MaxBytesToEmit) {
  573. emitValueToAlignment(Alignment, 0, 1, MaxBytesToEmit);
  574. cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true, STI);
  575. }
  576. void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
  577. unsigned char Value,
  578. SMLoc Loc) {
  579. insert(new MCOrgFragment(*Offset, Value, Loc));
  580. }
  581. // Associate DTPRel32 fixup with data and resize data area
  582. void MCObjectStreamer::emitDTPRel32Value(const MCExpr *Value) {
  583. MCDataFragment *DF = getOrCreateDataFragment();
  584. flushPendingLabels(DF, DF->getContents().size());
  585. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  586. Value, FK_DTPRel_4));
  587. DF->getContents().resize(DF->getContents().size() + 4, 0);
  588. }
  589. // Associate DTPRel64 fixup with data and resize data area
  590. void MCObjectStreamer::emitDTPRel64Value(const MCExpr *Value) {
  591. MCDataFragment *DF = getOrCreateDataFragment();
  592. flushPendingLabels(DF, DF->getContents().size());
  593. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  594. Value, FK_DTPRel_8));
  595. DF->getContents().resize(DF->getContents().size() + 8, 0);
  596. }
  597. // Associate TPRel32 fixup with data and resize data area
  598. void MCObjectStreamer::emitTPRel32Value(const MCExpr *Value) {
  599. MCDataFragment *DF = getOrCreateDataFragment();
  600. flushPendingLabels(DF, DF->getContents().size());
  601. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  602. Value, FK_TPRel_4));
  603. DF->getContents().resize(DF->getContents().size() + 4, 0);
  604. }
  605. // Associate TPRel64 fixup with data and resize data area
  606. void MCObjectStreamer::emitTPRel64Value(const MCExpr *Value) {
  607. MCDataFragment *DF = getOrCreateDataFragment();
  608. flushPendingLabels(DF, DF->getContents().size());
  609. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  610. Value, FK_TPRel_8));
  611. DF->getContents().resize(DF->getContents().size() + 8, 0);
  612. }
  613. // Associate GPRel32 fixup with data and resize data area
  614. void MCObjectStreamer::emitGPRel32Value(const MCExpr *Value) {
  615. MCDataFragment *DF = getOrCreateDataFragment();
  616. flushPendingLabels(DF, DF->getContents().size());
  617. DF->getFixups().push_back(
  618. MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4));
  619. DF->getContents().resize(DF->getContents().size() + 4, 0);
  620. }
  621. // Associate GPRel64 fixup with data and resize data area
  622. void MCObjectStreamer::emitGPRel64Value(const MCExpr *Value) {
  623. MCDataFragment *DF = getOrCreateDataFragment();
  624. flushPendingLabels(DF, DF->getContents().size());
  625. DF->getFixups().push_back(
  626. MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4));
  627. DF->getContents().resize(DF->getContents().size() + 8, 0);
  628. }
  629. static std::optional<std::pair<bool, std::string>>
  630. getOffsetAndDataFragment(const MCSymbol &Symbol, uint32_t &RelocOffset,
  631. MCDataFragment *&DF) {
  632. if (Symbol.isVariable()) {
  633. const MCExpr *SymbolExpr = Symbol.getVariableValue();
  634. MCValue OffsetVal;
  635. if(!SymbolExpr->evaluateAsRelocatable(OffsetVal, nullptr, nullptr))
  636. return std::make_pair(false,
  637. std::string("symbol in .reloc offset is not "
  638. "relocatable"));
  639. if (OffsetVal.isAbsolute()) {
  640. RelocOffset = OffsetVal.getConstant();
  641. MCFragment *Fragment = Symbol.getFragment();
  642. // FIXME Support symbols with no DF. For example:
  643. // .reloc .data, ENUM_VALUE, <some expr>
  644. if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
  645. return std::make_pair(false,
  646. std::string("symbol in offset has no data "
  647. "fragment"));
  648. DF = cast<MCDataFragment>(Fragment);
  649. return std::nullopt;
  650. }
  651. if (OffsetVal.getSymB())
  652. return std::make_pair(false,
  653. std::string(".reloc symbol offset is not "
  654. "representable"));
  655. const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA());
  656. if (!SRE.getSymbol().isDefined())
  657. return std::make_pair(false,
  658. std::string("symbol used in the .reloc offset is "
  659. "not defined"));
  660. if (SRE.getSymbol().isVariable())
  661. return std::make_pair(false,
  662. std::string("symbol used in the .reloc offset is "
  663. "variable"));
  664. MCFragment *Fragment = SRE.getSymbol().getFragment();
  665. // FIXME Support symbols with no DF. For example:
  666. // .reloc .data, ENUM_VALUE, <some expr>
  667. if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
  668. return std::make_pair(false,
  669. std::string("symbol in offset has no data "
  670. "fragment"));
  671. RelocOffset = SRE.getSymbol().getOffset() + OffsetVal.getConstant();
  672. DF = cast<MCDataFragment>(Fragment);
  673. } else {
  674. RelocOffset = Symbol.getOffset();
  675. MCFragment *Fragment = Symbol.getFragment();
  676. // FIXME Support symbols with no DF. For example:
  677. // .reloc .data, ENUM_VALUE, <some expr>
  678. if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
  679. return std::make_pair(false,
  680. std::string("symbol in offset has no data "
  681. "fragment"));
  682. DF = cast<MCDataFragment>(Fragment);
  683. }
  684. return std::nullopt;
  685. }
  686. std::optional<std::pair<bool, std::string>>
  687. MCObjectStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
  688. const MCExpr *Expr, SMLoc Loc,
  689. const MCSubtargetInfo &STI) {
  690. std::optional<MCFixupKind> MaybeKind =
  691. Assembler->getBackend().getFixupKind(Name);
  692. if (!MaybeKind)
  693. return std::make_pair(true, std::string("unknown relocation name"));
  694. MCFixupKind Kind = *MaybeKind;
  695. if (Expr == nullptr)
  696. Expr =
  697. MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext());
  698. MCDataFragment *DF = getOrCreateDataFragment(&STI);
  699. flushPendingLabels(DF, DF->getContents().size());
  700. MCValue OffsetVal;
  701. if (!Offset.evaluateAsRelocatable(OffsetVal, nullptr, nullptr))
  702. return std::make_pair(false,
  703. std::string(".reloc offset is not relocatable"));
  704. if (OffsetVal.isAbsolute()) {
  705. if (OffsetVal.getConstant() < 0)
  706. return std::make_pair(false, std::string(".reloc offset is negative"));
  707. DF->getFixups().push_back(
  708. MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc));
  709. return std::nullopt;
  710. }
  711. if (OffsetVal.getSymB())
  712. return std::make_pair(false,
  713. std::string(".reloc offset is not representable"));
  714. const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA());
  715. const MCSymbol &Symbol = SRE.getSymbol();
  716. if (Symbol.isDefined()) {
  717. uint32_t SymbolOffset = 0;
  718. std::optional<std::pair<bool, std::string>> Error =
  719. getOffsetAndDataFragment(Symbol, SymbolOffset, DF);
  720. if (Error != std::nullopt)
  721. return Error;
  722. DF->getFixups().push_back(
  723. MCFixup::create(SymbolOffset + OffsetVal.getConstant(),
  724. Expr, Kind, Loc));
  725. return std::nullopt;
  726. }
  727. PendingFixups.emplace_back(
  728. &SRE.getSymbol(), DF,
  729. MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc));
  730. return std::nullopt;
  731. }
  732. void MCObjectStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
  733. SMLoc Loc) {
  734. MCDataFragment *DF = getOrCreateDataFragment();
  735. flushPendingLabels(DF, DF->getContents().size());
  736. assert(getCurrentSectionOnly() && "need a section");
  737. insert(new MCFillFragment(FillValue, 1, NumBytes, Loc));
  738. }
  739. void MCObjectStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
  740. int64_t Expr, SMLoc Loc) {
  741. int64_t IntNumValues;
  742. // Do additional checking now if we can resolve the value.
  743. if (NumValues.evaluateAsAbsolute(IntNumValues, getAssemblerPtr())) {
  744. if (IntNumValues < 0) {
  745. getContext().getSourceManager()->PrintMessage(
  746. Loc, SourceMgr::DK_Warning,
  747. "'.fill' directive with negative repeat count has no effect");
  748. return;
  749. }
  750. // Emit now if we can for better errors.
  751. int64_t NonZeroSize = Size > 4 ? 4 : Size;
  752. Expr &= ~0ULL >> (64 - NonZeroSize * 8);
  753. for (uint64_t i = 0, e = IntNumValues; i != e; ++i) {
  754. emitIntValue(Expr, NonZeroSize);
  755. if (NonZeroSize < Size)
  756. emitIntValue(0, Size - NonZeroSize);
  757. }
  758. return;
  759. }
  760. // Otherwise emit as fragment.
  761. MCDataFragment *DF = getOrCreateDataFragment();
  762. flushPendingLabels(DF, DF->getContents().size());
  763. assert(getCurrentSectionOnly() && "need a section");
  764. insert(new MCFillFragment(Expr, Size, NumValues, Loc));
  765. }
  766. void MCObjectStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLength,
  767. SMLoc Loc, const MCSubtargetInfo &STI) {
  768. // Emit an NOP fragment.
  769. MCDataFragment *DF = getOrCreateDataFragment();
  770. flushPendingLabels(DF, DF->getContents().size());
  771. assert(getCurrentSectionOnly() && "need a section");
  772. insert(new MCNopsFragment(NumBytes, ControlledNopLength, Loc, STI));
  773. }
  774. void MCObjectStreamer::emitFileDirective(StringRef Filename) {
  775. getAssembler().addFileName(Filename);
  776. }
  777. void MCObjectStreamer::emitFileDirective(StringRef Filename,
  778. StringRef CompilerVerion,
  779. StringRef TimeStamp,
  780. StringRef Description) {
  781. getAssembler().addFileName(Filename);
  782. // TODO: add additional info to integrated assembler.
  783. }
  784. void MCObjectStreamer::emitAddrsig() {
  785. getAssembler().getWriter().emitAddrsigSection();
  786. }
  787. void MCObjectStreamer::emitAddrsigSym(const MCSymbol *Sym) {
  788. getAssembler().getWriter().addAddrsigSymbol(Sym);
  789. }
  790. void MCObjectStreamer::finishImpl() {
  791. getContext().RemapDebugPaths();
  792. // If we are generating dwarf for assembly source files dump out the sections.
  793. if (getContext().getGenDwarfForAssembly())
  794. MCGenDwarfInfo::Emit(this);
  795. // Dump out the dwarf file & directory tables and line tables.
  796. MCDwarfLineTable::emit(this, getAssembler().getDWARFLinetableParams());
  797. // Emit pseudo probes for the current module.
  798. MCPseudoProbeTable::emit(this);
  799. // Update any remaining pending labels with empty data fragments.
  800. flushPendingLabels();
  801. resolvePendingFixups();
  802. getAssembler().Finish();
  803. }