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