AArch64AsmBackend.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. //===-- AArch64AsmBackend.cpp - AArch64 Assembler Backend -----------------===//
  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 "MCTargetDesc/AArch64FixupKinds.h"
  9. #include "MCTargetDesc/AArch64MCExpr.h"
  10. #include "MCTargetDesc/AArch64MCTargetDesc.h"
  11. #include "Utils/AArch64BaseInfo.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/BinaryFormat/MachO.h"
  14. #include "llvm/MC/MCAsmBackend.h"
  15. #include "llvm/MC/MCAssembler.h"
  16. #include "llvm/MC/MCContext.h"
  17. #include "llvm/MC/MCDirectives.h"
  18. #include "llvm/MC/MCELFObjectWriter.h"
  19. #include "llvm/MC/MCFixupKindInfo.h"
  20. #include "llvm/MC/MCObjectWriter.h"
  21. #include "llvm/MC/MCRegisterInfo.h"
  22. #include "llvm/MC/MCSectionELF.h"
  23. #include "llvm/MC/MCSectionMachO.h"
  24. #include "llvm/MC/MCTargetOptions.h"
  25. #include "llvm/MC/MCValue.h"
  26. #include "llvm/MC/TargetRegistry.h"
  27. #include "llvm/Support/EndianStream.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. using namespace llvm;
  30. namespace {
  31. class AArch64AsmBackend : public MCAsmBackend {
  32. static const unsigned PCRelFlagVal =
  33. MCFixupKindInfo::FKF_IsAlignedDownTo32Bits | MCFixupKindInfo::FKF_IsPCRel;
  34. protected:
  35. Triple TheTriple;
  36. public:
  37. AArch64AsmBackend(const Target &T, const Triple &TT, bool IsLittleEndian)
  38. : MCAsmBackend(IsLittleEndian ? support::little : support::big),
  39. TheTriple(TT) {}
  40. unsigned getNumFixupKinds() const override {
  41. return AArch64::NumTargetFixupKinds;
  42. }
  43. Optional<MCFixupKind> getFixupKind(StringRef Name) const override;
  44. const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override {
  45. const static MCFixupKindInfo Infos[AArch64::NumTargetFixupKinds] = {
  46. // This table *must* be in the order that the fixup_* kinds are defined
  47. // in AArch64FixupKinds.h.
  48. //
  49. // Name Offset (bits) Size (bits) Flags
  50. {"fixup_aarch64_pcrel_adr_imm21", 0, 32, PCRelFlagVal},
  51. {"fixup_aarch64_pcrel_adrp_imm21", 0, 32, PCRelFlagVal},
  52. {"fixup_aarch64_add_imm12", 10, 12, 0},
  53. {"fixup_aarch64_ldst_imm12_scale1", 10, 12, 0},
  54. {"fixup_aarch64_ldst_imm12_scale2", 10, 12, 0},
  55. {"fixup_aarch64_ldst_imm12_scale4", 10, 12, 0},
  56. {"fixup_aarch64_ldst_imm12_scale8", 10, 12, 0},
  57. {"fixup_aarch64_ldst_imm12_scale16", 10, 12, 0},
  58. {"fixup_aarch64_ldr_pcrel_imm19", 5, 19, PCRelFlagVal},
  59. {"fixup_aarch64_movw", 5, 16, 0},
  60. {"fixup_aarch64_pcrel_branch14", 5, 14, PCRelFlagVal},
  61. {"fixup_aarch64_pcrel_branch19", 5, 19, PCRelFlagVal},
  62. {"fixup_aarch64_pcrel_branch26", 0, 26, PCRelFlagVal},
  63. {"fixup_aarch64_pcrel_call26", 0, 26, PCRelFlagVal}};
  64. // Fixup kinds from .reloc directive are like R_AARCH64_NONE. They do not
  65. // require any extra processing.
  66. if (Kind >= FirstLiteralRelocationKind)
  67. return MCAsmBackend::getFixupKindInfo(FK_NONE);
  68. if (Kind < FirstTargetFixupKind)
  69. return MCAsmBackend::getFixupKindInfo(Kind);
  70. assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
  71. "Invalid kind!");
  72. return Infos[Kind - FirstTargetFixupKind];
  73. }
  74. void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
  75. const MCValue &Target, MutableArrayRef<char> Data,
  76. uint64_t Value, bool IsResolved,
  77. const MCSubtargetInfo *STI) const override;
  78. bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
  79. const MCRelaxableFragment *DF,
  80. const MCAsmLayout &Layout) const override;
  81. void relaxInstruction(MCInst &Inst,
  82. const MCSubtargetInfo &STI) const override;
  83. bool writeNopData(raw_ostream &OS, uint64_t Count,
  84. const MCSubtargetInfo *STI) const override;
  85. unsigned getFixupKindContainereSizeInBytes(unsigned Kind) const;
  86. bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup,
  87. const MCValue &Target) override;
  88. };
  89. } // end anonymous namespace
  90. /// The number of bytes the fixup may change.
  91. static unsigned getFixupKindNumBytes(unsigned Kind) {
  92. switch (Kind) {
  93. default:
  94. llvm_unreachable("Unknown fixup kind!");
  95. case FK_Data_1:
  96. return 1;
  97. case FK_Data_2:
  98. case FK_SecRel_2:
  99. return 2;
  100. case AArch64::fixup_aarch64_movw:
  101. case AArch64::fixup_aarch64_pcrel_branch14:
  102. case AArch64::fixup_aarch64_add_imm12:
  103. case AArch64::fixup_aarch64_ldst_imm12_scale1:
  104. case AArch64::fixup_aarch64_ldst_imm12_scale2:
  105. case AArch64::fixup_aarch64_ldst_imm12_scale4:
  106. case AArch64::fixup_aarch64_ldst_imm12_scale8:
  107. case AArch64::fixup_aarch64_ldst_imm12_scale16:
  108. case AArch64::fixup_aarch64_ldr_pcrel_imm19:
  109. case AArch64::fixup_aarch64_pcrel_branch19:
  110. return 3;
  111. case AArch64::fixup_aarch64_pcrel_adr_imm21:
  112. case AArch64::fixup_aarch64_pcrel_adrp_imm21:
  113. case AArch64::fixup_aarch64_pcrel_branch26:
  114. case AArch64::fixup_aarch64_pcrel_call26:
  115. case FK_Data_4:
  116. case FK_SecRel_4:
  117. return 4;
  118. case FK_Data_8:
  119. return 8;
  120. }
  121. }
  122. static unsigned AdrImmBits(unsigned Value) {
  123. unsigned lo2 = Value & 0x3;
  124. unsigned hi19 = (Value & 0x1ffffc) >> 2;
  125. return (hi19 << 5) | (lo2 << 29);
  126. }
  127. static uint64_t adjustFixupValue(const MCFixup &Fixup, const MCValue &Target,
  128. uint64_t Value, MCContext &Ctx,
  129. const Triple &TheTriple, bool IsResolved) {
  130. int64_t SignedValue = static_cast<int64_t>(Value);
  131. switch (Fixup.getTargetKind()) {
  132. default:
  133. llvm_unreachable("Unknown fixup kind!");
  134. case AArch64::fixup_aarch64_pcrel_adr_imm21:
  135. if (SignedValue > 2097151 || SignedValue < -2097152)
  136. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  137. return AdrImmBits(Value & 0x1fffffULL);
  138. case AArch64::fixup_aarch64_pcrel_adrp_imm21:
  139. assert(!IsResolved);
  140. if (TheTriple.isOSBinFormatCOFF()) {
  141. if (!isInt<21>(SignedValue))
  142. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  143. return AdrImmBits(Value & 0x1fffffULL);
  144. }
  145. return AdrImmBits((Value & 0x1fffff000ULL) >> 12);
  146. case AArch64::fixup_aarch64_ldr_pcrel_imm19:
  147. case AArch64::fixup_aarch64_pcrel_branch19:
  148. // Signed 21-bit immediate
  149. if (SignedValue > 2097151 || SignedValue < -2097152)
  150. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  151. if (Value & 0x3)
  152. Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
  153. // Low two bits are not encoded.
  154. return (Value >> 2) & 0x7ffff;
  155. case AArch64::fixup_aarch64_add_imm12:
  156. case AArch64::fixup_aarch64_ldst_imm12_scale1:
  157. if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
  158. Value &= 0xfff;
  159. // Unsigned 12-bit immediate
  160. if (Value >= 0x1000)
  161. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  162. return Value;
  163. case AArch64::fixup_aarch64_ldst_imm12_scale2:
  164. if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
  165. Value &= 0xfff;
  166. // Unsigned 12-bit immediate which gets multiplied by 2
  167. if (Value >= 0x2000)
  168. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  169. if (Value & 0x1)
  170. Ctx.reportError(Fixup.getLoc(), "fixup must be 2-byte aligned");
  171. return Value >> 1;
  172. case AArch64::fixup_aarch64_ldst_imm12_scale4:
  173. if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
  174. Value &= 0xfff;
  175. // Unsigned 12-bit immediate which gets multiplied by 4
  176. if (Value >= 0x4000)
  177. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  178. if (Value & 0x3)
  179. Ctx.reportError(Fixup.getLoc(), "fixup must be 4-byte aligned");
  180. return Value >> 2;
  181. case AArch64::fixup_aarch64_ldst_imm12_scale8:
  182. if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
  183. Value &= 0xfff;
  184. // Unsigned 12-bit immediate which gets multiplied by 8
  185. if (Value >= 0x8000)
  186. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  187. if (Value & 0x7)
  188. Ctx.reportError(Fixup.getLoc(), "fixup must be 8-byte aligned");
  189. return Value >> 3;
  190. case AArch64::fixup_aarch64_ldst_imm12_scale16:
  191. if (TheTriple.isOSBinFormatCOFF() && !IsResolved)
  192. Value &= 0xfff;
  193. // Unsigned 12-bit immediate which gets multiplied by 16
  194. if (Value >= 0x10000)
  195. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  196. if (Value & 0xf)
  197. Ctx.reportError(Fixup.getLoc(), "fixup must be 16-byte aligned");
  198. return Value >> 4;
  199. case AArch64::fixup_aarch64_movw: {
  200. AArch64MCExpr::VariantKind RefKind =
  201. static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
  202. if (AArch64MCExpr::getSymbolLoc(RefKind) != AArch64MCExpr::VK_ABS &&
  203. AArch64MCExpr::getSymbolLoc(RefKind) != AArch64MCExpr::VK_SABS) {
  204. if (!RefKind) {
  205. // The fixup is an expression
  206. if (SignedValue > 0xFFFF || SignedValue < -0xFFFF)
  207. Ctx.reportError(Fixup.getLoc(),
  208. "fixup value out of range [-0xFFFF, 0xFFFF]");
  209. // Invert the negative immediate because it will feed into a MOVN.
  210. if (SignedValue < 0)
  211. SignedValue = ~SignedValue;
  212. Value = static_cast<uint64_t>(SignedValue);
  213. } else
  214. // VK_GOTTPREL, VK_TPREL, VK_DTPREL are movw fixups, but they can't
  215. // ever be resolved in the assembler.
  216. Ctx.reportError(Fixup.getLoc(),
  217. "relocation for a thread-local variable points to an "
  218. "absolute symbol");
  219. return Value;
  220. }
  221. if (!IsResolved) {
  222. // FIXME: Figure out when this can actually happen, and verify our
  223. // behavior.
  224. Ctx.reportError(Fixup.getLoc(), "unresolved movw fixup not yet "
  225. "implemented");
  226. return Value;
  227. }
  228. if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS) {
  229. switch (AArch64MCExpr::getAddressFrag(RefKind)) {
  230. case AArch64MCExpr::VK_G0:
  231. break;
  232. case AArch64MCExpr::VK_G1:
  233. SignedValue = SignedValue >> 16;
  234. break;
  235. case AArch64MCExpr::VK_G2:
  236. SignedValue = SignedValue >> 32;
  237. break;
  238. case AArch64MCExpr::VK_G3:
  239. SignedValue = SignedValue >> 48;
  240. break;
  241. default:
  242. llvm_unreachable("Variant kind doesn't correspond to fixup");
  243. }
  244. } else {
  245. switch (AArch64MCExpr::getAddressFrag(RefKind)) {
  246. case AArch64MCExpr::VK_G0:
  247. break;
  248. case AArch64MCExpr::VK_G1:
  249. Value = Value >> 16;
  250. break;
  251. case AArch64MCExpr::VK_G2:
  252. Value = Value >> 32;
  253. break;
  254. case AArch64MCExpr::VK_G3:
  255. Value = Value >> 48;
  256. break;
  257. default:
  258. llvm_unreachable("Variant kind doesn't correspond to fixup");
  259. }
  260. }
  261. if (RefKind & AArch64MCExpr::VK_NC) {
  262. Value &= 0xFFFF;
  263. }
  264. else if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS) {
  265. if (SignedValue > 0xFFFF || SignedValue < -0xFFFF)
  266. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  267. // Invert the negative immediate because it will feed into a MOVN.
  268. if (SignedValue < 0)
  269. SignedValue = ~SignedValue;
  270. Value = static_cast<uint64_t>(SignedValue);
  271. }
  272. else if (Value > 0xFFFF) {
  273. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  274. }
  275. return Value;
  276. }
  277. case AArch64::fixup_aarch64_pcrel_branch14:
  278. // Signed 16-bit immediate
  279. if (SignedValue > 32767 || SignedValue < -32768)
  280. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  281. // Low two bits are not encoded (4-byte alignment assumed).
  282. if (Value & 0x3)
  283. Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
  284. return (Value >> 2) & 0x3fff;
  285. case AArch64::fixup_aarch64_pcrel_branch26:
  286. case AArch64::fixup_aarch64_pcrel_call26:
  287. // Signed 28-bit immediate
  288. if (SignedValue > 134217727 || SignedValue < -134217728)
  289. Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
  290. // Low two bits are not encoded (4-byte alignment assumed).
  291. if (Value & 0x3)
  292. Ctx.reportError(Fixup.getLoc(), "fixup not sufficiently aligned");
  293. return (Value >> 2) & 0x3ffffff;
  294. case FK_Data_1:
  295. case FK_Data_2:
  296. case FK_Data_4:
  297. case FK_Data_8:
  298. case FK_SecRel_2:
  299. case FK_SecRel_4:
  300. return Value;
  301. }
  302. }
  303. Optional<MCFixupKind> AArch64AsmBackend::getFixupKind(StringRef Name) const {
  304. if (!TheTriple.isOSBinFormatELF())
  305. return None;
  306. unsigned Type = llvm::StringSwitch<unsigned>(Name)
  307. #define ELF_RELOC(X, Y) .Case(#X, Y)
  308. #include "llvm/BinaryFormat/ELFRelocs/AArch64.def"
  309. #undef ELF_RELOC
  310. .Case("BFD_RELOC_NONE", ELF::R_AARCH64_NONE)
  311. .Case("BFD_RELOC_16", ELF::R_AARCH64_ABS16)
  312. .Case("BFD_RELOC_32", ELF::R_AARCH64_ABS32)
  313. .Case("BFD_RELOC_64", ELF::R_AARCH64_ABS64)
  314. .Default(-1u);
  315. if (Type == -1u)
  316. return None;
  317. return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
  318. }
  319. /// getFixupKindContainereSizeInBytes - The number of bytes of the
  320. /// container involved in big endian or 0 if the item is little endian
  321. unsigned AArch64AsmBackend::getFixupKindContainereSizeInBytes(unsigned Kind) const {
  322. if (Endian == support::little)
  323. return 0;
  324. switch (Kind) {
  325. default:
  326. llvm_unreachable("Unknown fixup kind!");
  327. case FK_Data_1:
  328. return 1;
  329. case FK_Data_2:
  330. return 2;
  331. case FK_Data_4:
  332. return 4;
  333. case FK_Data_8:
  334. return 8;
  335. case AArch64::fixup_aarch64_movw:
  336. case AArch64::fixup_aarch64_pcrel_branch14:
  337. case AArch64::fixup_aarch64_add_imm12:
  338. case AArch64::fixup_aarch64_ldst_imm12_scale1:
  339. case AArch64::fixup_aarch64_ldst_imm12_scale2:
  340. case AArch64::fixup_aarch64_ldst_imm12_scale4:
  341. case AArch64::fixup_aarch64_ldst_imm12_scale8:
  342. case AArch64::fixup_aarch64_ldst_imm12_scale16:
  343. case AArch64::fixup_aarch64_ldr_pcrel_imm19:
  344. case AArch64::fixup_aarch64_pcrel_branch19:
  345. case AArch64::fixup_aarch64_pcrel_adr_imm21:
  346. case AArch64::fixup_aarch64_pcrel_adrp_imm21:
  347. case AArch64::fixup_aarch64_pcrel_branch26:
  348. case AArch64::fixup_aarch64_pcrel_call26:
  349. // Instructions are always little endian
  350. return 0;
  351. }
  352. }
  353. void AArch64AsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
  354. const MCValue &Target,
  355. MutableArrayRef<char> Data, uint64_t Value,
  356. bool IsResolved,
  357. const MCSubtargetInfo *STI) const {
  358. if (!Value)
  359. return; // Doesn't change encoding.
  360. unsigned Kind = Fixup.getKind();
  361. if (Kind >= FirstLiteralRelocationKind)
  362. return;
  363. unsigned NumBytes = getFixupKindNumBytes(Kind);
  364. MCFixupKindInfo Info = getFixupKindInfo(Fixup.getKind());
  365. MCContext &Ctx = Asm.getContext();
  366. int64_t SignedValue = static_cast<int64_t>(Value);
  367. // Apply any target-specific value adjustments.
  368. Value = adjustFixupValue(Fixup, Target, Value, Ctx, TheTriple, IsResolved);
  369. // Shift the value into position.
  370. Value <<= Info.TargetOffset;
  371. unsigned Offset = Fixup.getOffset();
  372. assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
  373. // Used to point to big endian bytes.
  374. unsigned FulleSizeInBytes = getFixupKindContainereSizeInBytes(Fixup.getKind());
  375. // For each byte of the fragment that the fixup touches, mask in the
  376. // bits from the fixup value.
  377. if (FulleSizeInBytes == 0) {
  378. // Handle as little-endian
  379. for (unsigned i = 0; i != NumBytes; ++i) {
  380. Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
  381. }
  382. } else {
  383. // Handle as big-endian
  384. assert((Offset + FulleSizeInBytes) <= Data.size() && "Invalid fixup size!");
  385. assert(NumBytes <= FulleSizeInBytes && "Invalid fixup size!");
  386. for (unsigned i = 0; i != NumBytes; ++i) {
  387. unsigned Idx = FulleSizeInBytes - 1 - i;
  388. Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
  389. }
  390. }
  391. // FIXME: getFixupKindInfo() and getFixupKindNumBytes() could be fixed to
  392. // handle this more cleanly. This may affect the output of -show-mc-encoding.
  393. AArch64MCExpr::VariantKind RefKind =
  394. static_cast<AArch64MCExpr::VariantKind>(Target.getRefKind());
  395. if (AArch64MCExpr::getSymbolLoc(RefKind) == AArch64MCExpr::VK_SABS ||
  396. (!RefKind && Fixup.getTargetKind() == AArch64::fixup_aarch64_movw)) {
  397. // If the immediate is negative, generate MOVN else MOVZ.
  398. // (Bit 30 = 0) ==> MOVN, (Bit 30 = 1) ==> MOVZ.
  399. if (SignedValue < 0)
  400. Data[Offset + 3] &= ~(1 << 6);
  401. else
  402. Data[Offset + 3] |= (1 << 6);
  403. }
  404. }
  405. bool AArch64AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
  406. uint64_t Value,
  407. const MCRelaxableFragment *DF,
  408. const MCAsmLayout &Layout) const {
  409. // FIXME: This isn't correct for AArch64. Just moving the "generic" logic
  410. // into the targets for now.
  411. //
  412. // Relax if the value is too big for a (signed) i8.
  413. return int64_t(Value) != int64_t(int8_t(Value));
  414. }
  415. void AArch64AsmBackend::relaxInstruction(MCInst &Inst,
  416. const MCSubtargetInfo &STI) const {
  417. llvm_unreachable("AArch64AsmBackend::relaxInstruction() unimplemented");
  418. }
  419. bool AArch64AsmBackend::writeNopData(raw_ostream &OS, uint64_t Count,
  420. const MCSubtargetInfo *STI) const {
  421. // If the count is not 4-byte aligned, we must be writing data into the text
  422. // section (otherwise we have unaligned instructions, and thus have far
  423. // bigger problems), so just write zeros instead.
  424. OS.write_zeros(Count % 4);
  425. // We are properly aligned, so write NOPs as requested.
  426. Count /= 4;
  427. for (uint64_t i = 0; i != Count; ++i)
  428. support::endian::write<uint32_t>(OS, 0xd503201f, Endian);
  429. return true;
  430. }
  431. bool AArch64AsmBackend::shouldForceRelocation(const MCAssembler &Asm,
  432. const MCFixup &Fixup,
  433. const MCValue &Target) {
  434. unsigned Kind = Fixup.getKind();
  435. if (Kind >= FirstLiteralRelocationKind)
  436. return true;
  437. // The ADRP instruction adds some multiple of 0x1000 to the current PC &
  438. // ~0xfff. This means that the required offset to reach a symbol can vary by
  439. // up to one step depending on where the ADRP is in memory. For example:
  440. //
  441. // ADRP x0, there
  442. // there:
  443. //
  444. // If the ADRP occurs at address 0xffc then "there" will be at 0x1000 and
  445. // we'll need that as an offset. At any other address "there" will be in the
  446. // same page as the ADRP and the instruction should encode 0x0. Assuming the
  447. // section isn't 0x1000-aligned, we therefore need to delegate this decision
  448. // to the linker -- a relocation!
  449. if (Kind == AArch64::fixup_aarch64_pcrel_adrp_imm21)
  450. return true;
  451. return false;
  452. }
  453. namespace {
  454. namespace CU {
  455. /// Compact unwind encoding values.
  456. enum CompactUnwindEncodings {
  457. /// A "frameless" leaf function, where no non-volatile registers are
  458. /// saved. The return remains in LR throughout the function.
  459. UNWIND_ARM64_MODE_FRAMELESS = 0x02000000,
  460. /// No compact unwind encoding available. Instead the low 23-bits of
  461. /// the compact unwind encoding is the offset of the DWARF FDE in the
  462. /// __eh_frame section. This mode is never used in object files. It is only
  463. /// generated by the linker in final linked images, which have only DWARF info
  464. /// for a function.
  465. UNWIND_ARM64_MODE_DWARF = 0x03000000,
  466. /// This is a standard arm64 prologue where FP/LR are immediately
  467. /// pushed on the stack, then SP is copied to FP. If there are any
  468. /// non-volatile register saved, they are copied into the stack fame in pairs
  469. /// in a contiguous ranger right below the saved FP/LR pair. Any subset of the
  470. /// five X pairs and four D pairs can be saved, but the memory layout must be
  471. /// in register number order.
  472. UNWIND_ARM64_MODE_FRAME = 0x04000000,
  473. /// Frame register pair encodings.
  474. UNWIND_ARM64_FRAME_X19_X20_PAIR = 0x00000001,
  475. UNWIND_ARM64_FRAME_X21_X22_PAIR = 0x00000002,
  476. UNWIND_ARM64_FRAME_X23_X24_PAIR = 0x00000004,
  477. UNWIND_ARM64_FRAME_X25_X26_PAIR = 0x00000008,
  478. UNWIND_ARM64_FRAME_X27_X28_PAIR = 0x00000010,
  479. UNWIND_ARM64_FRAME_D8_D9_PAIR = 0x00000100,
  480. UNWIND_ARM64_FRAME_D10_D11_PAIR = 0x00000200,
  481. UNWIND_ARM64_FRAME_D12_D13_PAIR = 0x00000400,
  482. UNWIND_ARM64_FRAME_D14_D15_PAIR = 0x00000800
  483. };
  484. } // end CU namespace
  485. // FIXME: This should be in a separate file.
  486. class DarwinAArch64AsmBackend : public AArch64AsmBackend {
  487. const MCRegisterInfo &MRI;
  488. /// Encode compact unwind stack adjustment for frameless functions.
  489. /// See UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK in compact_unwind_encoding.h.
  490. /// The stack size always needs to be 16 byte aligned.
  491. uint32_t encodeStackAdjustment(uint32_t StackSize) const {
  492. return (StackSize / 16) << 12;
  493. }
  494. public:
  495. DarwinAArch64AsmBackend(const Target &T, const Triple &TT,
  496. const MCRegisterInfo &MRI)
  497. : AArch64AsmBackend(T, TT, /*IsLittleEndian*/ true), MRI(MRI) {}
  498. std::unique_ptr<MCObjectTargetWriter>
  499. createObjectTargetWriter() const override {
  500. uint32_t CPUType = cantFail(MachO::getCPUType(TheTriple));
  501. uint32_t CPUSubType = cantFail(MachO::getCPUSubType(TheTriple));
  502. return createAArch64MachObjectWriter(CPUType, CPUSubType,
  503. TheTriple.isArch32Bit());
  504. }
  505. /// Generate the compact unwind encoding from the CFI directives.
  506. uint32_t generateCompactUnwindEncoding(
  507. ArrayRef<MCCFIInstruction> Instrs) const override {
  508. if (Instrs.empty())
  509. return CU::UNWIND_ARM64_MODE_FRAMELESS;
  510. bool HasFP = false;
  511. unsigned StackSize = 0;
  512. uint32_t CompactUnwindEncoding = 0;
  513. int CurOffset = 0;
  514. for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
  515. const MCCFIInstruction &Inst = Instrs[i];
  516. switch (Inst.getOperation()) {
  517. default:
  518. // Cannot handle this directive: bail out.
  519. return CU::UNWIND_ARM64_MODE_DWARF;
  520. case MCCFIInstruction::OpDefCfa: {
  521. // Defines a frame pointer.
  522. unsigned XReg =
  523. getXRegFromWReg(*MRI.getLLVMRegNum(Inst.getRegister(), true));
  524. // Other CFA registers than FP are not supported by compact unwind.
  525. // Fallback on DWARF.
  526. // FIXME: When opt-remarks are supported in MC, add a remark to notify
  527. // the user.
  528. if (XReg != AArch64::FP)
  529. return CU::UNWIND_ARM64_MODE_DWARF;
  530. assert(XReg == AArch64::FP && "Invalid frame pointer!");
  531. assert(i + 2 < e && "Insufficient CFI instructions to define a frame!");
  532. const MCCFIInstruction &LRPush = Instrs[++i];
  533. assert(LRPush.getOperation() == MCCFIInstruction::OpOffset &&
  534. "Link register not pushed!");
  535. const MCCFIInstruction &FPPush = Instrs[++i];
  536. assert(FPPush.getOperation() == MCCFIInstruction::OpOffset &&
  537. "Frame pointer not pushed!");
  538. assert(FPPush.getOffset() + 8 == LRPush.getOffset());
  539. CurOffset = FPPush.getOffset();
  540. unsigned LRReg = *MRI.getLLVMRegNum(LRPush.getRegister(), true);
  541. unsigned FPReg = *MRI.getLLVMRegNum(FPPush.getRegister(), true);
  542. LRReg = getXRegFromWReg(LRReg);
  543. FPReg = getXRegFromWReg(FPReg);
  544. assert(LRReg == AArch64::LR && FPReg == AArch64::FP &&
  545. "Pushing invalid registers for frame!");
  546. // Indicate that the function has a frame.
  547. CompactUnwindEncoding |= CU::UNWIND_ARM64_MODE_FRAME;
  548. HasFP = true;
  549. break;
  550. }
  551. case MCCFIInstruction::OpDefCfaOffset: {
  552. assert(StackSize == 0 && "We already have the CFA offset!");
  553. StackSize = std::abs(Inst.getOffset());
  554. break;
  555. }
  556. case MCCFIInstruction::OpOffset: {
  557. // Registers are saved in pairs. We expect there to be two consecutive
  558. // `.cfi_offset' instructions with the appropriate registers specified.
  559. unsigned Reg1 = *MRI.getLLVMRegNum(Inst.getRegister(), true);
  560. if (i + 1 == e)
  561. return CU::UNWIND_ARM64_MODE_DWARF;
  562. if (CurOffset != 0 && Inst.getOffset() != CurOffset - 8)
  563. return CU::UNWIND_ARM64_MODE_DWARF;
  564. CurOffset = Inst.getOffset();
  565. const MCCFIInstruction &Inst2 = Instrs[++i];
  566. if (Inst2.getOperation() != MCCFIInstruction::OpOffset)
  567. return CU::UNWIND_ARM64_MODE_DWARF;
  568. unsigned Reg2 = *MRI.getLLVMRegNum(Inst2.getRegister(), true);
  569. if (Inst2.getOffset() != CurOffset - 8)
  570. return CU::UNWIND_ARM64_MODE_DWARF;
  571. CurOffset = Inst2.getOffset();
  572. // N.B. The encodings must be in register number order, and the X
  573. // registers before the D registers.
  574. // X19/X20 pair = 0x00000001,
  575. // X21/X22 pair = 0x00000002,
  576. // X23/X24 pair = 0x00000004,
  577. // X25/X26 pair = 0x00000008,
  578. // X27/X28 pair = 0x00000010
  579. Reg1 = getXRegFromWReg(Reg1);
  580. Reg2 = getXRegFromWReg(Reg2);
  581. if (Reg1 == AArch64::X19 && Reg2 == AArch64::X20 &&
  582. (CompactUnwindEncoding & 0xF1E) == 0)
  583. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X19_X20_PAIR;
  584. else if (Reg1 == AArch64::X21 && Reg2 == AArch64::X22 &&
  585. (CompactUnwindEncoding & 0xF1C) == 0)
  586. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X21_X22_PAIR;
  587. else if (Reg1 == AArch64::X23 && Reg2 == AArch64::X24 &&
  588. (CompactUnwindEncoding & 0xF18) == 0)
  589. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X23_X24_PAIR;
  590. else if (Reg1 == AArch64::X25 && Reg2 == AArch64::X26 &&
  591. (CompactUnwindEncoding & 0xF10) == 0)
  592. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X25_X26_PAIR;
  593. else if (Reg1 == AArch64::X27 && Reg2 == AArch64::X28 &&
  594. (CompactUnwindEncoding & 0xF00) == 0)
  595. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_X27_X28_PAIR;
  596. else {
  597. Reg1 = getDRegFromBReg(Reg1);
  598. Reg2 = getDRegFromBReg(Reg2);
  599. // D8/D9 pair = 0x00000100,
  600. // D10/D11 pair = 0x00000200,
  601. // D12/D13 pair = 0x00000400,
  602. // D14/D15 pair = 0x00000800
  603. if (Reg1 == AArch64::D8 && Reg2 == AArch64::D9 &&
  604. (CompactUnwindEncoding & 0xE00) == 0)
  605. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D8_D9_PAIR;
  606. else if (Reg1 == AArch64::D10 && Reg2 == AArch64::D11 &&
  607. (CompactUnwindEncoding & 0xC00) == 0)
  608. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D10_D11_PAIR;
  609. else if (Reg1 == AArch64::D12 && Reg2 == AArch64::D13 &&
  610. (CompactUnwindEncoding & 0x800) == 0)
  611. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D12_D13_PAIR;
  612. else if (Reg1 == AArch64::D14 && Reg2 == AArch64::D15)
  613. CompactUnwindEncoding |= CU::UNWIND_ARM64_FRAME_D14_D15_PAIR;
  614. else
  615. // A pair was pushed which we cannot handle.
  616. return CU::UNWIND_ARM64_MODE_DWARF;
  617. }
  618. break;
  619. }
  620. }
  621. }
  622. if (!HasFP) {
  623. // With compact unwind info we can only represent stack adjustments of up
  624. // to 65520 bytes.
  625. if (StackSize > 65520)
  626. return CU::UNWIND_ARM64_MODE_DWARF;
  627. CompactUnwindEncoding |= CU::UNWIND_ARM64_MODE_FRAMELESS;
  628. CompactUnwindEncoding |= encodeStackAdjustment(StackSize);
  629. }
  630. return CompactUnwindEncoding;
  631. }
  632. };
  633. } // end anonymous namespace
  634. namespace {
  635. class ELFAArch64AsmBackend : public AArch64AsmBackend {
  636. public:
  637. uint8_t OSABI;
  638. bool IsILP32;
  639. ELFAArch64AsmBackend(const Target &T, const Triple &TT, uint8_t OSABI,
  640. bool IsLittleEndian, bool IsILP32)
  641. : AArch64AsmBackend(T, TT, IsLittleEndian), OSABI(OSABI),
  642. IsILP32(IsILP32) {}
  643. std::unique_ptr<MCObjectTargetWriter>
  644. createObjectTargetWriter() const override {
  645. return createAArch64ELFObjectWriter(OSABI, IsILP32);
  646. }
  647. };
  648. }
  649. namespace {
  650. class COFFAArch64AsmBackend : public AArch64AsmBackend {
  651. public:
  652. COFFAArch64AsmBackend(const Target &T, const Triple &TheTriple)
  653. : AArch64AsmBackend(T, TheTriple, /*IsLittleEndian*/ true) {}
  654. std::unique_ptr<MCObjectTargetWriter>
  655. createObjectTargetWriter() const override {
  656. return createAArch64WinCOFFObjectWriter();
  657. }
  658. };
  659. }
  660. MCAsmBackend *llvm::createAArch64leAsmBackend(const Target &T,
  661. const MCSubtargetInfo &STI,
  662. const MCRegisterInfo &MRI,
  663. const MCTargetOptions &Options) {
  664. const Triple &TheTriple = STI.getTargetTriple();
  665. if (TheTriple.isOSBinFormatMachO()) {
  666. return new DarwinAArch64AsmBackend(T, TheTriple, MRI);
  667. }
  668. if (TheTriple.isOSBinFormatCOFF())
  669. return new COFFAArch64AsmBackend(T, TheTriple);
  670. assert(TheTriple.isOSBinFormatELF() && "Invalid target");
  671. uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
  672. bool IsILP32 = STI.getTargetTriple().getEnvironment() == Triple::GNUILP32;
  673. return new ELFAArch64AsmBackend(T, TheTriple, OSABI, /*IsLittleEndian=*/true,
  674. IsILP32);
  675. }
  676. MCAsmBackend *llvm::createAArch64beAsmBackend(const Target &T,
  677. const MCSubtargetInfo &STI,
  678. const MCRegisterInfo &MRI,
  679. const MCTargetOptions &Options) {
  680. const Triple &TheTriple = STI.getTargetTriple();
  681. assert(TheTriple.isOSBinFormatELF() &&
  682. "Big endian is only supported for ELF targets!");
  683. uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
  684. bool IsILP32 = STI.getTargetTriple().getEnvironment() == Triple::GNUILP32;
  685. return new ELFAArch64AsmBackend(T, TheTriple, OSABI, /*IsLittleEndian=*/false,
  686. IsILP32);
  687. }