X86MCCodeEmitter.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. //===-- X86MCCodeEmitter.cpp - Convert X86 code to machine code -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the X86MCCodeEmitter class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "MCTargetDesc/X86BaseInfo.h"
  13. #include "MCTargetDesc/X86FixupKinds.h"
  14. #include "MCTargetDesc/X86MCTargetDesc.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/MC/MCCodeEmitter.h"
  17. #include "llvm/MC/MCContext.h"
  18. #include "llvm/MC/MCExpr.h"
  19. #include "llvm/MC/MCFixup.h"
  20. #include "llvm/MC/MCInst.h"
  21. #include "llvm/MC/MCInstrDesc.h"
  22. #include "llvm/MC/MCInstrInfo.h"
  23. #include "llvm/MC/MCRegisterInfo.h"
  24. #include "llvm/MC/MCSubtargetInfo.h"
  25. #include "llvm/MC/MCSymbol.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <cassert>
  29. #include <cstdint>
  30. #include <cstdlib>
  31. using namespace llvm;
  32. #define DEBUG_TYPE "mccodeemitter"
  33. namespace {
  34. class X86MCCodeEmitter : public MCCodeEmitter {
  35. const MCInstrInfo &MCII;
  36. MCContext &Ctx;
  37. public:
  38. X86MCCodeEmitter(const MCInstrInfo &mcii, MCContext &ctx)
  39. : MCII(mcii), Ctx(ctx) {}
  40. X86MCCodeEmitter(const X86MCCodeEmitter &) = delete;
  41. X86MCCodeEmitter &operator=(const X86MCCodeEmitter &) = delete;
  42. ~X86MCCodeEmitter() override = default;
  43. void emitPrefix(const MCInst &MI, raw_ostream &OS,
  44. const MCSubtargetInfo &STI) const override;
  45. void encodeInstruction(const MCInst &MI, raw_ostream &OS,
  46. SmallVectorImpl<MCFixup> &Fixups,
  47. const MCSubtargetInfo &STI) const override;
  48. private:
  49. unsigned getX86RegNum(const MCOperand &MO) const;
  50. unsigned getX86RegEncoding(const MCInst &MI, unsigned OpNum) const;
  51. /// \param MI a single low-level machine instruction.
  52. /// \param OpNum the operand #.
  53. /// \returns true if the OpNumth operand of MI require a bit to be set in
  54. /// REX prefix.
  55. bool isREXExtendedReg(const MCInst &MI, unsigned OpNum) const;
  56. void emitImmediate(const MCOperand &Disp, SMLoc Loc, unsigned ImmSize,
  57. MCFixupKind FixupKind, uint64_t StartByte, raw_ostream &OS,
  58. SmallVectorImpl<MCFixup> &Fixups, int ImmOffset = 0) const;
  59. void emitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
  60. raw_ostream &OS) const;
  61. void emitSIBByte(unsigned SS, unsigned Index, unsigned Base,
  62. raw_ostream &OS) const;
  63. void emitMemModRMByte(const MCInst &MI, unsigned Op, unsigned RegOpcodeField,
  64. uint64_t TSFlags, bool HasREX, uint64_t StartByte,
  65. raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
  66. const MCSubtargetInfo &STI,
  67. bool ForceSIB = false) const;
  68. bool emitPrefixImpl(unsigned &CurOp, const MCInst &MI,
  69. const MCSubtargetInfo &STI, raw_ostream &OS) const;
  70. void emitVEXOpcodePrefix(int MemOperand, const MCInst &MI,
  71. raw_ostream &OS) const;
  72. void emitSegmentOverridePrefix(unsigned SegOperand, const MCInst &MI,
  73. raw_ostream &OS) const;
  74. bool emitOpcodePrefix(int MemOperand, const MCInst &MI,
  75. const MCSubtargetInfo &STI, raw_ostream &OS) const;
  76. bool emitREXPrefix(int MemOperand, const MCInst &MI,
  77. const MCSubtargetInfo &STI, raw_ostream &OS) const;
  78. };
  79. } // end anonymous namespace
  80. static uint8_t modRMByte(unsigned Mod, unsigned RegOpcode, unsigned RM) {
  81. assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
  82. return RM | (RegOpcode << 3) | (Mod << 6);
  83. }
  84. static void emitByte(uint8_t C, raw_ostream &OS) { OS << static_cast<char>(C); }
  85. static void emitConstant(uint64_t Val, unsigned Size, raw_ostream &OS) {
  86. // Output the constant in little endian byte order.
  87. for (unsigned i = 0; i != Size; ++i) {
  88. emitByte(Val & 255, OS);
  89. Val >>= 8;
  90. }
  91. }
  92. /// Determine if this immediate can fit in a disp8 or a compressed disp8 for
  93. /// EVEX instructions. \p will be set to the value to pass to the ImmOffset
  94. /// parameter of emitImmediate.
  95. static bool isDispOrCDisp8(uint64_t TSFlags, int Value, int &ImmOffset) {
  96. bool HasEVEX = (TSFlags & X86II::EncodingMask) == X86II::EVEX;
  97. int CD8_Scale =
  98. (TSFlags & X86II::CD8_Scale_Mask) >> X86II::CD8_Scale_Shift;
  99. if (!HasEVEX || CD8_Scale == 0)
  100. return isInt<8>(Value);
  101. assert(isPowerOf2_32(CD8_Scale) && "Unexpected CD8 scale!");
  102. if (Value & (CD8_Scale - 1)) // Unaligned offset
  103. return false;
  104. int CDisp8 = Value / CD8_Scale;
  105. if (!isInt<8>(CDisp8))
  106. return false;
  107. // ImmOffset will be added to Value in emitImmediate leaving just CDisp8.
  108. ImmOffset = CDisp8 - Value;
  109. return true;
  110. }
  111. /// \returns the appropriate fixup kind to use for an immediate in an
  112. /// instruction with the specified TSFlags.
  113. static MCFixupKind getImmFixupKind(uint64_t TSFlags) {
  114. unsigned Size = X86II::getSizeOfImm(TSFlags);
  115. bool isPCRel = X86II::isImmPCRel(TSFlags);
  116. if (X86II::isImmSigned(TSFlags)) {
  117. switch (Size) {
  118. default:
  119. llvm_unreachable("Unsupported signed fixup size!");
  120. case 4:
  121. return MCFixupKind(X86::reloc_signed_4byte);
  122. }
  123. }
  124. return MCFixup::getKindForSize(Size, isPCRel);
  125. }
  126. /// \param Op operand # of the memory operand.
  127. ///
  128. /// \returns true if the specified instruction has a 16-bit memory operand.
  129. static bool is16BitMemOperand(const MCInst &MI, unsigned Op,
  130. const MCSubtargetInfo &STI) {
  131. const MCOperand &Base = MI.getOperand(Op + X86::AddrBaseReg);
  132. const MCOperand &Index = MI.getOperand(Op + X86::AddrIndexReg);
  133. unsigned BaseReg = Base.getReg();
  134. unsigned IndexReg = Index.getReg();
  135. if (STI.hasFeature(X86::Mode16Bit) && BaseReg == 0 && IndexReg == 0)
  136. return true;
  137. if ((BaseReg != 0 &&
  138. X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) ||
  139. (IndexReg != 0 &&
  140. X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)))
  141. return true;
  142. return false;
  143. }
  144. /// \param Op operand # of the memory operand.
  145. ///
  146. /// \returns true if the specified instruction has a 32-bit memory operand.
  147. static bool is32BitMemOperand(const MCInst &MI, unsigned Op) {
  148. const MCOperand &BaseReg = MI.getOperand(Op + X86::AddrBaseReg);
  149. const MCOperand &IndexReg = MI.getOperand(Op + X86::AddrIndexReg);
  150. if ((BaseReg.getReg() != 0 &&
  151. X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
  152. (IndexReg.getReg() != 0 &&
  153. X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
  154. return true;
  155. if (BaseReg.getReg() == X86::EIP) {
  156. assert(IndexReg.getReg() == 0 && "Invalid eip-based address.");
  157. return true;
  158. }
  159. if (IndexReg.getReg() == X86::EIZ)
  160. return true;
  161. return false;
  162. }
  163. /// \param Op operand # of the memory operand.
  164. ///
  165. /// \returns true if the specified instruction has a 64-bit memory operand.
  166. #ifndef NDEBUG
  167. static bool is64BitMemOperand(const MCInst &MI, unsigned Op) {
  168. const MCOperand &BaseReg = MI.getOperand(Op + X86::AddrBaseReg);
  169. const MCOperand &IndexReg = MI.getOperand(Op + X86::AddrIndexReg);
  170. if ((BaseReg.getReg() != 0 &&
  171. X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg())) ||
  172. (IndexReg.getReg() != 0 &&
  173. X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg())))
  174. return true;
  175. return false;
  176. }
  177. #endif
  178. enum GlobalOffsetTableExprKind { GOT_None, GOT_Normal, GOT_SymDiff };
  179. /// Check if this expression starts with _GLOBAL_OFFSET_TABLE_ and if it is
  180. /// of the form _GLOBAL_OFFSET_TABLE_-symbol. This is needed to support PIC on
  181. /// ELF i386 as _GLOBAL_OFFSET_TABLE_ is magical. We check only simple case that
  182. /// are know to be used: _GLOBAL_OFFSET_TABLE_ by itself or at the start of a
  183. /// binary expression.
  184. static GlobalOffsetTableExprKind
  185. startsWithGlobalOffsetTable(const MCExpr *Expr) {
  186. const MCExpr *RHS = nullptr;
  187. if (Expr->getKind() == MCExpr::Binary) {
  188. const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Expr);
  189. Expr = BE->getLHS();
  190. RHS = BE->getRHS();
  191. }
  192. if (Expr->getKind() != MCExpr::SymbolRef)
  193. return GOT_None;
  194. const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
  195. const MCSymbol &S = Ref->getSymbol();
  196. if (S.getName() != "_GLOBAL_OFFSET_TABLE_")
  197. return GOT_None;
  198. if (RHS && RHS->getKind() == MCExpr::SymbolRef)
  199. return GOT_SymDiff;
  200. return GOT_Normal;
  201. }
  202. static bool hasSecRelSymbolRef(const MCExpr *Expr) {
  203. if (Expr->getKind() == MCExpr::SymbolRef) {
  204. const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr);
  205. return Ref->getKind() == MCSymbolRefExpr::VK_SECREL;
  206. }
  207. return false;
  208. }
  209. static bool isPCRel32Branch(const MCInst &MI, const MCInstrInfo &MCII) {
  210. unsigned Opcode = MI.getOpcode();
  211. const MCInstrDesc &Desc = MCII.get(Opcode);
  212. if ((Opcode != X86::CALL64pcrel32 && Opcode != X86::JMP_4 &&
  213. Opcode != X86::JCC_4) ||
  214. getImmFixupKind(Desc.TSFlags) != FK_PCRel_4)
  215. return false;
  216. unsigned CurOp = X86II::getOperandBias(Desc);
  217. const MCOperand &Op = MI.getOperand(CurOp);
  218. if (!Op.isExpr())
  219. return false;
  220. const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Op.getExpr());
  221. return Ref && Ref->getKind() == MCSymbolRefExpr::VK_None;
  222. }
  223. unsigned X86MCCodeEmitter::getX86RegNum(const MCOperand &MO) const {
  224. return Ctx.getRegisterInfo()->getEncodingValue(MO.getReg()) & 0x7;
  225. }
  226. unsigned X86MCCodeEmitter::getX86RegEncoding(const MCInst &MI,
  227. unsigned OpNum) const {
  228. return Ctx.getRegisterInfo()->getEncodingValue(MI.getOperand(OpNum).getReg());
  229. }
  230. /// \param MI a single low-level machine instruction.
  231. /// \param OpNum the operand #.
  232. /// \returns true if the OpNumth operand of MI require a bit to be set in
  233. /// REX prefix.
  234. bool X86MCCodeEmitter::isREXExtendedReg(const MCInst &MI,
  235. unsigned OpNum) const {
  236. return (getX86RegEncoding(MI, OpNum) >> 3) & 1;
  237. }
  238. void X86MCCodeEmitter::emitImmediate(const MCOperand &DispOp, SMLoc Loc,
  239. unsigned Size, MCFixupKind FixupKind,
  240. uint64_t StartByte, raw_ostream &OS,
  241. SmallVectorImpl<MCFixup> &Fixups,
  242. int ImmOffset) const {
  243. const MCExpr *Expr = nullptr;
  244. if (DispOp.isImm()) {
  245. // If this is a simple integer displacement that doesn't require a
  246. // relocation, emit it now.
  247. if (FixupKind != FK_PCRel_1 && FixupKind != FK_PCRel_2 &&
  248. FixupKind != FK_PCRel_4) {
  249. emitConstant(DispOp.getImm() + ImmOffset, Size, OS);
  250. return;
  251. }
  252. Expr = MCConstantExpr::create(DispOp.getImm(), Ctx);
  253. } else {
  254. Expr = DispOp.getExpr();
  255. }
  256. // If we have an immoffset, add it to the expression.
  257. if ((FixupKind == FK_Data_4 || FixupKind == FK_Data_8 ||
  258. FixupKind == MCFixupKind(X86::reloc_signed_4byte))) {
  259. GlobalOffsetTableExprKind Kind = startsWithGlobalOffsetTable(Expr);
  260. if (Kind != GOT_None) {
  261. assert(ImmOffset == 0);
  262. if (Size == 8) {
  263. FixupKind = MCFixupKind(X86::reloc_global_offset_table8);
  264. } else {
  265. assert(Size == 4);
  266. FixupKind = MCFixupKind(X86::reloc_global_offset_table);
  267. }
  268. if (Kind == GOT_Normal)
  269. ImmOffset = static_cast<int>(OS.tell() - StartByte);
  270. } else if (Expr->getKind() == MCExpr::SymbolRef) {
  271. if (hasSecRelSymbolRef(Expr)) {
  272. FixupKind = MCFixupKind(FK_SecRel_4);
  273. }
  274. } else if (Expr->getKind() == MCExpr::Binary) {
  275. const MCBinaryExpr *Bin = static_cast<const MCBinaryExpr *>(Expr);
  276. if (hasSecRelSymbolRef(Bin->getLHS()) ||
  277. hasSecRelSymbolRef(Bin->getRHS())) {
  278. FixupKind = MCFixupKind(FK_SecRel_4);
  279. }
  280. }
  281. }
  282. // If the fixup is pc-relative, we need to bias the value to be relative to
  283. // the start of the field, not the end of the field.
  284. if (FixupKind == FK_PCRel_4 ||
  285. FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
  286. FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load) ||
  287. FixupKind == MCFixupKind(X86::reloc_riprel_4byte_relax) ||
  288. FixupKind == MCFixupKind(X86::reloc_riprel_4byte_relax_rex) ||
  289. FixupKind == MCFixupKind(X86::reloc_branch_4byte_pcrel)) {
  290. ImmOffset -= 4;
  291. // If this is a pc-relative load off _GLOBAL_OFFSET_TABLE_:
  292. // leaq _GLOBAL_OFFSET_TABLE_(%rip), %r15
  293. // this needs to be a GOTPC32 relocation.
  294. if (startsWithGlobalOffsetTable(Expr) != GOT_None)
  295. FixupKind = MCFixupKind(X86::reloc_global_offset_table);
  296. }
  297. if (FixupKind == FK_PCRel_2)
  298. ImmOffset -= 2;
  299. if (FixupKind == FK_PCRel_1)
  300. ImmOffset -= 1;
  301. if (ImmOffset)
  302. Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(ImmOffset, Ctx),
  303. Ctx);
  304. // Emit a symbolic constant as a fixup and 4 zeros.
  305. Fixups.push_back(MCFixup::create(static_cast<uint32_t>(OS.tell() - StartByte),
  306. Expr, FixupKind, Loc));
  307. emitConstant(0, Size, OS);
  308. }
  309. void X86MCCodeEmitter::emitRegModRMByte(const MCOperand &ModRMReg,
  310. unsigned RegOpcodeFld,
  311. raw_ostream &OS) const {
  312. emitByte(modRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)), OS);
  313. }
  314. void X86MCCodeEmitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base,
  315. raw_ostream &OS) const {
  316. // SIB byte is in the same format as the modRMByte.
  317. emitByte(modRMByte(SS, Index, Base), OS);
  318. }
  319. void X86MCCodeEmitter::emitMemModRMByte(const MCInst &MI, unsigned Op,
  320. unsigned RegOpcodeField,
  321. uint64_t TSFlags, bool HasREX,
  322. uint64_t StartByte, raw_ostream &OS,
  323. SmallVectorImpl<MCFixup> &Fixups,
  324. const MCSubtargetInfo &STI,
  325. bool ForceSIB) const {
  326. const MCOperand &Disp = MI.getOperand(Op + X86::AddrDisp);
  327. const MCOperand &Base = MI.getOperand(Op + X86::AddrBaseReg);
  328. const MCOperand &Scale = MI.getOperand(Op + X86::AddrScaleAmt);
  329. const MCOperand &IndexReg = MI.getOperand(Op + X86::AddrIndexReg);
  330. unsigned BaseReg = Base.getReg();
  331. // Handle %rip relative addressing.
  332. if (BaseReg == X86::RIP ||
  333. BaseReg == X86::EIP) { // [disp32+rIP] in X86-64 mode
  334. assert(STI.hasFeature(X86::Mode64Bit) &&
  335. "Rip-relative addressing requires 64-bit mode");
  336. assert(IndexReg.getReg() == 0 && !ForceSIB &&
  337. "Invalid rip-relative address");
  338. emitByte(modRMByte(0, RegOpcodeField, 5), OS);
  339. unsigned Opcode = MI.getOpcode();
  340. unsigned FixupKind = [&]() {
  341. // Enable relaxed relocation only for a MCSymbolRefExpr. We cannot use a
  342. // relaxed relocation if an offset is present (e.g. x@GOTPCREL+4).
  343. if (!(Disp.isExpr() && isa<MCSymbolRefExpr>(Disp.getExpr())))
  344. return X86::reloc_riprel_4byte;
  345. // Certain loads for GOT references can be relocated against the symbol
  346. // directly if the symbol ends up in the same linkage unit.
  347. switch (Opcode) {
  348. default:
  349. return X86::reloc_riprel_4byte;
  350. case X86::MOV64rm:
  351. // movq loads is a subset of reloc_riprel_4byte_relax_rex. It is a
  352. // special case because COFF and Mach-O don't support ELF's more
  353. // flexible R_X86_64_REX_GOTPCRELX relaxation.
  354. assert(HasREX);
  355. return X86::reloc_riprel_4byte_movq_load;
  356. case X86::ADC32rm:
  357. case X86::ADD32rm:
  358. case X86::AND32rm:
  359. case X86::CMP32rm:
  360. case X86::MOV32rm:
  361. case X86::OR32rm:
  362. case X86::SBB32rm:
  363. case X86::SUB32rm:
  364. case X86::TEST32mr:
  365. case X86::XOR32rm:
  366. case X86::CALL64m:
  367. case X86::JMP64m:
  368. case X86::TAILJMPm64:
  369. case X86::TEST64mr:
  370. case X86::ADC64rm:
  371. case X86::ADD64rm:
  372. case X86::AND64rm:
  373. case X86::CMP64rm:
  374. case X86::OR64rm:
  375. case X86::SBB64rm:
  376. case X86::SUB64rm:
  377. case X86::XOR64rm:
  378. return HasREX ? X86::reloc_riprel_4byte_relax_rex
  379. : X86::reloc_riprel_4byte_relax;
  380. }
  381. }();
  382. // rip-relative addressing is actually relative to the *next* instruction.
  383. // Since an immediate can follow the mod/rm byte for an instruction, this
  384. // means that we need to bias the displacement field of the instruction with
  385. // the size of the immediate field. If we have this case, add it into the
  386. // expression to emit.
  387. // Note: rip-relative addressing using immediate displacement values should
  388. // not be adjusted, assuming it was the user's intent.
  389. int ImmSize = !Disp.isImm() && X86II::hasImm(TSFlags)
  390. ? X86II::getSizeOfImm(TSFlags)
  391. : 0;
  392. emitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(FixupKind), StartByte, OS,
  393. Fixups, -ImmSize);
  394. return;
  395. }
  396. unsigned BaseRegNo = BaseReg ? getX86RegNum(Base) : -1U;
  397. // 16-bit addressing forms of the ModR/M byte have a different encoding for
  398. // the R/M field and are far more limited in which registers can be used.
  399. if (is16BitMemOperand(MI, Op, STI)) {
  400. if (BaseReg) {
  401. // For 32-bit addressing, the row and column values in Table 2-2 are
  402. // basically the same. It's AX/CX/DX/BX/SP/BP/SI/DI in that order, with
  403. // some special cases. And getX86RegNum reflects that numbering.
  404. // For 16-bit addressing it's more fun, as shown in the SDM Vol 2A,
  405. // Table 2-1 "16-Bit Addressing Forms with the ModR/M byte". We can only
  406. // use SI/DI/BP/BX, which have "row" values 4-7 in no particular order,
  407. // while values 0-3 indicate the allowed combinations (base+index) of
  408. // those: 0 for BX+SI, 1 for BX+DI, 2 for BP+SI, 3 for BP+DI.
  409. //
  410. // R16Table[] is a lookup from the normal RegNo, to the row values from
  411. // Table 2-1 for 16-bit addressing modes. Where zero means disallowed.
  412. static const unsigned R16Table[] = {0, 0, 0, 7, 0, 6, 4, 5};
  413. unsigned RMfield = R16Table[BaseRegNo];
  414. assert(RMfield && "invalid 16-bit base register");
  415. if (IndexReg.getReg()) {
  416. unsigned IndexReg16 = R16Table[getX86RegNum(IndexReg)];
  417. assert(IndexReg16 && "invalid 16-bit index register");
  418. // We must have one of SI/DI (4,5), and one of BP/BX (6,7).
  419. assert(((IndexReg16 ^ RMfield) & 2) &&
  420. "invalid 16-bit base/index register combination");
  421. assert(Scale.getImm() == 1 &&
  422. "invalid scale for 16-bit memory reference");
  423. // Allow base/index to appear in either order (although GAS doesn't).
  424. if (IndexReg16 & 2)
  425. RMfield = (RMfield & 1) | ((7 - IndexReg16) << 1);
  426. else
  427. RMfield = (IndexReg16 & 1) | ((7 - RMfield) << 1);
  428. }
  429. if (Disp.isImm() && isInt<8>(Disp.getImm())) {
  430. if (Disp.getImm() == 0 && RMfield != 6) {
  431. // There is no displacement; just the register.
  432. emitByte(modRMByte(0, RegOpcodeField, RMfield), OS);
  433. return;
  434. }
  435. // Use the [REG]+disp8 form, including for [BP] which cannot be encoded.
  436. emitByte(modRMByte(1, RegOpcodeField, RMfield), OS);
  437. emitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, StartByte, OS, Fixups);
  438. return;
  439. }
  440. // This is the [REG]+disp16 case.
  441. emitByte(modRMByte(2, RegOpcodeField, RMfield), OS);
  442. } else {
  443. assert(IndexReg.getReg() == 0 && "Unexpected index register!");
  444. // There is no BaseReg; this is the plain [disp16] case.
  445. emitByte(modRMByte(0, RegOpcodeField, 6), OS);
  446. }
  447. // Emit 16-bit displacement for plain disp16 or [REG]+disp16 cases.
  448. emitImmediate(Disp, MI.getLoc(), 2, FK_Data_2, StartByte, OS, Fixups);
  449. return;
  450. }
  451. // Check for presence of {disp8} or {disp32} pseudo prefixes.
  452. bool UseDisp8 = MI.getFlags() & X86::IP_USE_DISP8;
  453. bool UseDisp32 = MI.getFlags() & X86::IP_USE_DISP32;
  454. // We only allow no displacement if no pseudo prefix is present.
  455. bool AllowNoDisp = !UseDisp8 && !UseDisp32;
  456. // Disp8 is allowed unless the {disp32} prefix is present.
  457. bool AllowDisp8 = !UseDisp32;
  458. // Determine whether a SIB byte is needed.
  459. if (// The SIB byte must be used if there is an index register or the
  460. // encoding requires a SIB byte.
  461. !ForceSIB && IndexReg.getReg() == 0 &&
  462. // The SIB byte must be used if the base is ESP/RSP/R12, all of which
  463. // encode to an R/M value of 4, which indicates that a SIB byte is
  464. // present.
  465. BaseRegNo != N86::ESP &&
  466. // If there is no base register and we're in 64-bit mode, we need a SIB
  467. // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
  468. (!STI.hasFeature(X86::Mode64Bit) || BaseReg != 0)) {
  469. if (BaseReg == 0) { // [disp32] in X86-32 mode
  470. emitByte(modRMByte(0, RegOpcodeField, 5), OS);
  471. emitImmediate(Disp, MI.getLoc(), 4, FK_Data_4, StartByte, OS, Fixups);
  472. return;
  473. }
  474. // If the base is not EBP/ESP/R12/R13 and there is no displacement, use
  475. // simple indirect register encoding, this handles addresses like [EAX].
  476. // The encoding for [EBP] or[R13] with no displacement means [disp32] so we
  477. // handle it by emitting a displacement of 0 later.
  478. if (BaseRegNo != N86::EBP) {
  479. if (Disp.isImm() && Disp.getImm() == 0 && AllowNoDisp) {
  480. emitByte(modRMByte(0, RegOpcodeField, BaseRegNo), OS);
  481. return;
  482. }
  483. // If the displacement is @tlscall, treat it as a zero.
  484. if (Disp.isExpr()) {
  485. auto *Sym = dyn_cast<MCSymbolRefExpr>(Disp.getExpr());
  486. if (Sym && Sym->getKind() == MCSymbolRefExpr::VK_TLSCALL) {
  487. // This is exclusively used by call *a@tlscall(base). The relocation
  488. // (R_386_TLSCALL or R_X86_64_TLSCALL) applies to the beginning.
  489. Fixups.push_back(MCFixup::create(0, Sym, FK_NONE, MI.getLoc()));
  490. emitByte(modRMByte(0, RegOpcodeField, BaseRegNo), OS);
  491. return;
  492. }
  493. }
  494. }
  495. // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
  496. // Including a compressed disp8 for EVEX instructions that support it.
  497. // This also handles the 0 displacement for [EBP] or [R13]. We can't use
  498. // disp8 if the {disp32} pseudo prefix is present.
  499. if (Disp.isImm() && AllowDisp8) {
  500. int ImmOffset = 0;
  501. if (isDispOrCDisp8(TSFlags, Disp.getImm(), ImmOffset)) {
  502. emitByte(modRMByte(1, RegOpcodeField, BaseRegNo), OS);
  503. emitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, StartByte, OS, Fixups,
  504. ImmOffset);
  505. return;
  506. }
  507. }
  508. // Otherwise, emit the most general non-SIB encoding: [REG+disp32].
  509. // Displacement may be 0 for [EBP] or [R13] case if {disp32} pseudo prefix
  510. // prevented using disp8 above.
  511. emitByte(modRMByte(2, RegOpcodeField, BaseRegNo), OS);
  512. unsigned Opcode = MI.getOpcode();
  513. unsigned FixupKind = Opcode == X86::MOV32rm ? X86::reloc_signed_4byte_relax
  514. : X86::reloc_signed_4byte;
  515. emitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(FixupKind), StartByte, OS,
  516. Fixups);
  517. return;
  518. }
  519. // We need a SIB byte, so start by outputting the ModR/M byte first
  520. assert(IndexReg.getReg() != X86::ESP && IndexReg.getReg() != X86::RSP &&
  521. "Cannot use ESP as index reg!");
  522. bool ForceDisp32 = false;
  523. bool ForceDisp8 = false;
  524. int ImmOffset = 0;
  525. if (BaseReg == 0) {
  526. // If there is no base register, we emit the special case SIB byte with
  527. // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
  528. BaseRegNo = 5;
  529. emitByte(modRMByte(0, RegOpcodeField, 4), OS);
  530. ForceDisp32 = true;
  531. } else if (Disp.isImm() && Disp.getImm() == 0 && AllowNoDisp &&
  532. // Base reg can't be EBP/RBP/R13 as that would end up with '5' as
  533. // the base field, but that is the magic [*] nomenclature that
  534. // indicates no base when mod=0. For these cases we'll emit a 0
  535. // displacement instead.
  536. BaseRegNo != N86::EBP) {
  537. // Emit no displacement ModR/M byte
  538. emitByte(modRMByte(0, RegOpcodeField, 4), OS);
  539. } else if (Disp.isImm() && AllowDisp8 &&
  540. isDispOrCDisp8(TSFlags, Disp.getImm(), ImmOffset)) {
  541. // Displacement fits in a byte or matches an EVEX compressed disp8, use
  542. // disp8 encoding. This also handles EBP/R13 base with 0 displacement unless
  543. // {disp32} pseudo prefix was used.
  544. emitByte(modRMByte(1, RegOpcodeField, 4), OS);
  545. ForceDisp8 = true;
  546. } else {
  547. // Otherwise, emit the normal disp32 encoding.
  548. emitByte(modRMByte(2, RegOpcodeField, 4), OS);
  549. ForceDisp32 = true;
  550. }
  551. // Calculate what the SS field value should be...
  552. static const unsigned SSTable[] = {~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3};
  553. unsigned SS = SSTable[Scale.getImm()];
  554. unsigned IndexRegNo = IndexReg.getReg() ? getX86RegNum(IndexReg) : 4;
  555. emitSIBByte(SS, IndexRegNo, BaseRegNo, OS);
  556. // Do we need to output a displacement?
  557. if (ForceDisp8)
  558. emitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, StartByte, OS, Fixups,
  559. ImmOffset);
  560. else if (ForceDisp32)
  561. emitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byte),
  562. StartByte, OS, Fixups);
  563. }
  564. /// Emit all instruction prefixes.
  565. ///
  566. /// \returns true if REX prefix is used, otherwise returns false.
  567. bool X86MCCodeEmitter::emitPrefixImpl(unsigned &CurOp, const MCInst &MI,
  568. const MCSubtargetInfo &STI,
  569. raw_ostream &OS) const {
  570. uint64_t TSFlags = MCII.get(MI.getOpcode()).TSFlags;
  571. // Determine where the memory operand starts, if present.
  572. int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
  573. // Emit segment override opcode prefix as needed.
  574. if (MemoryOperand != -1) {
  575. MemoryOperand += CurOp;
  576. emitSegmentOverridePrefix(MemoryOperand + X86::AddrSegmentReg, MI, OS);
  577. }
  578. // Emit the repeat opcode prefix as needed.
  579. unsigned Flags = MI.getFlags();
  580. if (TSFlags & X86II::REP || Flags & X86::IP_HAS_REPEAT)
  581. emitByte(0xF3, OS);
  582. if (Flags & X86::IP_HAS_REPEAT_NE)
  583. emitByte(0xF2, OS);
  584. // Emit the address size opcode prefix as needed.
  585. bool NeedAddressOverride;
  586. uint64_t AdSize = TSFlags & X86II::AdSizeMask;
  587. if ((STI.hasFeature(X86::Mode16Bit) && AdSize == X86II::AdSize32) ||
  588. (STI.hasFeature(X86::Mode32Bit) && AdSize == X86II::AdSize16) ||
  589. (STI.hasFeature(X86::Mode64Bit) && AdSize == X86II::AdSize32)) {
  590. NeedAddressOverride = true;
  591. } else if (MemoryOperand < 0) {
  592. NeedAddressOverride = false;
  593. } else if (STI.hasFeature(X86::Mode64Bit)) {
  594. assert(!is16BitMemOperand(MI, MemoryOperand, STI));
  595. NeedAddressOverride = is32BitMemOperand(MI, MemoryOperand);
  596. } else if (STI.hasFeature(X86::Mode32Bit)) {
  597. assert(!is64BitMemOperand(MI, MemoryOperand));
  598. NeedAddressOverride = is16BitMemOperand(MI, MemoryOperand, STI);
  599. } else {
  600. assert(STI.hasFeature(X86::Mode16Bit));
  601. assert(!is64BitMemOperand(MI, MemoryOperand));
  602. NeedAddressOverride = !is16BitMemOperand(MI, MemoryOperand, STI);
  603. }
  604. if (NeedAddressOverride)
  605. emitByte(0x67, OS);
  606. // Encoding type for this instruction.
  607. uint64_t Encoding = TSFlags & X86II::EncodingMask;
  608. bool HasREX = false;
  609. if (Encoding)
  610. emitVEXOpcodePrefix(MemoryOperand, MI, OS);
  611. else
  612. HasREX = emitOpcodePrefix(MemoryOperand, MI, STI, OS);
  613. uint64_t Form = TSFlags & X86II::FormMask;
  614. switch (Form) {
  615. default:
  616. break;
  617. case X86II::RawFrmDstSrc: {
  618. unsigned siReg = MI.getOperand(1).getReg();
  619. assert(((siReg == X86::SI && MI.getOperand(0).getReg() == X86::DI) ||
  620. (siReg == X86::ESI && MI.getOperand(0).getReg() == X86::EDI) ||
  621. (siReg == X86::RSI && MI.getOperand(0).getReg() == X86::RDI)) &&
  622. "SI and DI register sizes do not match");
  623. // Emit segment override opcode prefix as needed (not for %ds).
  624. if (MI.getOperand(2).getReg() != X86::DS)
  625. emitSegmentOverridePrefix(2, MI, OS);
  626. // Emit AdSize prefix as needed.
  627. if ((!STI.hasFeature(X86::Mode32Bit) && siReg == X86::ESI) ||
  628. (STI.hasFeature(X86::Mode32Bit) && siReg == X86::SI))
  629. emitByte(0x67, OS);
  630. CurOp += 3; // Consume operands.
  631. break;
  632. }
  633. case X86II::RawFrmSrc: {
  634. unsigned siReg = MI.getOperand(0).getReg();
  635. // Emit segment override opcode prefix as needed (not for %ds).
  636. if (MI.getOperand(1).getReg() != X86::DS)
  637. emitSegmentOverridePrefix(1, MI, OS);
  638. // Emit AdSize prefix as needed.
  639. if ((!STI.hasFeature(X86::Mode32Bit) && siReg == X86::ESI) ||
  640. (STI.hasFeature(X86::Mode32Bit) && siReg == X86::SI))
  641. emitByte(0x67, OS);
  642. CurOp += 2; // Consume operands.
  643. break;
  644. }
  645. case X86II::RawFrmDst: {
  646. unsigned siReg = MI.getOperand(0).getReg();
  647. // Emit AdSize prefix as needed.
  648. if ((!STI.hasFeature(X86::Mode32Bit) && siReg == X86::EDI) ||
  649. (STI.hasFeature(X86::Mode32Bit) && siReg == X86::DI))
  650. emitByte(0x67, OS);
  651. ++CurOp; // Consume operand.
  652. break;
  653. }
  654. case X86II::RawFrmMemOffs: {
  655. // Emit segment override opcode prefix as needed.
  656. emitSegmentOverridePrefix(1, MI, OS);
  657. break;
  658. }
  659. }
  660. return HasREX;
  661. }
  662. /// AVX instructions are encoded using a opcode prefix called VEX.
  663. void X86MCCodeEmitter::emitVEXOpcodePrefix(int MemOperand, const MCInst &MI,
  664. raw_ostream &OS) const {
  665. const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
  666. uint64_t TSFlags = Desc.TSFlags;
  667. assert(!(TSFlags & X86II::LOCK) && "Can't have LOCK VEX.");
  668. uint64_t Encoding = TSFlags & X86II::EncodingMask;
  669. bool HasEVEX_K = TSFlags & X86II::EVEX_K;
  670. bool HasVEX_4V = TSFlags & X86II::VEX_4V;
  671. bool HasEVEX_RC = TSFlags & X86II::EVEX_RC;
  672. // VEX_R: opcode externsion equivalent to REX.R in
  673. // 1's complement (inverted) form
  674. //
  675. // 1: Same as REX_R=0 (must be 1 in 32-bit mode)
  676. // 0: Same as REX_R=1 (64 bit mode only)
  677. //
  678. uint8_t VEX_R = 0x1;
  679. uint8_t EVEX_R2 = 0x1;
  680. // VEX_X: equivalent to REX.X, only used when a
  681. // register is used for index in SIB Byte.
  682. //
  683. // 1: Same as REX.X=0 (must be 1 in 32-bit mode)
  684. // 0: Same as REX.X=1 (64-bit mode only)
  685. uint8_t VEX_X = 0x1;
  686. // VEX_B:
  687. //
  688. // 1: Same as REX_B=0 (ignored in 32-bit mode)
  689. // 0: Same as REX_B=1 (64 bit mode only)
  690. //
  691. uint8_t VEX_B = 0x1;
  692. // VEX_W: opcode specific (use like REX.W, or used for
  693. // opcode extension, or ignored, depending on the opcode byte)
  694. uint8_t VEX_W = (TSFlags & X86II::VEX_W) ? 1 : 0;
  695. // VEX_5M (VEX m-mmmmm field):
  696. //
  697. // 0b00000: Reserved for future use
  698. // 0b00001: implied 0F leading opcode
  699. // 0b00010: implied 0F 38 leading opcode bytes
  700. // 0b00011: implied 0F 3A leading opcode bytes
  701. // 0b00100: Reserved for future use
  702. // 0b00101: VEX MAP5
  703. // 0b00110: VEX MAP6
  704. // 0b00111-0b11111: Reserved for future use
  705. // 0b01000: XOP map select - 08h instructions with imm byte
  706. // 0b01001: XOP map select - 09h instructions with no imm byte
  707. // 0b01010: XOP map select - 0Ah instructions with imm dword
  708. uint8_t VEX_5M;
  709. switch (TSFlags & X86II::OpMapMask) {
  710. default:
  711. llvm_unreachable("Invalid prefix!");
  712. case X86II::TB:
  713. VEX_5M = 0x1;
  714. break; // 0F
  715. case X86II::T8:
  716. VEX_5M = 0x2;
  717. break; // 0F 38
  718. case X86II::TA:
  719. VEX_5M = 0x3;
  720. break; // 0F 3A
  721. case X86II::XOP8:
  722. VEX_5M = 0x8;
  723. break;
  724. case X86II::XOP9:
  725. VEX_5M = 0x9;
  726. break;
  727. case X86II::XOPA:
  728. VEX_5M = 0xA;
  729. break;
  730. case X86II::T_MAP5:
  731. VEX_5M = 0x5;
  732. break;
  733. case X86II::T_MAP6:
  734. VEX_5M = 0x6;
  735. break;
  736. }
  737. // VEX_4V (VEX vvvv field): a register specifier
  738. // (in 1's complement form) or 1111 if unused.
  739. uint8_t VEX_4V = 0xf;
  740. uint8_t EVEX_V2 = 0x1;
  741. // EVEX_L2/VEX_L (Vector Length):
  742. //
  743. // L2 L
  744. // 0 0: scalar or 128-bit vector
  745. // 0 1: 256-bit vector
  746. // 1 0: 512-bit vector
  747. //
  748. uint8_t VEX_L = (TSFlags & X86II::VEX_L) ? 1 : 0;
  749. uint8_t EVEX_L2 = (TSFlags & X86II::EVEX_L2) ? 1 : 0;
  750. // VEX_PP: opcode extension providing equivalent
  751. // functionality of a SIMD prefix
  752. //
  753. // 0b00: None
  754. // 0b01: 66
  755. // 0b10: F3
  756. // 0b11: F2
  757. //
  758. uint8_t VEX_PP = 0;
  759. switch (TSFlags & X86II::OpPrefixMask) {
  760. case X86II::PD:
  761. VEX_PP = 0x1;
  762. break; // 66
  763. case X86II::XS:
  764. VEX_PP = 0x2;
  765. break; // F3
  766. case X86II::XD:
  767. VEX_PP = 0x3;
  768. break; // F2
  769. }
  770. // EVEX_U
  771. uint8_t EVEX_U = 1; // Always '1' so far
  772. // EVEX_z
  773. uint8_t EVEX_z = (HasEVEX_K && (TSFlags & X86II::EVEX_Z)) ? 1 : 0;
  774. // EVEX_b
  775. uint8_t EVEX_b = (TSFlags & X86II::EVEX_B) ? 1 : 0;
  776. // EVEX_rc
  777. uint8_t EVEX_rc = 0;
  778. // EVEX_aaa
  779. uint8_t EVEX_aaa = 0;
  780. bool EncodeRC = false;
  781. // Classify VEX_B, VEX_4V, VEX_R, VEX_X
  782. unsigned NumOps = Desc.getNumOperands();
  783. unsigned CurOp = X86II::getOperandBias(Desc);
  784. switch (TSFlags & X86II::FormMask) {
  785. default:
  786. llvm_unreachable("Unexpected form in emitVEXOpcodePrefix!");
  787. case X86II::MRM_C0:
  788. case X86II::RawFrm:
  789. case X86II::PrefixByte:
  790. break;
  791. case X86II::MRMDestMemFSIB:
  792. case X86II::MRMDestMem: {
  793. // MRMDestMem instructions forms:
  794. // MemAddr, src1(ModR/M)
  795. // MemAddr, src1(VEX_4V), src2(ModR/M)
  796. // MemAddr, src1(ModR/M), imm8
  797. //
  798. unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
  799. VEX_B = ~(BaseRegEnc >> 3) & 1;
  800. unsigned IndexRegEnc =
  801. getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
  802. VEX_X = ~(IndexRegEnc >> 3) & 1;
  803. if (!HasVEX_4V) // Only needed with VSIB which don't use VVVV.
  804. EVEX_V2 = ~(IndexRegEnc >> 4) & 1;
  805. CurOp += X86::AddrNumOperands;
  806. if (HasEVEX_K)
  807. EVEX_aaa = getX86RegEncoding(MI, CurOp++);
  808. if (HasVEX_4V) {
  809. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  810. VEX_4V = ~VRegEnc & 0xf;
  811. EVEX_V2 = ~(VRegEnc >> 4) & 1;
  812. }
  813. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  814. VEX_R = ~(RegEnc >> 3) & 1;
  815. EVEX_R2 = ~(RegEnc >> 4) & 1;
  816. break;
  817. }
  818. case X86II::MRMSrcMemFSIB:
  819. case X86II::MRMSrcMem: {
  820. // MRMSrcMem instructions forms:
  821. // src1(ModR/M), MemAddr
  822. // src1(ModR/M), src2(VEX_4V), MemAddr
  823. // src1(ModR/M), MemAddr, imm8
  824. // src1(ModR/M), MemAddr, src2(Imm[7:4])
  825. //
  826. // FMA4:
  827. // dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(Imm[7:4])
  828. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  829. VEX_R = ~(RegEnc >> 3) & 1;
  830. EVEX_R2 = ~(RegEnc >> 4) & 1;
  831. if (HasEVEX_K)
  832. EVEX_aaa = getX86RegEncoding(MI, CurOp++);
  833. if (HasVEX_4V) {
  834. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  835. VEX_4V = ~VRegEnc & 0xf;
  836. EVEX_V2 = ~(VRegEnc >> 4) & 1;
  837. }
  838. unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
  839. VEX_B = ~(BaseRegEnc >> 3) & 1;
  840. unsigned IndexRegEnc =
  841. getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
  842. VEX_X = ~(IndexRegEnc >> 3) & 1;
  843. if (!HasVEX_4V) // Only needed with VSIB which don't use VVVV.
  844. EVEX_V2 = ~(IndexRegEnc >> 4) & 1;
  845. break;
  846. }
  847. case X86II::MRMSrcMem4VOp3: {
  848. // Instruction format for 4VOp3:
  849. // src1(ModR/M), MemAddr, src3(VEX_4V)
  850. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  851. VEX_R = ~(RegEnc >> 3) & 1;
  852. unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
  853. VEX_B = ~(BaseRegEnc >> 3) & 1;
  854. unsigned IndexRegEnc =
  855. getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
  856. VEX_X = ~(IndexRegEnc >> 3) & 1;
  857. VEX_4V = ~getX86RegEncoding(MI, CurOp + X86::AddrNumOperands) & 0xf;
  858. break;
  859. }
  860. case X86II::MRMSrcMemOp4: {
  861. // dst(ModR/M.reg), src1(VEX_4V), src2(Imm[7:4]), src3(ModR/M),
  862. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  863. VEX_R = ~(RegEnc >> 3) & 1;
  864. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  865. VEX_4V = ~VRegEnc & 0xf;
  866. unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
  867. VEX_B = ~(BaseRegEnc >> 3) & 1;
  868. unsigned IndexRegEnc =
  869. getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
  870. VEX_X = ~(IndexRegEnc >> 3) & 1;
  871. break;
  872. }
  873. case X86II::MRM0m:
  874. case X86II::MRM1m:
  875. case X86II::MRM2m:
  876. case X86II::MRM3m:
  877. case X86II::MRM4m:
  878. case X86II::MRM5m:
  879. case X86II::MRM6m:
  880. case X86II::MRM7m: {
  881. // MRM[0-9]m instructions forms:
  882. // MemAddr
  883. // src1(VEX_4V), MemAddr
  884. if (HasVEX_4V) {
  885. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  886. VEX_4V = ~VRegEnc & 0xf;
  887. EVEX_V2 = ~(VRegEnc >> 4) & 1;
  888. }
  889. if (HasEVEX_K)
  890. EVEX_aaa = getX86RegEncoding(MI, CurOp++);
  891. unsigned BaseRegEnc = getX86RegEncoding(MI, MemOperand + X86::AddrBaseReg);
  892. VEX_B = ~(BaseRegEnc >> 3) & 1;
  893. unsigned IndexRegEnc =
  894. getX86RegEncoding(MI, MemOperand + X86::AddrIndexReg);
  895. VEX_X = ~(IndexRegEnc >> 3) & 1;
  896. if (!HasVEX_4V) // Only needed with VSIB which don't use VVVV.
  897. EVEX_V2 = ~(IndexRegEnc >> 4) & 1;
  898. break;
  899. }
  900. case X86II::MRMSrcReg: {
  901. // MRMSrcReg instructions forms:
  902. // dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(Imm[7:4])
  903. // dst(ModR/M), src1(ModR/M)
  904. // dst(ModR/M), src1(ModR/M), imm8
  905. //
  906. // FMA4:
  907. // dst(ModR/M.reg), src1(VEX_4V), src2(Imm[7:4]), src3(ModR/M),
  908. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  909. VEX_R = ~(RegEnc >> 3) & 1;
  910. EVEX_R2 = ~(RegEnc >> 4) & 1;
  911. if (HasEVEX_K)
  912. EVEX_aaa = getX86RegEncoding(MI, CurOp++);
  913. if (HasVEX_4V) {
  914. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  915. VEX_4V = ~VRegEnc & 0xf;
  916. EVEX_V2 = ~(VRegEnc >> 4) & 1;
  917. }
  918. RegEnc = getX86RegEncoding(MI, CurOp++);
  919. VEX_B = ~(RegEnc >> 3) & 1;
  920. VEX_X = ~(RegEnc >> 4) & 1;
  921. if (EVEX_b) {
  922. if (HasEVEX_RC) {
  923. unsigned RcOperand = NumOps - 1;
  924. assert(RcOperand >= CurOp);
  925. EVEX_rc = MI.getOperand(RcOperand).getImm();
  926. assert(EVEX_rc <= 3 && "Invalid rounding control!");
  927. }
  928. EncodeRC = true;
  929. }
  930. break;
  931. }
  932. case X86II::MRMSrcReg4VOp3: {
  933. // Instruction format for 4VOp3:
  934. // src1(ModR/M), src2(ModR/M), src3(VEX_4V)
  935. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  936. VEX_R = ~(RegEnc >> 3) & 1;
  937. RegEnc = getX86RegEncoding(MI, CurOp++);
  938. VEX_B = ~(RegEnc >> 3) & 1;
  939. VEX_4V = ~getX86RegEncoding(MI, CurOp++) & 0xf;
  940. break;
  941. }
  942. case X86II::MRMSrcRegOp4: {
  943. // dst(ModR/M.reg), src1(VEX_4V), src2(Imm[7:4]), src3(ModR/M),
  944. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  945. VEX_R = ~(RegEnc >> 3) & 1;
  946. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  947. VEX_4V = ~VRegEnc & 0xf;
  948. // Skip second register source (encoded in Imm[7:4])
  949. ++CurOp;
  950. RegEnc = getX86RegEncoding(MI, CurOp++);
  951. VEX_B = ~(RegEnc >> 3) & 1;
  952. VEX_X = ~(RegEnc >> 4) & 1;
  953. break;
  954. }
  955. case X86II::MRMDestReg: {
  956. // MRMDestReg instructions forms:
  957. // dst(ModR/M), src(ModR/M)
  958. // dst(ModR/M), src(ModR/M), imm8
  959. // dst(ModR/M), src1(VEX_4V), src2(ModR/M)
  960. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  961. VEX_B = ~(RegEnc >> 3) & 1;
  962. VEX_X = ~(RegEnc >> 4) & 1;
  963. if (HasEVEX_K)
  964. EVEX_aaa = getX86RegEncoding(MI, CurOp++);
  965. if (HasVEX_4V) {
  966. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  967. VEX_4V = ~VRegEnc & 0xf;
  968. EVEX_V2 = ~(VRegEnc >> 4) & 1;
  969. }
  970. RegEnc = getX86RegEncoding(MI, CurOp++);
  971. VEX_R = ~(RegEnc >> 3) & 1;
  972. EVEX_R2 = ~(RegEnc >> 4) & 1;
  973. if (EVEX_b)
  974. EncodeRC = true;
  975. break;
  976. }
  977. case X86II::MRMr0: {
  978. // MRMr0 instructions forms:
  979. // 11:rrr:000
  980. // dst(ModR/M)
  981. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  982. VEX_R = ~(RegEnc >> 3) & 1;
  983. EVEX_R2 = ~(RegEnc >> 4) & 1;
  984. break;
  985. }
  986. case X86II::MRM0r:
  987. case X86II::MRM1r:
  988. case X86II::MRM2r:
  989. case X86II::MRM3r:
  990. case X86II::MRM4r:
  991. case X86II::MRM5r:
  992. case X86II::MRM6r:
  993. case X86II::MRM7r: {
  994. // MRM0r-MRM7r instructions forms:
  995. // dst(VEX_4V), src(ModR/M), imm8
  996. if (HasVEX_4V) {
  997. unsigned VRegEnc = getX86RegEncoding(MI, CurOp++);
  998. VEX_4V = ~VRegEnc & 0xf;
  999. EVEX_V2 = ~(VRegEnc >> 4) & 1;
  1000. }
  1001. if (HasEVEX_K)
  1002. EVEX_aaa = getX86RegEncoding(MI, CurOp++);
  1003. unsigned RegEnc = getX86RegEncoding(MI, CurOp++);
  1004. VEX_B = ~(RegEnc >> 3) & 1;
  1005. VEX_X = ~(RegEnc >> 4) & 1;
  1006. break;
  1007. }
  1008. }
  1009. if (Encoding == X86II::VEX || Encoding == X86II::XOP) {
  1010. // VEX opcode prefix can have 2 or 3 bytes
  1011. //
  1012. // 3 bytes:
  1013. // +-----+ +--------------+ +-------------------+
  1014. // | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
  1015. // +-----+ +--------------+ +-------------------+
  1016. // 2 bytes:
  1017. // +-----+ +-------------------+
  1018. // | C5h | | R | vvvv | L | pp |
  1019. // +-----+ +-------------------+
  1020. //
  1021. // XOP uses a similar prefix:
  1022. // +-----+ +--------------+ +-------------------+
  1023. // | 8Fh | | RXB | m-mmmm | | W | vvvv | L | pp |
  1024. // +-----+ +--------------+ +-------------------+
  1025. uint8_t LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
  1026. // Can we use the 2 byte VEX prefix?
  1027. if (!(MI.getFlags() & X86::IP_USE_VEX3) && Encoding == X86II::VEX &&
  1028. VEX_B && VEX_X && !VEX_W && (VEX_5M == 1)) {
  1029. emitByte(0xC5, OS);
  1030. emitByte(LastByte | (VEX_R << 7), OS);
  1031. return;
  1032. }
  1033. // 3 byte VEX prefix
  1034. emitByte(Encoding == X86II::XOP ? 0x8F : 0xC4, OS);
  1035. emitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, OS);
  1036. emitByte(LastByte | (VEX_W << 7), OS);
  1037. } else {
  1038. assert(Encoding == X86II::EVEX && "unknown encoding!");
  1039. // EVEX opcode prefix can have 4 bytes
  1040. //
  1041. // +-----+ +--------------+ +-------------------+ +------------------------+
  1042. // | 62h | | RXBR' | 0mmm | | W | vvvv | U | pp | | z | L'L | b | v' | aaa |
  1043. // +-----+ +--------------+ +-------------------+ +------------------------+
  1044. assert((VEX_5M & 0x7) == VEX_5M &&
  1045. "More than 3 significant bits in VEX.m-mmmm fields for EVEX!");
  1046. emitByte(0x62, OS);
  1047. emitByte((VEX_R << 7) | (VEX_X << 6) | (VEX_B << 5) | (EVEX_R2 << 4) |
  1048. VEX_5M,
  1049. OS);
  1050. emitByte((VEX_W << 7) | (VEX_4V << 3) | (EVEX_U << 2) | VEX_PP, OS);
  1051. if (EncodeRC)
  1052. emitByte((EVEX_z << 7) | (EVEX_rc << 5) | (EVEX_b << 4) | (EVEX_V2 << 3) |
  1053. EVEX_aaa,
  1054. OS);
  1055. else
  1056. emitByte((EVEX_z << 7) | (EVEX_L2 << 6) | (VEX_L << 5) | (EVEX_b << 4) |
  1057. (EVEX_V2 << 3) | EVEX_aaa,
  1058. OS);
  1059. }
  1060. }
  1061. /// Emit REX prefix which specifies
  1062. /// 1) 64-bit instructions,
  1063. /// 2) non-default operand size, and
  1064. /// 3) use of X86-64 extended registers.
  1065. ///
  1066. /// \returns true if REX prefix is used, otherwise returns false.
  1067. bool X86MCCodeEmitter::emitREXPrefix(int MemOperand, const MCInst &MI,
  1068. const MCSubtargetInfo &STI,
  1069. raw_ostream &OS) const {
  1070. uint8_t REX = [&, MemOperand]() {
  1071. uint8_t REX = 0;
  1072. bool UsesHighByteReg = false;
  1073. const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
  1074. uint64_t TSFlags = Desc.TSFlags;
  1075. if (TSFlags & X86II::REX_W)
  1076. REX |= 1 << 3; // set REX.W
  1077. if (MI.getNumOperands() == 0)
  1078. return REX;
  1079. unsigned NumOps = MI.getNumOperands();
  1080. unsigned CurOp = X86II::getOperandBias(Desc);
  1081. // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
  1082. for (unsigned i = CurOp; i != NumOps; ++i) {
  1083. const MCOperand &MO = MI.getOperand(i);
  1084. if (MO.isReg()) {
  1085. unsigned Reg = MO.getReg();
  1086. if (Reg == X86::AH || Reg == X86::BH || Reg == X86::CH ||
  1087. Reg == X86::DH)
  1088. UsesHighByteReg = true;
  1089. if (X86II::isX86_64NonExtLowByteReg(Reg))
  1090. // FIXME: The caller of determineREXPrefix slaps this prefix onto
  1091. // anything that returns non-zero.
  1092. REX |= 0x40; // REX fixed encoding prefix
  1093. } else if (MO.isExpr() && STI.getTargetTriple().isX32()) {
  1094. // GOTTPOFF and TLSDESC relocations require a REX prefix to allow
  1095. // linker optimizations: even if the instructions we see may not require
  1096. // any prefix, they may be replaced by instructions that do. This is
  1097. // handled as a special case here so that it also works for hand-written
  1098. // assembly without the user needing to write REX, as with GNU as.
  1099. const auto *Ref = dyn_cast<MCSymbolRefExpr>(MO.getExpr());
  1100. if (Ref && (Ref->getKind() == MCSymbolRefExpr::VK_GOTTPOFF ||
  1101. Ref->getKind() == MCSymbolRefExpr::VK_TLSDESC)) {
  1102. REX |= 0x40; // REX fixed encoding prefix
  1103. }
  1104. }
  1105. }
  1106. switch (TSFlags & X86II::FormMask) {
  1107. case X86II::AddRegFrm:
  1108. REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
  1109. break;
  1110. case X86II::MRMSrcReg:
  1111. case X86II::MRMSrcRegCC:
  1112. REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
  1113. REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
  1114. break;
  1115. case X86II::MRMSrcMem:
  1116. case X86II::MRMSrcMemCC:
  1117. REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
  1118. REX |= isREXExtendedReg(MI, MemOperand + X86::AddrBaseReg) << 0; // REX.B
  1119. REX |= isREXExtendedReg(MI, MemOperand + X86::AddrIndexReg) << 1; // REX.X
  1120. CurOp += X86::AddrNumOperands;
  1121. break;
  1122. case X86II::MRMDestReg:
  1123. REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
  1124. REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
  1125. break;
  1126. case X86II::MRMDestMem:
  1127. REX |= isREXExtendedReg(MI, MemOperand + X86::AddrBaseReg) << 0; // REX.B
  1128. REX |= isREXExtendedReg(MI, MemOperand + X86::AddrIndexReg) << 1; // REX.X
  1129. CurOp += X86::AddrNumOperands;
  1130. REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
  1131. break;
  1132. case X86II::MRMXmCC:
  1133. case X86II::MRMXm:
  1134. case X86II::MRM0m:
  1135. case X86II::MRM1m:
  1136. case X86II::MRM2m:
  1137. case X86II::MRM3m:
  1138. case X86II::MRM4m:
  1139. case X86II::MRM5m:
  1140. case X86II::MRM6m:
  1141. case X86II::MRM7m:
  1142. REX |= isREXExtendedReg(MI, MemOperand + X86::AddrBaseReg) << 0; // REX.B
  1143. REX |= isREXExtendedReg(MI, MemOperand + X86::AddrIndexReg) << 1; // REX.X
  1144. break;
  1145. case X86II::MRMXrCC:
  1146. case X86II::MRMXr:
  1147. case X86II::MRM0r:
  1148. case X86II::MRM1r:
  1149. case X86II::MRM2r:
  1150. case X86II::MRM3r:
  1151. case X86II::MRM4r:
  1152. case X86II::MRM5r:
  1153. case X86II::MRM6r:
  1154. case X86II::MRM7r:
  1155. REX |= isREXExtendedReg(MI, CurOp++) << 0; // REX.B
  1156. break;
  1157. case X86II::MRMr0:
  1158. REX |= isREXExtendedReg(MI, CurOp++) << 2; // REX.R
  1159. break;
  1160. case X86II::MRMDestMemFSIB:
  1161. llvm_unreachable("FSIB format never need REX prefix!");
  1162. }
  1163. if (REX && UsesHighByteReg)
  1164. report_fatal_error(
  1165. "Cannot encode high byte register in REX-prefixed instruction");
  1166. return REX;
  1167. }();
  1168. if (!REX)
  1169. return false;
  1170. emitByte(0x40 | REX, OS);
  1171. return true;
  1172. }
  1173. /// Emit segment override opcode prefix as needed.
  1174. void X86MCCodeEmitter::emitSegmentOverridePrefix(unsigned SegOperand,
  1175. const MCInst &MI,
  1176. raw_ostream &OS) const {
  1177. // Check for explicit segment override on memory operand.
  1178. if (unsigned Reg = MI.getOperand(SegOperand).getReg())
  1179. emitByte(X86::getSegmentOverridePrefixForReg(Reg), OS);
  1180. }
  1181. /// Emit all instruction prefixes prior to the opcode.
  1182. ///
  1183. /// \param MemOperand the operand # of the start of a memory operand if present.
  1184. /// If not present, it is -1.
  1185. ///
  1186. /// \returns true if REX prefix is used, otherwise returns false.
  1187. bool X86MCCodeEmitter::emitOpcodePrefix(int MemOperand, const MCInst &MI,
  1188. const MCSubtargetInfo &STI,
  1189. raw_ostream &OS) const {
  1190. const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
  1191. uint64_t TSFlags = Desc.TSFlags;
  1192. // Emit the operand size opcode prefix as needed.
  1193. if ((TSFlags & X86II::OpSizeMask) ==
  1194. (STI.hasFeature(X86::Mode16Bit) ? X86II::OpSize32 : X86II::OpSize16))
  1195. emitByte(0x66, OS);
  1196. // Emit the LOCK opcode prefix.
  1197. if (TSFlags & X86II::LOCK || MI.getFlags() & X86::IP_HAS_LOCK)
  1198. emitByte(0xF0, OS);
  1199. // Emit the NOTRACK opcode prefix.
  1200. if (TSFlags & X86II::NOTRACK || MI.getFlags() & X86::IP_HAS_NOTRACK)
  1201. emitByte(0x3E, OS);
  1202. switch (TSFlags & X86II::OpPrefixMask) {
  1203. case X86II::PD: // 66
  1204. emitByte(0x66, OS);
  1205. break;
  1206. case X86II::XS: // F3
  1207. emitByte(0xF3, OS);
  1208. break;
  1209. case X86II::XD: // F2
  1210. emitByte(0xF2, OS);
  1211. break;
  1212. }
  1213. // Handle REX prefix.
  1214. assert((STI.hasFeature(X86::Mode64Bit) || !(TSFlags & X86II::REX_W)) &&
  1215. "REX.W requires 64bit mode.");
  1216. bool HasREX = STI.hasFeature(X86::Mode64Bit)
  1217. ? emitREXPrefix(MemOperand, MI, STI, OS)
  1218. : false;
  1219. // 0x0F escape code must be emitted just before the opcode.
  1220. switch (TSFlags & X86II::OpMapMask) {
  1221. case X86II::TB: // Two-byte opcode map
  1222. case X86II::T8: // 0F 38
  1223. case X86II::TA: // 0F 3A
  1224. case X86II::ThreeDNow: // 0F 0F, second 0F emitted by caller.
  1225. emitByte(0x0F, OS);
  1226. break;
  1227. }
  1228. switch (TSFlags & X86II::OpMapMask) {
  1229. case X86II::T8: // 0F 38
  1230. emitByte(0x38, OS);
  1231. break;
  1232. case X86II::TA: // 0F 3A
  1233. emitByte(0x3A, OS);
  1234. break;
  1235. }
  1236. return HasREX;
  1237. }
  1238. void X86MCCodeEmitter::emitPrefix(const MCInst &MI, raw_ostream &OS,
  1239. const MCSubtargetInfo &STI) const {
  1240. unsigned Opcode = MI.getOpcode();
  1241. const MCInstrDesc &Desc = MCII.get(Opcode);
  1242. uint64_t TSFlags = Desc.TSFlags;
  1243. // Pseudo instructions don't get encoded.
  1244. if (X86II::isPseudo(TSFlags))
  1245. return;
  1246. unsigned CurOp = X86II::getOperandBias(Desc);
  1247. emitPrefixImpl(CurOp, MI, STI, OS);
  1248. }
  1249. void X86MCCodeEmitter::encodeInstruction(const MCInst &MI, raw_ostream &OS,
  1250. SmallVectorImpl<MCFixup> &Fixups,
  1251. const MCSubtargetInfo &STI) const {
  1252. unsigned Opcode = MI.getOpcode();
  1253. const MCInstrDesc &Desc = MCII.get(Opcode);
  1254. uint64_t TSFlags = Desc.TSFlags;
  1255. // Pseudo instructions don't get encoded.
  1256. if (X86II::isPseudo(TSFlags))
  1257. return;
  1258. unsigned NumOps = Desc.getNumOperands();
  1259. unsigned CurOp = X86II::getOperandBias(Desc);
  1260. uint64_t StartByte = OS.tell();
  1261. bool HasREX = emitPrefixImpl(CurOp, MI, STI, OS);
  1262. // It uses the VEX.VVVV field?
  1263. bool HasVEX_4V = TSFlags & X86II::VEX_4V;
  1264. bool HasVEX_I8Reg = (TSFlags & X86II::ImmMask) == X86II::Imm8Reg;
  1265. // It uses the EVEX.aaa field?
  1266. bool HasEVEX_K = TSFlags & X86II::EVEX_K;
  1267. bool HasEVEX_RC = TSFlags & X86II::EVEX_RC;
  1268. // Used if a register is encoded in 7:4 of immediate.
  1269. unsigned I8RegNum = 0;
  1270. uint8_t BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
  1271. if ((TSFlags & X86II::OpMapMask) == X86II::ThreeDNow)
  1272. BaseOpcode = 0x0F; // Weird 3DNow! encoding.
  1273. unsigned OpcodeOffset = 0;
  1274. uint64_t Form = TSFlags & X86II::FormMask;
  1275. switch (Form) {
  1276. default:
  1277. errs() << "FORM: " << Form << "\n";
  1278. llvm_unreachable("Unknown FormMask value in X86MCCodeEmitter!");
  1279. case X86II::Pseudo:
  1280. llvm_unreachable("Pseudo instruction shouldn't be emitted");
  1281. case X86II::RawFrmDstSrc:
  1282. case X86II::RawFrmSrc:
  1283. case X86II::RawFrmDst:
  1284. case X86II::PrefixByte:
  1285. emitByte(BaseOpcode, OS);
  1286. break;
  1287. case X86II::AddCCFrm: {
  1288. // This will be added to the opcode in the fallthrough.
  1289. OpcodeOffset = MI.getOperand(NumOps - 1).getImm();
  1290. assert(OpcodeOffset < 16 && "Unexpected opcode offset!");
  1291. --NumOps; // Drop the operand from the end.
  1292. LLVM_FALLTHROUGH;
  1293. case X86II::RawFrm:
  1294. emitByte(BaseOpcode + OpcodeOffset, OS);
  1295. if (!STI.hasFeature(X86::Mode64Bit) || !isPCRel32Branch(MI, MCII))
  1296. break;
  1297. const MCOperand &Op = MI.getOperand(CurOp++);
  1298. emitImmediate(Op, MI.getLoc(), X86II::getSizeOfImm(TSFlags),
  1299. MCFixupKind(X86::reloc_branch_4byte_pcrel), StartByte, OS,
  1300. Fixups);
  1301. break;
  1302. }
  1303. case X86II::RawFrmMemOffs:
  1304. emitByte(BaseOpcode, OS);
  1305. emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
  1306. X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
  1307. StartByte, OS, Fixups);
  1308. ++CurOp; // skip segment operand
  1309. break;
  1310. case X86II::RawFrmImm8:
  1311. emitByte(BaseOpcode, OS);
  1312. emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
  1313. X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
  1314. StartByte, OS, Fixups);
  1315. emitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 1, FK_Data_1, StartByte,
  1316. OS, Fixups);
  1317. break;
  1318. case X86II::RawFrmImm16:
  1319. emitByte(BaseOpcode, OS);
  1320. emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
  1321. X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
  1322. StartByte, OS, Fixups);
  1323. emitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 2, FK_Data_2, StartByte,
  1324. OS, Fixups);
  1325. break;
  1326. case X86II::AddRegFrm:
  1327. emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++)), OS);
  1328. break;
  1329. case X86II::MRMDestReg: {
  1330. emitByte(BaseOpcode, OS);
  1331. unsigned SrcRegNum = CurOp + 1;
  1332. if (HasEVEX_K) // Skip writemask
  1333. ++SrcRegNum;
  1334. if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
  1335. ++SrcRegNum;
  1336. emitRegModRMByte(MI.getOperand(CurOp),
  1337. getX86RegNum(MI.getOperand(SrcRegNum)), OS);
  1338. CurOp = SrcRegNum + 1;
  1339. break;
  1340. }
  1341. case X86II::MRMDestMemFSIB:
  1342. case X86II::MRMDestMem: {
  1343. emitByte(BaseOpcode, OS);
  1344. unsigned SrcRegNum = CurOp + X86::AddrNumOperands;
  1345. if (HasEVEX_K) // Skip writemask
  1346. ++SrcRegNum;
  1347. if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
  1348. ++SrcRegNum;
  1349. bool ForceSIB = (Form == X86II::MRMDestMemFSIB);
  1350. emitMemModRMByte(MI, CurOp, getX86RegNum(MI.getOperand(SrcRegNum)), TSFlags,
  1351. HasREX, StartByte, OS, Fixups, STI, ForceSIB);
  1352. CurOp = SrcRegNum + 1;
  1353. break;
  1354. }
  1355. case X86II::MRMSrcReg: {
  1356. emitByte(BaseOpcode, OS);
  1357. unsigned SrcRegNum = CurOp + 1;
  1358. if (HasEVEX_K) // Skip writemask
  1359. ++SrcRegNum;
  1360. if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
  1361. ++SrcRegNum;
  1362. emitRegModRMByte(MI.getOperand(SrcRegNum),
  1363. getX86RegNum(MI.getOperand(CurOp)), OS);
  1364. CurOp = SrcRegNum + 1;
  1365. if (HasVEX_I8Reg)
  1366. I8RegNum = getX86RegEncoding(MI, CurOp++);
  1367. // do not count the rounding control operand
  1368. if (HasEVEX_RC)
  1369. --NumOps;
  1370. break;
  1371. }
  1372. case X86II::MRMSrcReg4VOp3: {
  1373. emitByte(BaseOpcode, OS);
  1374. unsigned SrcRegNum = CurOp + 1;
  1375. emitRegModRMByte(MI.getOperand(SrcRegNum),
  1376. getX86RegNum(MI.getOperand(CurOp)), OS);
  1377. CurOp = SrcRegNum + 1;
  1378. ++CurOp; // Encoded in VEX.VVVV
  1379. break;
  1380. }
  1381. case X86II::MRMSrcRegOp4: {
  1382. emitByte(BaseOpcode, OS);
  1383. unsigned SrcRegNum = CurOp + 1;
  1384. // Skip 1st src (which is encoded in VEX_VVVV)
  1385. ++SrcRegNum;
  1386. // Capture 2nd src (which is encoded in Imm[7:4])
  1387. assert(HasVEX_I8Reg && "MRMSrcRegOp4 should imply VEX_I8Reg");
  1388. I8RegNum = getX86RegEncoding(MI, SrcRegNum++);
  1389. emitRegModRMByte(MI.getOperand(SrcRegNum),
  1390. getX86RegNum(MI.getOperand(CurOp)), OS);
  1391. CurOp = SrcRegNum + 1;
  1392. break;
  1393. }
  1394. case X86II::MRMSrcRegCC: {
  1395. unsigned FirstOp = CurOp++;
  1396. unsigned SecondOp = CurOp++;
  1397. unsigned CC = MI.getOperand(CurOp++).getImm();
  1398. emitByte(BaseOpcode + CC, OS);
  1399. emitRegModRMByte(MI.getOperand(SecondOp),
  1400. getX86RegNum(MI.getOperand(FirstOp)), OS);
  1401. break;
  1402. }
  1403. case X86II::MRMSrcMemFSIB:
  1404. case X86II::MRMSrcMem: {
  1405. unsigned FirstMemOp = CurOp + 1;
  1406. if (HasEVEX_K) // Skip writemask
  1407. ++FirstMemOp;
  1408. if (HasVEX_4V)
  1409. ++FirstMemOp; // Skip the register source (which is encoded in VEX_VVVV).
  1410. emitByte(BaseOpcode, OS);
  1411. bool ForceSIB = (Form == X86II::MRMSrcMemFSIB);
  1412. emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(CurOp)),
  1413. TSFlags, HasREX, StartByte, OS, Fixups, STI, ForceSIB);
  1414. CurOp = FirstMemOp + X86::AddrNumOperands;
  1415. if (HasVEX_I8Reg)
  1416. I8RegNum = getX86RegEncoding(MI, CurOp++);
  1417. break;
  1418. }
  1419. case X86II::MRMSrcMem4VOp3: {
  1420. unsigned FirstMemOp = CurOp + 1;
  1421. emitByte(BaseOpcode, OS);
  1422. emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(CurOp)),
  1423. TSFlags, HasREX, StartByte, OS, Fixups, STI);
  1424. CurOp = FirstMemOp + X86::AddrNumOperands;
  1425. ++CurOp; // Encoded in VEX.VVVV.
  1426. break;
  1427. }
  1428. case X86II::MRMSrcMemOp4: {
  1429. unsigned FirstMemOp = CurOp + 1;
  1430. ++FirstMemOp; // Skip the register source (which is encoded in VEX_VVVV).
  1431. // Capture second register source (encoded in Imm[7:4])
  1432. assert(HasVEX_I8Reg && "MRMSrcRegOp4 should imply VEX_I8Reg");
  1433. I8RegNum = getX86RegEncoding(MI, FirstMemOp++);
  1434. emitByte(BaseOpcode, OS);
  1435. emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(CurOp)),
  1436. TSFlags, HasREX, StartByte, OS, Fixups, STI);
  1437. CurOp = FirstMemOp + X86::AddrNumOperands;
  1438. break;
  1439. }
  1440. case X86II::MRMSrcMemCC: {
  1441. unsigned RegOp = CurOp++;
  1442. unsigned FirstMemOp = CurOp;
  1443. CurOp = FirstMemOp + X86::AddrNumOperands;
  1444. unsigned CC = MI.getOperand(CurOp++).getImm();
  1445. emitByte(BaseOpcode + CC, OS);
  1446. emitMemModRMByte(MI, FirstMemOp, getX86RegNum(MI.getOperand(RegOp)),
  1447. TSFlags, HasREX, StartByte, OS, Fixups, STI);
  1448. break;
  1449. }
  1450. case X86II::MRMXrCC: {
  1451. unsigned RegOp = CurOp++;
  1452. unsigned CC = MI.getOperand(CurOp++).getImm();
  1453. emitByte(BaseOpcode + CC, OS);
  1454. emitRegModRMByte(MI.getOperand(RegOp), 0, OS);
  1455. break;
  1456. }
  1457. case X86II::MRMXr:
  1458. case X86II::MRM0r:
  1459. case X86II::MRM1r:
  1460. case X86II::MRM2r:
  1461. case X86II::MRM3r:
  1462. case X86II::MRM4r:
  1463. case X86II::MRM5r:
  1464. case X86II::MRM6r:
  1465. case X86II::MRM7r:
  1466. if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
  1467. ++CurOp;
  1468. if (HasEVEX_K) // Skip writemask
  1469. ++CurOp;
  1470. emitByte(BaseOpcode, OS);
  1471. emitRegModRMByte(MI.getOperand(CurOp++),
  1472. (Form == X86II::MRMXr) ? 0 : Form - X86II::MRM0r, OS);
  1473. break;
  1474. case X86II::MRMr0:
  1475. emitByte(BaseOpcode, OS);
  1476. emitByte(modRMByte(3, getX86RegNum(MI.getOperand(CurOp++)),0), OS);
  1477. break;
  1478. case X86II::MRMXmCC: {
  1479. unsigned FirstMemOp = CurOp;
  1480. CurOp = FirstMemOp + X86::AddrNumOperands;
  1481. unsigned CC = MI.getOperand(CurOp++).getImm();
  1482. emitByte(BaseOpcode + CC, OS);
  1483. emitMemModRMByte(MI, FirstMemOp, 0, TSFlags, HasREX, StartByte, OS, Fixups,
  1484. STI);
  1485. break;
  1486. }
  1487. case X86II::MRMXm:
  1488. case X86II::MRM0m:
  1489. case X86II::MRM1m:
  1490. case X86II::MRM2m:
  1491. case X86II::MRM3m:
  1492. case X86II::MRM4m:
  1493. case X86II::MRM5m:
  1494. case X86II::MRM6m:
  1495. case X86II::MRM7m:
  1496. if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
  1497. ++CurOp;
  1498. if (HasEVEX_K) // Skip writemask
  1499. ++CurOp;
  1500. emitByte(BaseOpcode, OS);
  1501. emitMemModRMByte(MI, CurOp,
  1502. (Form == X86II::MRMXm) ? 0 : Form - X86II::MRM0m, TSFlags,
  1503. HasREX, StartByte, OS, Fixups, STI);
  1504. CurOp += X86::AddrNumOperands;
  1505. break;
  1506. case X86II::MRM0X:
  1507. case X86II::MRM1X:
  1508. case X86II::MRM2X:
  1509. case X86II::MRM3X:
  1510. case X86II::MRM4X:
  1511. case X86II::MRM5X:
  1512. case X86II::MRM6X:
  1513. case X86II::MRM7X:
  1514. emitByte(BaseOpcode, OS);
  1515. emitByte(0xC0 + ((Form - X86II::MRM0X) << 3), OS);
  1516. break;
  1517. case X86II::MRM_C0:
  1518. case X86II::MRM_C1:
  1519. case X86II::MRM_C2:
  1520. case X86II::MRM_C3:
  1521. case X86II::MRM_C4:
  1522. case X86II::MRM_C5:
  1523. case X86II::MRM_C6:
  1524. case X86II::MRM_C7:
  1525. case X86II::MRM_C8:
  1526. case X86II::MRM_C9:
  1527. case X86II::MRM_CA:
  1528. case X86II::MRM_CB:
  1529. case X86II::MRM_CC:
  1530. case X86II::MRM_CD:
  1531. case X86II::MRM_CE:
  1532. case X86II::MRM_CF:
  1533. case X86II::MRM_D0:
  1534. case X86II::MRM_D1:
  1535. case X86II::MRM_D2:
  1536. case X86II::MRM_D3:
  1537. case X86II::MRM_D4:
  1538. case X86II::MRM_D5:
  1539. case X86II::MRM_D6:
  1540. case X86II::MRM_D7:
  1541. case X86II::MRM_D8:
  1542. case X86II::MRM_D9:
  1543. case X86II::MRM_DA:
  1544. case X86II::MRM_DB:
  1545. case X86II::MRM_DC:
  1546. case X86II::MRM_DD:
  1547. case X86II::MRM_DE:
  1548. case X86II::MRM_DF:
  1549. case X86II::MRM_E0:
  1550. case X86II::MRM_E1:
  1551. case X86II::MRM_E2:
  1552. case X86II::MRM_E3:
  1553. case X86II::MRM_E4:
  1554. case X86II::MRM_E5:
  1555. case X86II::MRM_E6:
  1556. case X86II::MRM_E7:
  1557. case X86II::MRM_E8:
  1558. case X86II::MRM_E9:
  1559. case X86II::MRM_EA:
  1560. case X86II::MRM_EB:
  1561. case X86II::MRM_EC:
  1562. case X86II::MRM_ED:
  1563. case X86II::MRM_EE:
  1564. case X86II::MRM_EF:
  1565. case X86II::MRM_F0:
  1566. case X86II::MRM_F1:
  1567. case X86II::MRM_F2:
  1568. case X86II::MRM_F3:
  1569. case X86II::MRM_F4:
  1570. case X86II::MRM_F5:
  1571. case X86II::MRM_F6:
  1572. case X86II::MRM_F7:
  1573. case X86II::MRM_F8:
  1574. case X86II::MRM_F9:
  1575. case X86II::MRM_FA:
  1576. case X86II::MRM_FB:
  1577. case X86II::MRM_FC:
  1578. case X86II::MRM_FD:
  1579. case X86II::MRM_FE:
  1580. case X86II::MRM_FF:
  1581. emitByte(BaseOpcode, OS);
  1582. emitByte(0xC0 + Form - X86II::MRM_C0, OS);
  1583. break;
  1584. }
  1585. if (HasVEX_I8Reg) {
  1586. // The last source register of a 4 operand instruction in AVX is encoded
  1587. // in bits[7:4] of a immediate byte.
  1588. assert(I8RegNum < 16 && "Register encoding out of range");
  1589. I8RegNum <<= 4;
  1590. if (CurOp != NumOps) {
  1591. unsigned Val = MI.getOperand(CurOp++).getImm();
  1592. assert(Val < 16 && "Immediate operand value out of range");
  1593. I8RegNum |= Val;
  1594. }
  1595. emitImmediate(MCOperand::createImm(I8RegNum), MI.getLoc(), 1, FK_Data_1,
  1596. StartByte, OS, Fixups);
  1597. } else {
  1598. // If there is a remaining operand, it must be a trailing immediate. Emit it
  1599. // according to the right size for the instruction. Some instructions
  1600. // (SSE4a extrq and insertq) have two trailing immediates.
  1601. while (CurOp != NumOps && NumOps - CurOp <= 2) {
  1602. emitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
  1603. X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
  1604. StartByte, OS, Fixups);
  1605. }
  1606. }
  1607. if ((TSFlags & X86II::OpMapMask) == X86II::ThreeDNow)
  1608. emitByte(X86II::getBaseOpcodeFor(TSFlags), OS);
  1609. assert(OS.tell() - StartByte <= 15 &&
  1610. "The size of instruction must be no longer than 15.");
  1611. #ifndef NDEBUG
  1612. // FIXME: Verify.
  1613. if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
  1614. errs() << "Cannot encode all operands of: ";
  1615. MI.dump();
  1616. errs() << '\n';
  1617. abort();
  1618. }
  1619. #endif
  1620. }
  1621. MCCodeEmitter *llvm::createX86MCCodeEmitter(const MCInstrInfo &MCII,
  1622. const MCRegisterInfo &MRI,
  1623. MCContext &Ctx) {
  1624. return new X86MCCodeEmitter(MCII, Ctx);
  1625. }