MCAssembler.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
  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/MCAssembler.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/SmallString.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/Statistic.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/Twine.h"
  15. #include "llvm/MC/MCAsmBackend.h"
  16. #include "llvm/MC/MCAsmInfo.h"
  17. #include "llvm/MC/MCAsmLayout.h"
  18. #include "llvm/MC/MCCodeEmitter.h"
  19. #include "llvm/MC/MCCodeView.h"
  20. #include "llvm/MC/MCContext.h"
  21. #include "llvm/MC/MCDwarf.h"
  22. #include "llvm/MC/MCExpr.h"
  23. #include "llvm/MC/MCFixup.h"
  24. #include "llvm/MC/MCFixupKindInfo.h"
  25. #include "llvm/MC/MCFragment.h"
  26. #include "llvm/MC/MCInst.h"
  27. #include "llvm/MC/MCObjectWriter.h"
  28. #include "llvm/MC/MCSection.h"
  29. #include "llvm/MC/MCSymbol.h"
  30. #include "llvm/MC/MCValue.h"
  31. #include "llvm/Support/Alignment.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/EndianStream.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/LEB128.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <cassert>
  39. #include <cstdint>
  40. #include <tuple>
  41. #include <utility>
  42. using namespace llvm;
  43. namespace llvm {
  44. class MCSubtargetInfo;
  45. }
  46. #define DEBUG_TYPE "assembler"
  47. namespace {
  48. namespace stats {
  49. STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
  50. STATISTIC(EmittedRelaxableFragments,
  51. "Number of emitted assembler fragments - relaxable");
  52. STATISTIC(EmittedDataFragments,
  53. "Number of emitted assembler fragments - data");
  54. STATISTIC(EmittedCompactEncodedInstFragments,
  55. "Number of emitted assembler fragments - compact encoded inst");
  56. STATISTIC(EmittedAlignFragments,
  57. "Number of emitted assembler fragments - align");
  58. STATISTIC(EmittedFillFragments,
  59. "Number of emitted assembler fragments - fill");
  60. STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
  61. STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
  62. STATISTIC(evaluateFixup, "Number of evaluated fixups");
  63. STATISTIC(FragmentLayouts, "Number of fragment layouts");
  64. STATISTIC(ObjectBytes, "Number of emitted object file bytes");
  65. STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
  66. STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
  67. } // end namespace stats
  68. } // end anonymous namespace
  69. // FIXME FIXME FIXME: There are number of places in this file where we convert
  70. // what is a 64-bit assembler value used for computation into a value in the
  71. // object file, which may truncate it. We should detect that truncation where
  72. // invalid and report errors back.
  73. /* *** */
  74. MCAssembler::MCAssembler(MCContext &Context,
  75. std::unique_ptr<MCAsmBackend> Backend,
  76. std::unique_ptr<MCCodeEmitter> Emitter,
  77. std::unique_ptr<MCObjectWriter> Writer)
  78. : Context(Context), Backend(std::move(Backend)),
  79. Emitter(std::move(Emitter)), Writer(std::move(Writer)),
  80. BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
  81. IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
  82. VersionInfo.Major = 0; // Major version == 0 for "none specified"
  83. DarwinTargetVariantVersionInfo.Major = 0;
  84. }
  85. MCAssembler::~MCAssembler() = default;
  86. void MCAssembler::reset() {
  87. Sections.clear();
  88. Symbols.clear();
  89. IndirectSymbols.clear();
  90. DataRegions.clear();
  91. LinkerOptions.clear();
  92. FileNames.clear();
  93. ThumbFuncs.clear();
  94. BundleAlignSize = 0;
  95. RelaxAll = false;
  96. SubsectionsViaSymbols = false;
  97. IncrementalLinkerCompatible = false;
  98. ELFHeaderEFlags = 0;
  99. LOHContainer.reset();
  100. VersionInfo.Major = 0;
  101. VersionInfo.SDKVersion = VersionTuple();
  102. DarwinTargetVariantVersionInfo.Major = 0;
  103. DarwinTargetVariantVersionInfo.SDKVersion = VersionTuple();
  104. // reset objects owned by us
  105. if (getBackendPtr())
  106. getBackendPtr()->reset();
  107. if (getEmitterPtr())
  108. getEmitterPtr()->reset();
  109. if (getWriterPtr())
  110. getWriterPtr()->reset();
  111. getLOHContainer().reset();
  112. }
  113. bool MCAssembler::registerSection(MCSection &Section) {
  114. if (Section.isRegistered())
  115. return false;
  116. Sections.push_back(&Section);
  117. Section.setIsRegistered(true);
  118. return true;
  119. }
  120. bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
  121. if (ThumbFuncs.count(Symbol))
  122. return true;
  123. if (!Symbol->isVariable())
  124. return false;
  125. const MCExpr *Expr = Symbol->getVariableValue();
  126. MCValue V;
  127. if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
  128. return false;
  129. if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
  130. return false;
  131. const MCSymbolRefExpr *Ref = V.getSymA();
  132. if (!Ref)
  133. return false;
  134. if (Ref->getKind() != MCSymbolRefExpr::VK_None)
  135. return false;
  136. const MCSymbol &Sym = Ref->getSymbol();
  137. if (!isThumbFunc(&Sym))
  138. return false;
  139. ThumbFuncs.insert(Symbol); // Cache it.
  140. return true;
  141. }
  142. bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
  143. // Non-temporary labels should always be visible to the linker.
  144. if (!Symbol.isTemporary())
  145. return true;
  146. if (Symbol.isUsedInReloc())
  147. return true;
  148. return false;
  149. }
  150. const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
  151. // Linker visible symbols define atoms.
  152. if (isSymbolLinkerVisible(S))
  153. return &S;
  154. // Absolute and undefined symbols have no defining atom.
  155. if (!S.isInSection())
  156. return nullptr;
  157. // Non-linker visible symbols in sections which can't be atomized have no
  158. // defining atom.
  159. if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
  160. *S.getFragment()->getParent()))
  161. return nullptr;
  162. // Otherwise, return the atom for the containing fragment.
  163. return S.getFragment()->getAtom();
  164. }
  165. bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
  166. const MCFixup &Fixup, const MCFragment *DF,
  167. MCValue &Target, uint64_t &Value,
  168. bool &WasForced) const {
  169. ++stats::evaluateFixup;
  170. // FIXME: This code has some duplication with recordRelocation. We should
  171. // probably merge the two into a single callback that tries to evaluate a
  172. // fixup and records a relocation if one is needed.
  173. // On error claim to have completely evaluated the fixup, to prevent any
  174. // further processing from being done.
  175. const MCExpr *Expr = Fixup.getValue();
  176. MCContext &Ctx = getContext();
  177. Value = 0;
  178. WasForced = false;
  179. if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
  180. Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
  181. return true;
  182. }
  183. if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
  184. if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
  185. Ctx.reportError(Fixup.getLoc(),
  186. "unsupported subtraction of qualified symbol");
  187. return true;
  188. }
  189. }
  190. assert(getBackendPtr() && "Expected assembler backend");
  191. bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
  192. MCFixupKindInfo::FKF_IsTarget;
  193. if (IsTarget)
  194. return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
  195. Value, WasForced);
  196. unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
  197. bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
  198. MCFixupKindInfo::FKF_IsPCRel;
  199. bool IsResolved = false;
  200. if (IsPCRel) {
  201. if (Target.getSymB()) {
  202. IsResolved = false;
  203. } else if (!Target.getSymA()) {
  204. IsResolved = false;
  205. } else {
  206. const MCSymbolRefExpr *A = Target.getSymA();
  207. const MCSymbol &SA = A->getSymbol();
  208. if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
  209. IsResolved = false;
  210. } else if (auto *Writer = getWriterPtr()) {
  211. IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
  212. Writer->isSymbolRefDifferenceFullyResolvedImpl(
  213. *this, SA, *DF, false, true);
  214. }
  215. }
  216. } else {
  217. IsResolved = Target.isAbsolute();
  218. }
  219. Value = Target.getConstant();
  220. if (const MCSymbolRefExpr *A = Target.getSymA()) {
  221. const MCSymbol &Sym = A->getSymbol();
  222. if (Sym.isDefined())
  223. Value += Layout.getSymbolOffset(Sym);
  224. }
  225. if (const MCSymbolRefExpr *B = Target.getSymB()) {
  226. const MCSymbol &Sym = B->getSymbol();
  227. if (Sym.isDefined())
  228. Value -= Layout.getSymbolOffset(Sym);
  229. }
  230. bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
  231. MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
  232. assert((ShouldAlignPC ? IsPCRel : true) &&
  233. "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
  234. if (IsPCRel) {
  235. uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
  236. // A number of ARM fixups in Thumb mode require that the effective PC
  237. // address be determined as the 32-bit aligned version of the actual offset.
  238. if (ShouldAlignPC) Offset &= ~0x3;
  239. Value -= Offset;
  240. }
  241. // Let the backend force a relocation if needed.
  242. if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
  243. IsResolved = false;
  244. WasForced = true;
  245. }
  246. return IsResolved;
  247. }
  248. uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
  249. const MCFragment &F) const {
  250. assert(getBackendPtr() && "Requires assembler backend");
  251. switch (F.getKind()) {
  252. case MCFragment::FT_Data:
  253. return cast<MCDataFragment>(F).getContents().size();
  254. case MCFragment::FT_Relaxable:
  255. return cast<MCRelaxableFragment>(F).getContents().size();
  256. case MCFragment::FT_CompactEncodedInst:
  257. return cast<MCCompactEncodedInstFragment>(F).getContents().size();
  258. case MCFragment::FT_Fill: {
  259. auto &FF = cast<MCFillFragment>(F);
  260. int64_t NumValues = 0;
  261. if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
  262. getContext().reportError(FF.getLoc(),
  263. "expected assembly-time absolute expression");
  264. return 0;
  265. }
  266. int64_t Size = NumValues * FF.getValueSize();
  267. if (Size < 0) {
  268. getContext().reportError(FF.getLoc(), "invalid number of bytes");
  269. return 0;
  270. }
  271. return Size;
  272. }
  273. case MCFragment::FT_Nops:
  274. return cast<MCNopsFragment>(F).getNumBytes();
  275. case MCFragment::FT_LEB:
  276. return cast<MCLEBFragment>(F).getContents().size();
  277. case MCFragment::FT_BoundaryAlign:
  278. return cast<MCBoundaryAlignFragment>(F).getSize();
  279. case MCFragment::FT_SymbolId:
  280. return 4;
  281. case MCFragment::FT_Align: {
  282. const MCAlignFragment &AF = cast<MCAlignFragment>(F);
  283. unsigned Offset = Layout.getFragmentOffset(&AF);
  284. unsigned Size = offsetToAlignment(Offset, AF.getAlignment());
  285. // Insert extra Nops for code alignment if the target define
  286. // shouldInsertExtraNopBytesForCodeAlign target hook.
  287. if (AF.getParent()->useCodeAlign() && AF.hasEmitNops() &&
  288. getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
  289. return Size;
  290. // If we are padding with nops, force the padding to be larger than the
  291. // minimum nop size.
  292. if (Size > 0 && AF.hasEmitNops()) {
  293. while (Size % getBackend().getMinimumNopSize())
  294. Size += AF.getAlignment().value();
  295. }
  296. if (Size > AF.getMaxBytesToEmit())
  297. return 0;
  298. return Size;
  299. }
  300. case MCFragment::FT_Org: {
  301. const MCOrgFragment &OF = cast<MCOrgFragment>(F);
  302. MCValue Value;
  303. if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
  304. getContext().reportError(OF.getLoc(),
  305. "expected assembly-time absolute expression");
  306. return 0;
  307. }
  308. uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
  309. int64_t TargetLocation = Value.getConstant();
  310. if (const MCSymbolRefExpr *A = Value.getSymA()) {
  311. uint64_t Val;
  312. if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
  313. getContext().reportError(OF.getLoc(), "expected absolute expression");
  314. return 0;
  315. }
  316. TargetLocation += Val;
  317. }
  318. int64_t Size = TargetLocation - FragmentOffset;
  319. if (Size < 0 || Size >= 0x40000000) {
  320. getContext().reportError(
  321. OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
  322. "' (at offset '" + Twine(FragmentOffset) + "')");
  323. return 0;
  324. }
  325. return Size;
  326. }
  327. case MCFragment::FT_Dwarf:
  328. return cast<MCDwarfLineAddrFragment>(F).getContents().size();
  329. case MCFragment::FT_DwarfFrame:
  330. return cast<MCDwarfCallFrameFragment>(F).getContents().size();
  331. case MCFragment::FT_CVInlineLines:
  332. return cast<MCCVInlineLineTableFragment>(F).getContents().size();
  333. case MCFragment::FT_CVDefRange:
  334. return cast<MCCVDefRangeFragment>(F).getContents().size();
  335. case MCFragment::FT_PseudoProbe:
  336. return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
  337. case MCFragment::FT_Dummy:
  338. llvm_unreachable("Should not have been added");
  339. }
  340. llvm_unreachable("invalid fragment kind");
  341. }
  342. void MCAsmLayout::layoutFragment(MCFragment *F) {
  343. MCFragment *Prev = F->getPrevNode();
  344. // We should never try to recompute something which is valid.
  345. assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
  346. // We should never try to compute the fragment layout if its predecessor
  347. // isn't valid.
  348. assert((!Prev || isFragmentValid(Prev)) &&
  349. "Attempt to compute fragment before its predecessor!");
  350. assert(!F->IsBeingLaidOut && "Already being laid out!");
  351. F->IsBeingLaidOut = true;
  352. ++stats::FragmentLayouts;
  353. // Compute fragment offset and size.
  354. if (Prev)
  355. F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
  356. else
  357. F->Offset = 0;
  358. F->IsBeingLaidOut = false;
  359. LastValidFragment[F->getParent()] = F;
  360. // If bundling is enabled and this fragment has instructions in it, it has to
  361. // obey the bundling restrictions. With padding, we'll have:
  362. //
  363. //
  364. // BundlePadding
  365. // |||
  366. // -------------------------------------
  367. // Prev |##########| F |
  368. // -------------------------------------
  369. // ^
  370. // |
  371. // F->Offset
  372. //
  373. // The fragment's offset will point to after the padding, and its computed
  374. // size won't include the padding.
  375. //
  376. // When the -mc-relax-all flag is used, we optimize bundling by writting the
  377. // padding directly into fragments when the instructions are emitted inside
  378. // the streamer. When the fragment is larger than the bundle size, we need to
  379. // ensure that it's bundle aligned. This means that if we end up with
  380. // multiple fragments, we must emit bundle padding between fragments.
  381. //
  382. // ".align N" is an example of a directive that introduces multiple
  383. // fragments. We could add a special case to handle ".align N" by emitting
  384. // within-fragment padding (which would produce less padding when N is less
  385. // than the bundle size), but for now we don't.
  386. //
  387. if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
  388. assert(isa<MCEncodedFragment>(F) &&
  389. "Only MCEncodedFragment implementations have instructions");
  390. MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
  391. uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
  392. if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
  393. report_fatal_error("Fragment can't be larger than a bundle size");
  394. uint64_t RequiredBundlePadding =
  395. computeBundlePadding(Assembler, EF, EF->Offset, FSize);
  396. if (RequiredBundlePadding > UINT8_MAX)
  397. report_fatal_error("Padding cannot exceed 255 bytes");
  398. EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
  399. EF->Offset += RequiredBundlePadding;
  400. }
  401. }
  402. void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
  403. bool New = !Symbol.isRegistered();
  404. if (Created)
  405. *Created = New;
  406. if (New) {
  407. Symbol.setIsRegistered(true);
  408. Symbols.push_back(&Symbol);
  409. }
  410. }
  411. void MCAssembler::writeFragmentPadding(raw_ostream &OS,
  412. const MCEncodedFragment &EF,
  413. uint64_t FSize) const {
  414. assert(getBackendPtr() && "Expected assembler backend");
  415. // Should NOP padding be written out before this fragment?
  416. unsigned BundlePadding = EF.getBundlePadding();
  417. if (BundlePadding > 0) {
  418. assert(isBundlingEnabled() &&
  419. "Writing bundle padding with disabled bundling");
  420. assert(EF.hasInstructions() &&
  421. "Writing bundle padding for a fragment without instructions");
  422. unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
  423. const MCSubtargetInfo *STI = EF.getSubtargetInfo();
  424. if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
  425. // If the padding itself crosses a bundle boundary, it must be emitted
  426. // in 2 pieces, since even nop instructions must not cross boundaries.
  427. // v--------------v <- BundleAlignSize
  428. // v---------v <- BundlePadding
  429. // ----------------------------
  430. // | Prev |####|####| F |
  431. // ----------------------------
  432. // ^-------------------^ <- TotalLength
  433. unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
  434. if (!getBackend().writeNopData(OS, DistanceToBoundary, STI))
  435. report_fatal_error("unable to write NOP sequence of " +
  436. Twine(DistanceToBoundary) + " bytes");
  437. BundlePadding -= DistanceToBoundary;
  438. }
  439. if (!getBackend().writeNopData(OS, BundlePadding, STI))
  440. report_fatal_error("unable to write NOP sequence of " +
  441. Twine(BundlePadding) + " bytes");
  442. }
  443. }
  444. /// Write the fragment \p F to the output file.
  445. static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
  446. const MCAsmLayout &Layout, const MCFragment &F) {
  447. // FIXME: Embed in fragments instead?
  448. uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
  449. support::endianness Endian = Asm.getBackend().Endian;
  450. if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
  451. Asm.writeFragmentPadding(OS, *EF, FragmentSize);
  452. // This variable (and its dummy usage) is to participate in the assert at
  453. // the end of the function.
  454. uint64_t Start = OS.tell();
  455. (void) Start;
  456. ++stats::EmittedFragments;
  457. switch (F.getKind()) {
  458. case MCFragment::FT_Align: {
  459. ++stats::EmittedAlignFragments;
  460. const MCAlignFragment &AF = cast<MCAlignFragment>(F);
  461. assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
  462. uint64_t Count = FragmentSize / AF.getValueSize();
  463. // FIXME: This error shouldn't actually occur (the front end should emit
  464. // multiple .align directives to enforce the semantics it wants), but is
  465. // severe enough that we want to report it. How to handle this?
  466. if (Count * AF.getValueSize() != FragmentSize)
  467. report_fatal_error("undefined .align directive, value size '" +
  468. Twine(AF.getValueSize()) +
  469. "' is not a divisor of padding size '" +
  470. Twine(FragmentSize) + "'");
  471. // See if we are aligning with nops, and if so do that first to try to fill
  472. // the Count bytes. Then if that did not fill any bytes or there are any
  473. // bytes left to fill use the Value and ValueSize to fill the rest.
  474. // If we are aligning with nops, ask that target to emit the right data.
  475. if (AF.hasEmitNops()) {
  476. if (!Asm.getBackend().writeNopData(OS, Count, AF.getSubtargetInfo()))
  477. report_fatal_error("unable to write nop sequence of " +
  478. Twine(Count) + " bytes");
  479. break;
  480. }
  481. // Otherwise, write out in multiples of the value size.
  482. for (uint64_t i = 0; i != Count; ++i) {
  483. switch (AF.getValueSize()) {
  484. default: llvm_unreachable("Invalid size!");
  485. case 1: OS << char(AF.getValue()); break;
  486. case 2:
  487. support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
  488. break;
  489. case 4:
  490. support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
  491. break;
  492. case 8:
  493. support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
  494. break;
  495. }
  496. }
  497. break;
  498. }
  499. case MCFragment::FT_Data:
  500. ++stats::EmittedDataFragments;
  501. OS << cast<MCDataFragment>(F).getContents();
  502. break;
  503. case MCFragment::FT_Relaxable:
  504. ++stats::EmittedRelaxableFragments;
  505. OS << cast<MCRelaxableFragment>(F).getContents();
  506. break;
  507. case MCFragment::FT_CompactEncodedInst:
  508. ++stats::EmittedCompactEncodedInstFragments;
  509. OS << cast<MCCompactEncodedInstFragment>(F).getContents();
  510. break;
  511. case MCFragment::FT_Fill: {
  512. ++stats::EmittedFillFragments;
  513. const MCFillFragment &FF = cast<MCFillFragment>(F);
  514. uint64_t V = FF.getValue();
  515. unsigned VSize = FF.getValueSize();
  516. const unsigned MaxChunkSize = 16;
  517. char Data[MaxChunkSize];
  518. assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
  519. // Duplicate V into Data as byte vector to reduce number of
  520. // writes done. As such, do endian conversion here.
  521. for (unsigned I = 0; I != VSize; ++I) {
  522. unsigned index = Endian == support::little ? I : (VSize - I - 1);
  523. Data[I] = uint8_t(V >> (index * 8));
  524. }
  525. for (unsigned I = VSize; I < MaxChunkSize; ++I)
  526. Data[I] = Data[I - VSize];
  527. // Set to largest multiple of VSize in Data.
  528. const unsigned NumPerChunk = MaxChunkSize / VSize;
  529. // Set ChunkSize to largest multiple of VSize in Data
  530. const unsigned ChunkSize = VSize * NumPerChunk;
  531. // Do copies by chunk.
  532. StringRef Ref(Data, ChunkSize);
  533. for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
  534. OS << Ref;
  535. // do remainder if needed.
  536. unsigned TrailingCount = FragmentSize % ChunkSize;
  537. if (TrailingCount)
  538. OS.write(Data, TrailingCount);
  539. break;
  540. }
  541. case MCFragment::FT_Nops: {
  542. ++stats::EmittedNopsFragments;
  543. const MCNopsFragment &NF = cast<MCNopsFragment>(F);
  544. int64_t NumBytes = NF.getNumBytes();
  545. int64_t ControlledNopLength = NF.getControlledNopLength();
  546. int64_t MaximumNopLength =
  547. Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
  548. assert(NumBytes > 0 && "Expected positive NOPs fragment size");
  549. assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
  550. if (ControlledNopLength > MaximumNopLength) {
  551. Asm.getContext().reportError(NF.getLoc(),
  552. "illegal NOP size " +
  553. std::to_string(ControlledNopLength) +
  554. ". (expected within [0, " +
  555. std::to_string(MaximumNopLength) + "])");
  556. // Clamp the NOP length as reportError does not stop the execution
  557. // immediately.
  558. ControlledNopLength = MaximumNopLength;
  559. }
  560. // Use maximum value if the size of each NOP is not specified
  561. if (!ControlledNopLength)
  562. ControlledNopLength = MaximumNopLength;
  563. while (NumBytes) {
  564. uint64_t NumBytesToEmit =
  565. (uint64_t)std::min(NumBytes, ControlledNopLength);
  566. assert(NumBytesToEmit && "try to emit empty NOP instruction");
  567. if (!Asm.getBackend().writeNopData(OS, NumBytesToEmit,
  568. NF.getSubtargetInfo())) {
  569. report_fatal_error("unable to write nop sequence of the remaining " +
  570. Twine(NumBytesToEmit) + " bytes");
  571. break;
  572. }
  573. NumBytes -= NumBytesToEmit;
  574. }
  575. break;
  576. }
  577. case MCFragment::FT_LEB: {
  578. const MCLEBFragment &LF = cast<MCLEBFragment>(F);
  579. OS << LF.getContents();
  580. break;
  581. }
  582. case MCFragment::FT_BoundaryAlign: {
  583. const MCBoundaryAlignFragment &BF = cast<MCBoundaryAlignFragment>(F);
  584. if (!Asm.getBackend().writeNopData(OS, FragmentSize, BF.getSubtargetInfo()))
  585. report_fatal_error("unable to write nop sequence of " +
  586. Twine(FragmentSize) + " bytes");
  587. break;
  588. }
  589. case MCFragment::FT_SymbolId: {
  590. const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
  591. support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
  592. break;
  593. }
  594. case MCFragment::FT_Org: {
  595. ++stats::EmittedOrgFragments;
  596. const MCOrgFragment &OF = cast<MCOrgFragment>(F);
  597. for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
  598. OS << char(OF.getValue());
  599. break;
  600. }
  601. case MCFragment::FT_Dwarf: {
  602. const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
  603. OS << OF.getContents();
  604. break;
  605. }
  606. case MCFragment::FT_DwarfFrame: {
  607. const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
  608. OS << CF.getContents();
  609. break;
  610. }
  611. case MCFragment::FT_CVInlineLines: {
  612. const auto &OF = cast<MCCVInlineLineTableFragment>(F);
  613. OS << OF.getContents();
  614. break;
  615. }
  616. case MCFragment::FT_CVDefRange: {
  617. const auto &DRF = cast<MCCVDefRangeFragment>(F);
  618. OS << DRF.getContents();
  619. break;
  620. }
  621. case MCFragment::FT_PseudoProbe: {
  622. const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
  623. OS << PF.getContents();
  624. break;
  625. }
  626. case MCFragment::FT_Dummy:
  627. llvm_unreachable("Should not have been added");
  628. }
  629. assert(OS.tell() - Start == FragmentSize &&
  630. "The stream should advance by fragment size");
  631. }
  632. void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
  633. const MCAsmLayout &Layout) const {
  634. assert(getBackendPtr() && "Expected assembler backend");
  635. // Ignore virtual sections.
  636. if (Sec->isVirtualSection()) {
  637. assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
  638. // Check that contents are only things legal inside a virtual section.
  639. for (const MCFragment &F : *Sec) {
  640. switch (F.getKind()) {
  641. default: llvm_unreachable("Invalid fragment in virtual section!");
  642. case MCFragment::FT_Data: {
  643. // Check that we aren't trying to write a non-zero contents (or fixups)
  644. // into a virtual section. This is to support clients which use standard
  645. // directives to fill the contents of virtual sections.
  646. const MCDataFragment &DF = cast<MCDataFragment>(F);
  647. if (DF.fixup_begin() != DF.fixup_end())
  648. getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
  649. " section '" + Sec->getName() +
  650. "' cannot have fixups");
  651. for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
  652. if (DF.getContents()[i]) {
  653. getContext().reportError(SMLoc(),
  654. Sec->getVirtualSectionKind() +
  655. " section '" + Sec->getName() +
  656. "' cannot have non-zero initializers");
  657. break;
  658. }
  659. break;
  660. }
  661. case MCFragment::FT_Align:
  662. // Check that we aren't trying to write a non-zero value into a virtual
  663. // section.
  664. assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
  665. cast<MCAlignFragment>(F).getValue() == 0) &&
  666. "Invalid align in virtual section!");
  667. break;
  668. case MCFragment::FT_Fill:
  669. assert((cast<MCFillFragment>(F).getValue() == 0) &&
  670. "Invalid fill in virtual section!");
  671. break;
  672. case MCFragment::FT_Org:
  673. break;
  674. }
  675. }
  676. return;
  677. }
  678. uint64_t Start = OS.tell();
  679. (void)Start;
  680. for (const MCFragment &F : *Sec)
  681. writeFragment(OS, *this, Layout, F);
  682. assert(getContext().hadError() ||
  683. OS.tell() - Start == Layout.getSectionAddressSize(Sec));
  684. }
  685. std::tuple<MCValue, uint64_t, bool>
  686. MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
  687. const MCFixup &Fixup) {
  688. // Evaluate the fixup.
  689. MCValue Target;
  690. uint64_t FixedValue;
  691. bool WasForced;
  692. bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
  693. WasForced);
  694. if (!IsResolved) {
  695. // The fixup was unresolved, we need a relocation. Inform the object
  696. // writer of the relocation, and give it an opportunity to adjust the
  697. // fixup value if need be.
  698. getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
  699. }
  700. return std::make_tuple(Target, FixedValue, IsResolved);
  701. }
  702. void MCAssembler::layout(MCAsmLayout &Layout) {
  703. assert(getBackendPtr() && "Expected assembler backend");
  704. DEBUG_WITH_TYPE("mc-dump", {
  705. errs() << "assembler backend - pre-layout\n--\n";
  706. dump(); });
  707. // Create dummy fragments and assign section ordinals.
  708. unsigned SectionIndex = 0;
  709. for (MCSection &Sec : *this) {
  710. // Create dummy fragments to eliminate any empty sections, this simplifies
  711. // layout.
  712. if (Sec.getFragmentList().empty())
  713. new MCDataFragment(&Sec);
  714. Sec.setOrdinal(SectionIndex++);
  715. }
  716. // Assign layout order indices to sections and fragments.
  717. for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
  718. MCSection *Sec = Layout.getSectionOrder()[i];
  719. Sec->setLayoutOrder(i);
  720. unsigned FragmentIndex = 0;
  721. for (MCFragment &Frag : *Sec)
  722. Frag.setLayoutOrder(FragmentIndex++);
  723. }
  724. // Layout until everything fits.
  725. while (layoutOnce(Layout)) {
  726. if (getContext().hadError())
  727. return;
  728. // Size of fragments in one section can depend on the size of fragments in
  729. // another. If any fragment has changed size, we have to re-layout (and
  730. // as a result possibly further relax) all.
  731. for (MCSection &Sec : *this)
  732. Layout.invalidateFragmentsFrom(&*Sec.begin());
  733. }
  734. DEBUG_WITH_TYPE("mc-dump", {
  735. errs() << "assembler backend - post-relaxation\n--\n";
  736. dump(); });
  737. // Finalize the layout, including fragment lowering.
  738. finishLayout(Layout);
  739. DEBUG_WITH_TYPE("mc-dump", {
  740. errs() << "assembler backend - final-layout\n--\n";
  741. dump(); });
  742. // Allow the object writer a chance to perform post-layout binding (for
  743. // example, to set the index fields in the symbol data).
  744. getWriter().executePostLayoutBinding(*this, Layout);
  745. // Evaluate and apply the fixups, generating relocation entries as necessary.
  746. for (MCSection &Sec : *this) {
  747. for (MCFragment &Frag : Sec) {
  748. ArrayRef<MCFixup> Fixups;
  749. MutableArrayRef<char> Contents;
  750. const MCSubtargetInfo *STI = nullptr;
  751. // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
  752. switch (Frag.getKind()) {
  753. default:
  754. continue;
  755. case MCFragment::FT_Align: {
  756. MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
  757. // Insert fixup type for code alignment if the target define
  758. // shouldInsertFixupForCodeAlign target hook.
  759. if (Sec.useCodeAlign() && AF.hasEmitNops())
  760. getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
  761. continue;
  762. }
  763. case MCFragment::FT_Data: {
  764. MCDataFragment &DF = cast<MCDataFragment>(Frag);
  765. Fixups = DF.getFixups();
  766. Contents = DF.getContents();
  767. STI = DF.getSubtargetInfo();
  768. assert(!DF.hasInstructions() || STI != nullptr);
  769. break;
  770. }
  771. case MCFragment::FT_Relaxable: {
  772. MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
  773. Fixups = RF.getFixups();
  774. Contents = RF.getContents();
  775. STI = RF.getSubtargetInfo();
  776. assert(!RF.hasInstructions() || STI != nullptr);
  777. break;
  778. }
  779. case MCFragment::FT_CVDefRange: {
  780. MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
  781. Fixups = CF.getFixups();
  782. Contents = CF.getContents();
  783. break;
  784. }
  785. case MCFragment::FT_Dwarf: {
  786. MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
  787. Fixups = DF.getFixups();
  788. Contents = DF.getContents();
  789. break;
  790. }
  791. case MCFragment::FT_DwarfFrame: {
  792. MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
  793. Fixups = DF.getFixups();
  794. Contents = DF.getContents();
  795. break;
  796. }
  797. case MCFragment::FT_PseudoProbe: {
  798. MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
  799. Fixups = PF.getFixups();
  800. Contents = PF.getContents();
  801. break;
  802. }
  803. }
  804. for (const MCFixup &Fixup : Fixups) {
  805. uint64_t FixedValue;
  806. bool IsResolved;
  807. MCValue Target;
  808. std::tie(Target, FixedValue, IsResolved) =
  809. handleFixup(Layout, Frag, Fixup);
  810. getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
  811. IsResolved, STI);
  812. }
  813. }
  814. }
  815. }
  816. void MCAssembler::Finish() {
  817. // Create the layout object.
  818. MCAsmLayout Layout(*this);
  819. layout(Layout);
  820. // Write the object file.
  821. stats::ObjectBytes += getWriter().writeObject(*this, Layout);
  822. }
  823. bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
  824. const MCRelaxableFragment *DF,
  825. const MCAsmLayout &Layout) const {
  826. assert(getBackendPtr() && "Expected assembler backend");
  827. MCValue Target;
  828. uint64_t Value;
  829. bool WasForced;
  830. bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
  831. if (Target.getSymA() &&
  832. Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
  833. Fixup.getKind() == FK_Data_1)
  834. return false;
  835. return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
  836. Layout, WasForced);
  837. }
  838. bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
  839. const MCAsmLayout &Layout) const {
  840. assert(getBackendPtr() && "Expected assembler backend");
  841. // If this inst doesn't ever need relaxation, ignore it. This occurs when we
  842. // are intentionally pushing out inst fragments, or because we relaxed a
  843. // previous instruction to one that doesn't need relaxation.
  844. if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
  845. return false;
  846. for (const MCFixup &Fixup : F->getFixups())
  847. if (fixupNeedsRelaxation(Fixup, F, Layout))
  848. return true;
  849. return false;
  850. }
  851. bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
  852. MCRelaxableFragment &F) {
  853. assert(getEmitterPtr() &&
  854. "Expected CodeEmitter defined for relaxInstruction");
  855. if (!fragmentNeedsRelaxation(&F, Layout))
  856. return false;
  857. ++stats::RelaxedInstructions;
  858. // FIXME-PERF: We could immediately lower out instructions if we can tell
  859. // they are fully resolved, to avoid retesting on later passes.
  860. // Relax the fragment.
  861. MCInst Relaxed = F.getInst();
  862. getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
  863. // Encode the new instruction.
  864. //
  865. // FIXME-PERF: If it matters, we could let the target do this. It can
  866. // probably do so more efficiently in many cases.
  867. SmallVector<MCFixup, 4> Fixups;
  868. SmallString<256> Code;
  869. raw_svector_ostream VecOS(Code);
  870. getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
  871. // Update the fragment.
  872. F.setInst(Relaxed);
  873. F.getContents() = Code;
  874. F.getFixups() = Fixups;
  875. return true;
  876. }
  877. bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
  878. uint64_t OldSize = LF.getContents().size();
  879. int64_t Value;
  880. bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
  881. if (!Abs)
  882. report_fatal_error("sleb128 and uleb128 expressions must be absolute");
  883. SmallString<8> &Data = LF.getContents();
  884. Data.clear();
  885. raw_svector_ostream OSE(Data);
  886. // The compiler can generate EH table assembly that is impossible to assemble
  887. // without either adding padding to an LEB fragment or adding extra padding
  888. // to a later alignment fragment. To accommodate such tables, relaxation can
  889. // only increase an LEB fragment size here, not decrease it. See PR35809.
  890. if (LF.isSigned())
  891. encodeSLEB128(Value, OSE, OldSize);
  892. else
  893. encodeULEB128(Value, OSE, OldSize);
  894. return OldSize != LF.getContents().size();
  895. }
  896. /// Check if the branch crosses the boundary.
  897. ///
  898. /// \param StartAddr start address of the fused/unfused branch.
  899. /// \param Size size of the fused/unfused branch.
  900. /// \param BoundaryAlignment alignment requirement of the branch.
  901. /// \returns true if the branch cross the boundary.
  902. static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size,
  903. Align BoundaryAlignment) {
  904. uint64_t EndAddr = StartAddr + Size;
  905. return (StartAddr >> Log2(BoundaryAlignment)) !=
  906. ((EndAddr - 1) >> Log2(BoundaryAlignment));
  907. }
  908. /// Check if the branch is against the boundary.
  909. ///
  910. /// \param StartAddr start address of the fused/unfused branch.
  911. /// \param Size size of the fused/unfused branch.
  912. /// \param BoundaryAlignment alignment requirement of the branch.
  913. /// \returns true if the branch is against the boundary.
  914. static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size,
  915. Align BoundaryAlignment) {
  916. uint64_t EndAddr = StartAddr + Size;
  917. return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
  918. }
  919. /// Check if the branch needs padding.
  920. ///
  921. /// \param StartAddr start address of the fused/unfused branch.
  922. /// \param Size size of the fused/unfused branch.
  923. /// \param BoundaryAlignment alignment requirement of the branch.
  924. /// \returns true if the branch needs padding.
  925. static bool needPadding(uint64_t StartAddr, uint64_t Size,
  926. Align BoundaryAlignment) {
  927. return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
  928. isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
  929. }
  930. bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
  931. MCBoundaryAlignFragment &BF) {
  932. // BoundaryAlignFragment that doesn't need to align any fragment should not be
  933. // relaxed.
  934. if (!BF.getLastFragment())
  935. return false;
  936. uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
  937. uint64_t AlignedSize = 0;
  938. for (const MCFragment *F = BF.getLastFragment(); F != &BF;
  939. F = F->getPrevNode())
  940. AlignedSize += computeFragmentSize(Layout, *F);
  941. Align BoundaryAlignment = BF.getAlignment();
  942. uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
  943. ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
  944. : 0U;
  945. if (NewSize == BF.getSize())
  946. return false;
  947. BF.setSize(NewSize);
  948. Layout.invalidateFragmentsFrom(&BF);
  949. return true;
  950. }
  951. bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
  952. MCDwarfLineAddrFragment &DF) {
  953. bool WasRelaxed;
  954. if (getBackend().relaxDwarfLineAddr(DF, Layout, WasRelaxed))
  955. return WasRelaxed;
  956. MCContext &Context = Layout.getAssembler().getContext();
  957. uint64_t OldSize = DF.getContents().size();
  958. int64_t AddrDelta;
  959. bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
  960. assert(Abs && "We created a line delta with an invalid expression");
  961. (void)Abs;
  962. int64_t LineDelta;
  963. LineDelta = DF.getLineDelta();
  964. SmallVectorImpl<char> &Data = DF.getContents();
  965. Data.clear();
  966. raw_svector_ostream OSE(Data);
  967. DF.getFixups().clear();
  968. MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
  969. AddrDelta, OSE);
  970. return OldSize != Data.size();
  971. }
  972. bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
  973. MCDwarfCallFrameFragment &DF) {
  974. bool WasRelaxed;
  975. if (getBackend().relaxDwarfCFA(DF, Layout, WasRelaxed))
  976. return WasRelaxed;
  977. MCContext &Context = Layout.getAssembler().getContext();
  978. uint64_t OldSize = DF.getContents().size();
  979. int64_t AddrDelta;
  980. bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
  981. assert(Abs && "We created call frame with an invalid expression");
  982. (void) Abs;
  983. SmallVectorImpl<char> &Data = DF.getContents();
  984. Data.clear();
  985. raw_svector_ostream OSE(Data);
  986. DF.getFixups().clear();
  987. MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
  988. return OldSize != Data.size();
  989. }
  990. bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
  991. MCCVInlineLineTableFragment &F) {
  992. unsigned OldSize = F.getContents().size();
  993. getContext().getCVContext().encodeInlineLineTable(Layout, F);
  994. return OldSize != F.getContents().size();
  995. }
  996. bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
  997. MCCVDefRangeFragment &F) {
  998. unsigned OldSize = F.getContents().size();
  999. getContext().getCVContext().encodeDefRange(Layout, F);
  1000. return OldSize != F.getContents().size();
  1001. }
  1002. bool MCAssembler::relaxPseudoProbeAddr(MCAsmLayout &Layout,
  1003. MCPseudoProbeAddrFragment &PF) {
  1004. uint64_t OldSize = PF.getContents().size();
  1005. int64_t AddrDelta;
  1006. bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
  1007. assert(Abs && "We created a pseudo probe with an invalid expression");
  1008. (void)Abs;
  1009. SmallVectorImpl<char> &Data = PF.getContents();
  1010. Data.clear();
  1011. raw_svector_ostream OSE(Data);
  1012. PF.getFixups().clear();
  1013. // AddrDelta is a signed integer
  1014. encodeSLEB128(AddrDelta, OSE, OldSize);
  1015. return OldSize != Data.size();
  1016. }
  1017. bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
  1018. switch(F.getKind()) {
  1019. default:
  1020. return false;
  1021. case MCFragment::FT_Relaxable:
  1022. assert(!getRelaxAll() &&
  1023. "Did not expect a MCRelaxableFragment in RelaxAll mode");
  1024. return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
  1025. case MCFragment::FT_Dwarf:
  1026. return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
  1027. case MCFragment::FT_DwarfFrame:
  1028. return relaxDwarfCallFrameFragment(Layout,
  1029. cast<MCDwarfCallFrameFragment>(F));
  1030. case MCFragment::FT_LEB:
  1031. return relaxLEB(Layout, cast<MCLEBFragment>(F));
  1032. case MCFragment::FT_BoundaryAlign:
  1033. return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
  1034. case MCFragment::FT_CVInlineLines:
  1035. return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
  1036. case MCFragment::FT_CVDefRange:
  1037. return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
  1038. case MCFragment::FT_PseudoProbe:
  1039. return relaxPseudoProbeAddr(Layout, cast<MCPseudoProbeAddrFragment>(F));
  1040. }
  1041. }
  1042. bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
  1043. // Holds the first fragment which needed relaxing during this layout. It will
  1044. // remain NULL if none were relaxed.
  1045. // When a fragment is relaxed, all the fragments following it should get
  1046. // invalidated because their offset is going to change.
  1047. MCFragment *FirstRelaxedFragment = nullptr;
  1048. // Attempt to relax all the fragments in the section.
  1049. for (MCFragment &Frag : Sec) {
  1050. // Check if this is a fragment that needs relaxation.
  1051. bool RelaxedFrag = relaxFragment(Layout, Frag);
  1052. if (RelaxedFrag && !FirstRelaxedFragment)
  1053. FirstRelaxedFragment = &Frag;
  1054. }
  1055. if (FirstRelaxedFragment) {
  1056. Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
  1057. return true;
  1058. }
  1059. return false;
  1060. }
  1061. bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
  1062. ++stats::RelaxationSteps;
  1063. bool WasRelaxed = false;
  1064. for (MCSection &Sec : *this) {
  1065. while (layoutSectionOnce(Layout, Sec))
  1066. WasRelaxed = true;
  1067. }
  1068. return WasRelaxed;
  1069. }
  1070. void MCAssembler::finishLayout(MCAsmLayout &Layout) {
  1071. assert(getBackendPtr() && "Expected assembler backend");
  1072. // The layout is done. Mark every fragment as valid.
  1073. for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
  1074. MCSection &Section = *Layout.getSectionOrder()[i];
  1075. Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
  1076. computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
  1077. }
  1078. getBackend().finishLayout(*this, Layout);
  1079. }
  1080. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1081. LLVM_DUMP_METHOD void MCAssembler::dump() const{
  1082. raw_ostream &OS = errs();
  1083. OS << "<MCAssembler\n";
  1084. OS << " Sections:[\n ";
  1085. for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
  1086. if (it != begin()) OS << ",\n ";
  1087. it->dump();
  1088. }
  1089. OS << "],\n";
  1090. OS << " Symbols:[";
  1091. for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
  1092. if (it != symbol_begin()) OS << ",\n ";
  1093. OS << "(";
  1094. it->dump();
  1095. OS << ", Index:" << it->getIndex() << ", ";
  1096. OS << ")";
  1097. }
  1098. OS << "]>\n";
  1099. }
  1100. #endif