Home | History | Annotate | Download | only in MCTargetDesc
      1 //===-- X86MCCodeEmitter.cpp - Convert X86 code to machine code -----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the X86MCCodeEmitter class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #define DEBUG_TYPE "mccodeemitter"
     15 #include "MCTargetDesc/X86MCTargetDesc.h"
     16 #include "MCTargetDesc/X86BaseInfo.h"
     17 #include "MCTargetDesc/X86FixupKinds.h"
     18 #include "llvm/MC/MCCodeEmitter.h"
     19 #include "llvm/MC/MCContext.h"
     20 #include "llvm/MC/MCExpr.h"
     21 #include "llvm/MC/MCInst.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/raw_ostream.h"
     27 
     28 using namespace llvm;
     29 
     30 namespace {
     31 class X86MCCodeEmitter : public MCCodeEmitter {
     32   X86MCCodeEmitter(const X86MCCodeEmitter &) LLVM_DELETED_FUNCTION;
     33   void operator=(const X86MCCodeEmitter &) LLVM_DELETED_FUNCTION;
     34   const MCInstrInfo &MCII;
     35   const MCSubtargetInfo &STI;
     36   MCContext &Ctx;
     37 public:
     38   X86MCCodeEmitter(const MCInstrInfo &mcii, const MCSubtargetInfo &sti,
     39                    MCContext &ctx)
     40     : MCII(mcii), STI(sti), Ctx(ctx) {
     41   }
     42 
     43   ~X86MCCodeEmitter() {}
     44 
     45   bool is64BitMode() const {
     46     // FIXME: Can tablegen auto-generate this?
     47     return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
     48   }
     49 
     50   bool is32BitMode() const {
     51     // FIXME: Can tablegen auto-generate this?
     52     return (STI.getFeatureBits() & X86::Mode64Bit) == 0;
     53   }
     54 
     55   unsigned GetX86RegNum(const MCOperand &MO) const {
     56     return Ctx.getRegisterInfo()->getEncodingValue(MO.getReg()) & 0x7;
     57   }
     58 
     59   // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
     60   // 0-7 and the difference between the 2 groups is given by the REX prefix.
     61   // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
     62   // in 1's complement form, example:
     63   //
     64   //  ModRM field => XMM9 => 1
     65   //  VEX.VVVV    => XMM9 => ~9
     66   //
     67   // See table 4-35 of Intel AVX Programming Reference for details.
     68   unsigned char getVEXRegisterEncoding(const MCInst &MI,
     69                                        unsigned OpNum) const {
     70     unsigned SrcReg = MI.getOperand(OpNum).getReg();
     71     unsigned SrcRegNum = GetX86RegNum(MI.getOperand(OpNum));
     72     if (X86II::isX86_64ExtendedReg(SrcReg))
     73       SrcRegNum |= 8;
     74 
     75     // The registers represented through VEX_VVVV should
     76     // be encoded in 1's complement form.
     77     return (~SrcRegNum) & 0xf;
     78   }
     79 
     80   unsigned char getWriteMaskRegisterEncoding(const MCInst &MI,
     81                                              unsigned OpNum) const {
     82     assert(X86::K0 != MI.getOperand(OpNum).getReg() &&
     83            "Invalid mask register as write-mask!");
     84     unsigned MaskRegNum = GetX86RegNum(MI.getOperand(OpNum));
     85     return MaskRegNum;
     86   }
     87 
     88   void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
     89     OS << (char)C;
     90     ++CurByte;
     91   }
     92 
     93   void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
     94                     raw_ostream &OS) const {
     95     // Output the constant in little endian byte order.
     96     for (unsigned i = 0; i != Size; ++i) {
     97       EmitByte(Val & 255, CurByte, OS);
     98       Val >>= 8;
     99     }
    100   }
    101 
    102   void EmitImmediate(const MCOperand &Disp, SMLoc Loc,
    103                      unsigned ImmSize, MCFixupKind FixupKind,
    104                      unsigned &CurByte, raw_ostream &OS,
    105                      SmallVectorImpl<MCFixup> &Fixups,
    106                      int ImmOffset = 0) const;
    107 
    108   inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
    109                                         unsigned RM) {
    110     assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
    111     return RM | (RegOpcode << 3) | (Mod << 6);
    112   }
    113 
    114   void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
    115                         unsigned &CurByte, raw_ostream &OS) const {
    116     EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
    117   }
    118 
    119   void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
    120                    unsigned &CurByte, raw_ostream &OS) const {
    121     // SIB byte is in the same format as the ModRMByte.
    122     EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
    123   }
    124 
    125 
    126   void EmitMemModRMByte(const MCInst &MI, unsigned Op,
    127                         unsigned RegOpcodeField,
    128                         uint64_t TSFlags, unsigned &CurByte, raw_ostream &OS,
    129                         SmallVectorImpl<MCFixup> &Fixups) const;
    130 
    131   void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
    132                          SmallVectorImpl<MCFixup> &Fixups) const;
    133 
    134   void EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
    135                            const MCInst &MI, const MCInstrDesc &Desc,
    136                            raw_ostream &OS) const;
    137 
    138   void EmitSegmentOverridePrefix(uint64_t TSFlags, unsigned &CurByte,
    139                                  int MemOperand, const MCInst &MI,
    140                                  raw_ostream &OS) const;
    141 
    142   void EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
    143                         const MCInst &MI, const MCInstrDesc &Desc,
    144                         raw_ostream &OS) const;
    145 };
    146 
    147 } // end anonymous namespace
    148 
    149 
    150 MCCodeEmitter *llvm::createX86MCCodeEmitter(const MCInstrInfo &MCII,
    151                                             const MCRegisterInfo &MRI,
    152                                             const MCSubtargetInfo &STI,
    153                                             MCContext &Ctx) {
    154   return new X86MCCodeEmitter(MCII, STI, Ctx);
    155 }
    156 
    157 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
    158 /// sign-extended field.
    159 static bool isDisp8(int Value) {
    160   return Value == (signed char)Value;
    161 }
    162 
    163 /// isCDisp8 - Return true if this signed displacement fits in a 8-bit
    164 /// compressed dispacement field.
    165 static bool isCDisp8(uint64_t TSFlags, int Value, int& CValue) {
    166   assert(((TSFlags >> X86II::VEXShift) & X86II::EVEX) &&
    167          "Compressed 8-bit displacement is only valid for EVEX inst.");
    168 
    169   unsigned CD8E = (TSFlags >> X86II::EVEX_CD8EShift) & X86II::EVEX_CD8EMask;
    170   unsigned CD8V = (TSFlags >> X86II::EVEX_CD8VShift) & X86II::EVEX_CD8VMask;
    171 
    172   if (CD8V == 0 && CD8E == 0) {
    173     CValue = Value;
    174     return isDisp8(Value);
    175   }
    176 
    177   unsigned MemObjSize = 1U << CD8E;
    178   if (CD8V & 4) {
    179     // Fixed vector length
    180     MemObjSize *= 1U << (CD8V & 0x3);
    181   } else {
    182     // Modified vector length
    183     bool EVEX_b = (TSFlags >> X86II::VEXShift) & X86II::EVEX_B;
    184     if (!EVEX_b) {
    185       unsigned EVEX_LL = ((TSFlags >> X86II::VEXShift) & X86II::VEX_L) ? 1 : 0;
    186       EVEX_LL += ((TSFlags >> X86II::VEXShift) & X86II::EVEX_L2) ? 2 : 0;
    187       assert(EVEX_LL < 3 && "");
    188 
    189       unsigned NumElems = (1U << (EVEX_LL + 4)) / MemObjSize;
    190       NumElems /= 1U << (CD8V & 0x3);
    191 
    192       MemObjSize *= NumElems;
    193     }
    194   }
    195 
    196   unsigned MemObjMask = MemObjSize - 1;
    197   assert((MemObjSize & MemObjMask) == 0 && "Invalid memory object size.");
    198 
    199   if (Value & MemObjMask) // Unaligned offset
    200     return false;
    201   Value /= MemObjSize;
    202   bool Ret = (Value == (signed char)Value);
    203 
    204   if (Ret)
    205     CValue = Value;
    206   return Ret;
    207 }
    208 
    209 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
    210 /// in an instruction with the specified TSFlags.
    211 static MCFixupKind getImmFixupKind(uint64_t TSFlags) {
    212   unsigned Size = X86II::getSizeOfImm(TSFlags);
    213   bool isPCRel = X86II::isImmPCRel(TSFlags);
    214 
    215   return MCFixup::getKindForSize(Size, isPCRel);
    216 }
    217 
    218 /// Is32BitMemOperand - Return true if the specified instruction has
    219 /// a 32-bit memory operand. Op specifies the operand # of the memoperand.
    220 static bool Is32BitMemOperand(const MCInst &MI, unsigned Op) {
    221   const MCOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
    222   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
    223 
    224   if ((BaseReg.getReg() != 0 &&
    225        X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
    226       (IndexReg.getReg() != 0 &&
    227        X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
    228     return true;
    229   return false;
    230 }
    231 
    232 /// Is64BitMemOperand - Return true if the specified instruction has
    233 /// a 64-bit memory operand. Op specifies the operand # of the memoperand.
    234 #ifndef NDEBUG
    235 static bool Is64BitMemOperand(const MCInst &MI, unsigned Op) {
    236   const MCOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
    237   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
    238 
    239   if ((BaseReg.getReg() != 0 &&
    240        X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg())) ||
    241       (IndexReg.getReg() != 0 &&
    242        X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg())))
    243     return true;
    244   return false;
    245 }
    246 #endif
    247 
    248 /// Is16BitMemOperand - Return true if the specified instruction has
    249 /// a 16-bit memory operand. Op specifies the operand # of the memoperand.
    250 static bool Is16BitMemOperand(const MCInst &MI, unsigned Op) {
    251   const MCOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
    252   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
    253 
    254   if ((BaseReg.getReg() != 0 &&
    255        X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg.getReg())) ||
    256       (IndexReg.getReg() != 0 &&
    257        X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg.getReg())))
    258     return true;
    259   return false;
    260 }
    261 
    262 /// StartsWithGlobalOffsetTable - Check if this expression starts with
    263 ///  _GLOBAL_OFFSET_TABLE_ and if it is of the form
    264 ///  _GLOBAL_OFFSET_TABLE_-symbol. This is needed to support PIC on ELF
    265 /// i386 as _GLOBAL_OFFSET_TABLE_ is magical. We check only simple case that
    266 /// are know to be used: _GLOBAL_OFFSET_TABLE_ by itself or at the start
    267 /// of a binary expression.
    268 enum GlobalOffsetTableExprKind {
    269   GOT_None,
    270   GOT_Normal,
    271   GOT_SymDiff
    272 };
    273 static GlobalOffsetTableExprKind
    274 StartsWithGlobalOffsetTable(const MCExpr *Expr) {
    275   const MCExpr *RHS = 0;
    276   if (Expr->getKind() == MCExpr::Binary) {
    277     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Expr);
    278     Expr = BE->getLHS();
    279     RHS = BE->getRHS();
    280   }
    281 
    282   if (Expr->getKind() != MCExpr::SymbolRef)
    283     return GOT_None;
    284 
    285   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Expr);
    286   const MCSymbol &S = Ref->getSymbol();
    287   if (S.getName() != "_GLOBAL_OFFSET_TABLE_")
    288     return GOT_None;
    289   if (RHS && RHS->getKind() == MCExpr::SymbolRef)
    290     return GOT_SymDiff;
    291   return GOT_Normal;
    292 }
    293 
    294 static bool HasSecRelSymbolRef(const MCExpr *Expr) {
    295   if (Expr->getKind() == MCExpr::SymbolRef) {
    296     const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Expr);
    297     return Ref->getKind() == MCSymbolRefExpr::VK_SECREL;
    298   }
    299   return false;
    300 }
    301 
    302 void X86MCCodeEmitter::
    303 EmitImmediate(const MCOperand &DispOp, SMLoc Loc, unsigned Size,
    304               MCFixupKind FixupKind, unsigned &CurByte, raw_ostream &OS,
    305               SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
    306   const MCExpr *Expr = NULL;
    307   if (DispOp.isImm()) {
    308     // If this is a simple integer displacement that doesn't require a
    309     // relocation, emit it now.
    310     if (FixupKind != FK_PCRel_1 &&
    311         FixupKind != FK_PCRel_2 &&
    312         FixupKind != FK_PCRel_4) {
    313       EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
    314       return;
    315     }
    316     Expr = MCConstantExpr::Create(DispOp.getImm(), Ctx);
    317   } else {
    318     Expr = DispOp.getExpr();
    319   }
    320 
    321   // If we have an immoffset, add it to the expression.
    322   if ((FixupKind == FK_Data_4 ||
    323        FixupKind == FK_Data_8 ||
    324        FixupKind == MCFixupKind(X86::reloc_signed_4byte))) {
    325     GlobalOffsetTableExprKind Kind = StartsWithGlobalOffsetTable(Expr);
    326     if (Kind != GOT_None) {
    327       assert(ImmOffset == 0);
    328 
    329       FixupKind = MCFixupKind(X86::reloc_global_offset_table);
    330       if (Kind == GOT_Normal)
    331         ImmOffset = CurByte;
    332     } else if (Expr->getKind() == MCExpr::SymbolRef) {
    333       if (HasSecRelSymbolRef(Expr)) {
    334         FixupKind = MCFixupKind(FK_SecRel_4);
    335       }
    336     } else if (Expr->getKind() == MCExpr::Binary) {
    337       const MCBinaryExpr *Bin = static_cast<const MCBinaryExpr*>(Expr);
    338       if (HasSecRelSymbolRef(Bin->getLHS())
    339           || HasSecRelSymbolRef(Bin->getRHS())) {
    340         FixupKind = MCFixupKind(FK_SecRel_4);
    341       }
    342     }
    343   }
    344 
    345   // If the fixup is pc-relative, we need to bias the value to be relative to
    346   // the start of the field, not the end of the field.
    347   if (FixupKind == FK_PCRel_4 ||
    348       FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
    349       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load))
    350     ImmOffset -= 4;
    351   if (FixupKind == FK_PCRel_2)
    352     ImmOffset -= 2;
    353   if (FixupKind == FK_PCRel_1)
    354     ImmOffset -= 1;
    355 
    356   if (ImmOffset)
    357     Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(ImmOffset, Ctx),
    358                                    Ctx);
    359 
    360   // Emit a symbolic constant as a fixup and 4 zeros.
    361   Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind, Loc));
    362   EmitConstant(0, Size, CurByte, OS);
    363 }
    364 
    365 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
    366                                         unsigned RegOpcodeField,
    367                                         uint64_t TSFlags, unsigned &CurByte,
    368                                         raw_ostream &OS,
    369                                         SmallVectorImpl<MCFixup> &Fixups) const{
    370   const MCOperand &Disp     = MI.getOperand(Op+X86::AddrDisp);
    371   const MCOperand &Base     = MI.getOperand(Op+X86::AddrBaseReg);
    372   const MCOperand &Scale    = MI.getOperand(Op+X86::AddrScaleAmt);
    373   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
    374   unsigned BaseReg = Base.getReg();
    375   bool HasEVEX = (TSFlags >> X86II::VEXShift) & X86II::EVEX;
    376 
    377   // Handle %rip relative addressing.
    378   if (BaseReg == X86::RIP) {    // [disp32+RIP] in X86-64 mode
    379     assert(is64BitMode() && "Rip-relative addressing requires 64-bit mode");
    380     assert(IndexReg.getReg() == 0 && "Invalid rip-relative address");
    381     EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
    382 
    383     unsigned FixupKind = X86::reloc_riprel_4byte;
    384 
    385     // movq loads are handled with a special relocation form which allows the
    386     // linker to eliminate some loads for GOT references which end up in the
    387     // same linkage unit.
    388     if (MI.getOpcode() == X86::MOV64rm)
    389       FixupKind = X86::reloc_riprel_4byte_movq_load;
    390 
    391     // rip-relative addressing is actually relative to the *next* instruction.
    392     // Since an immediate can follow the mod/rm byte for an instruction, this
    393     // means that we need to bias the immediate field of the instruction with
    394     // the size of the immediate field.  If we have this case, add it into the
    395     // expression to emit.
    396     int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
    397 
    398     EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(FixupKind),
    399                   CurByte, OS, Fixups, -ImmSize);
    400     return;
    401   }
    402 
    403   unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
    404 
    405   // Determine whether a SIB byte is needed.
    406   // If no BaseReg, issue a RIP relative instruction only if the MCE can
    407   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
    408   // 2-7) and absolute references.
    409 
    410   if (// The SIB byte must be used if there is an index register.
    411       IndexReg.getReg() == 0 &&
    412       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
    413       // encode to an R/M value of 4, which indicates that a SIB byte is
    414       // present.
    415       BaseRegNo != N86::ESP &&
    416       // If there is no base register and we're in 64-bit mode, we need a SIB
    417       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
    418       (!is64BitMode() || BaseReg != 0)) {
    419 
    420     if (BaseReg == 0) {          // [disp32]     in X86-32 mode
    421       EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
    422       EmitImmediate(Disp, MI.getLoc(), 4, FK_Data_4, CurByte, OS, Fixups);
    423       return;
    424     }
    425 
    426     // If the base is not EBP/ESP and there is no displacement, use simple
    427     // indirect register encoding, this handles addresses like [EAX].  The
    428     // encoding for [EBP] with no displacement means [disp32] so we handle it
    429     // by emitting a displacement of 0 below.
    430     if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
    431       EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
    432       return;
    433     }
    434 
    435     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
    436     if (Disp.isImm()) {
    437       if (!HasEVEX && isDisp8(Disp.getImm())) {
    438         EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
    439         EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups);
    440         return;
    441       }
    442       // Try EVEX compressed 8-bit displacement first; if failed, fall back to
    443       // 32-bit displacement.
    444       int CDisp8 = 0;
    445       if (HasEVEX && isCDisp8(TSFlags, Disp.getImm(), CDisp8)) {
    446         EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
    447         EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups,
    448                       CDisp8 - Disp.getImm());
    449         return;
    450       }
    451     }
    452 
    453     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
    454     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
    455     EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, OS,
    456                   Fixups);
    457     return;
    458   }
    459 
    460   // We need a SIB byte, so start by outputting the ModR/M byte first
    461   assert(IndexReg.getReg() != X86::ESP &&
    462          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
    463 
    464   bool ForceDisp32 = false;
    465   bool ForceDisp8  = false;
    466   int CDisp8 = 0;
    467   int ImmOffset = 0;
    468   if (BaseReg == 0) {
    469     // If there is no base register, we emit the special case SIB byte with
    470     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
    471     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
    472     ForceDisp32 = true;
    473   } else if (!Disp.isImm()) {
    474     // Emit the normal disp32 encoding.
    475     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
    476     ForceDisp32 = true;
    477   } else if (Disp.getImm() == 0 &&
    478              // Base reg can't be anything that ends up with '5' as the base
    479              // reg, it is the magic [*] nomenclature that indicates no base.
    480              BaseRegNo != N86::EBP) {
    481     // Emit no displacement ModR/M byte
    482     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
    483   } else if (!HasEVEX && isDisp8(Disp.getImm())) {
    484     // Emit the disp8 encoding.
    485     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
    486     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
    487   } else if (HasEVEX && isCDisp8(TSFlags, Disp.getImm(), CDisp8)) {
    488     // Emit the disp8 encoding.
    489     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
    490     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
    491     ImmOffset = CDisp8 - Disp.getImm();
    492   } else {
    493     // Emit the normal disp32 encoding.
    494     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
    495   }
    496 
    497   // Calculate what the SS field value should be...
    498   static const unsigned SSTable[] = { ~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3 };
    499   unsigned SS = SSTable[Scale.getImm()];
    500 
    501   if (BaseReg == 0) {
    502     // Handle the SIB byte for the case where there is no base, see Intel
    503     // Manual 2A, table 2-7. The displacement has already been output.
    504     unsigned IndexRegNo;
    505     if (IndexReg.getReg())
    506       IndexRegNo = GetX86RegNum(IndexReg);
    507     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
    508       IndexRegNo = 4;
    509     EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
    510   } else {
    511     unsigned IndexRegNo;
    512     if (IndexReg.getReg())
    513       IndexRegNo = GetX86RegNum(IndexReg);
    514     else
    515       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
    516     EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
    517   }
    518 
    519   // Do we need to output a displacement?
    520   if (ForceDisp8)
    521     EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups, ImmOffset);
    522   else if (ForceDisp32 || Disp.getImm() != 0)
    523     EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byte),
    524                   CurByte, OS, Fixups);
    525 }
    526 
    527 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode prefix
    528 /// called VEX.
    529 void X86MCCodeEmitter::EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
    530                                            int MemOperand, const MCInst &MI,
    531                                            const MCInstrDesc &Desc,
    532                                            raw_ostream &OS) const {
    533   bool HasEVEX = (TSFlags >> X86II::VEXShift) & X86II::EVEX;
    534   bool HasEVEX_K = HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_K);
    535   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
    536   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
    537   bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
    538 
    539   // VEX_R: opcode externsion equivalent to REX.R in
    540   // 1's complement (inverted) form
    541   //
    542   //  1: Same as REX_R=0 (must be 1 in 32-bit mode)
    543   //  0: Same as REX_R=1 (64 bit mode only)
    544   //
    545   unsigned char VEX_R = 0x1;
    546   unsigned char EVEX_R2 = 0x1;
    547 
    548   // VEX_X: equivalent to REX.X, only used when a
    549   // register is used for index in SIB Byte.
    550   //
    551   //  1: Same as REX.X=0 (must be 1 in 32-bit mode)
    552   //  0: Same as REX.X=1 (64-bit mode only)
    553   unsigned char VEX_X = 0x1;
    554 
    555   // VEX_B:
    556   //
    557   //  1: Same as REX_B=0 (ignored in 32-bit mode)
    558   //  0: Same as REX_B=1 (64 bit mode only)
    559   //
    560   unsigned char VEX_B = 0x1;
    561 
    562   // VEX_W: opcode specific (use like REX.W, or used for
    563   // opcode extension, or ignored, depending on the opcode byte)
    564   unsigned char VEX_W = 0;
    565 
    566   // XOP: Use XOP prefix byte 0x8f instead of VEX.
    567   unsigned char XOP = 0;
    568 
    569   // VEX_5M (VEX m-mmmmm field):
    570   //
    571   //  0b00000: Reserved for future use
    572   //  0b00001: implied 0F leading opcode
    573   //  0b00010: implied 0F 38 leading opcode bytes
    574   //  0b00011: implied 0F 3A leading opcode bytes
    575   //  0b00100-0b11111: Reserved for future use
    576   //  0b01000: XOP map select - 08h instructions with imm byte
    577   //  0b10001: XOP map select - 09h instructions with no imm byte
    578   unsigned char VEX_5M = 0x1;
    579 
    580   // VEX_4V (VEX vvvv field): a register specifier
    581   // (in 1's complement form) or 1111 if unused.
    582   unsigned char VEX_4V = 0xf;
    583   unsigned char EVEX_V2 = 0x1;
    584 
    585   // VEX_L (Vector Length):
    586   //
    587   //  0: scalar or 128-bit vector
    588   //  1: 256-bit vector
    589   //
    590   unsigned char VEX_L = 0;
    591   unsigned char EVEX_L2 = 0;
    592 
    593   // VEX_PP: opcode extension providing equivalent
    594   // functionality of a SIMD prefix
    595   //
    596   //  0b00: None
    597   //  0b01: 66
    598   //  0b10: F3
    599   //  0b11: F2
    600   //
    601   unsigned char VEX_PP = 0;
    602 
    603   // EVEX_U
    604   unsigned char EVEX_U = 1; // Always '1' so far
    605 
    606   // EVEX_z
    607   unsigned char EVEX_z = 0;
    608 
    609   // EVEX_b
    610   unsigned char EVEX_b = 0;
    611 
    612   // EVEX_aaa
    613   unsigned char EVEX_aaa = 0;
    614 
    615   // Encode the operand size opcode prefix as needed.
    616   if (TSFlags & X86II::OpSize)
    617     VEX_PP = 0x01;
    618 
    619   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
    620     VEX_W = 1;
    621 
    622   if ((TSFlags >> X86II::VEXShift) & X86II::XOP)
    623     XOP = 1;
    624 
    625   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
    626     VEX_L = 1;
    627   if (HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_L2))
    628     EVEX_L2 = 1;
    629 
    630   if (HasEVEX_K && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_Z))
    631     EVEX_z = 1;
    632 
    633   if (HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_B))
    634     EVEX_b = 1;
    635 
    636   switch (TSFlags & X86II::Op0Mask) {
    637   default: llvm_unreachable("Invalid prefix!");
    638   case X86II::T8:  // 0F 38
    639     VEX_5M = 0x2;
    640     break;
    641   case X86II::TA:  // 0F 3A
    642     VEX_5M = 0x3;
    643     break;
    644   case X86II::T8XS: // F3 0F 38
    645     VEX_PP = 0x2;
    646     VEX_5M = 0x2;
    647     break;
    648   case X86II::T8XD: // F2 0F 38
    649     VEX_PP = 0x3;
    650     VEX_5M = 0x2;
    651     break;
    652   case X86II::TAXD: // F2 0F 3A
    653     VEX_PP = 0x3;
    654     VEX_5M = 0x3;
    655     break;
    656   case X86II::XS:  // F3 0F
    657     VEX_PP = 0x2;
    658     break;
    659   case X86II::XD:  // F2 0F
    660     VEX_PP = 0x3;
    661     break;
    662   case X86II::XOP8:
    663     VEX_5M = 0x8;
    664     break;
    665   case X86II::XOP9:
    666     VEX_5M = 0x9;
    667     break;
    668   case X86II::A6:  // Bypass: Not used by VEX
    669   case X86II::A7:  // Bypass: Not used by VEX
    670   case X86II::TB:  // Bypass: Not used by VEX
    671   case 0:
    672     break;  // No prefix!
    673   }
    674 
    675 
    676   // Classify VEX_B, VEX_4V, VEX_R, VEX_X
    677   unsigned NumOps = Desc.getNumOperands();
    678   unsigned CurOp = 0;
    679   if (NumOps > 1 && Desc.getOperandConstraint(1, MCOI::TIED_TO) == 0)
    680     ++CurOp;
    681   else if (NumOps > 3 && Desc.getOperandConstraint(2, MCOI::TIED_TO) == 0 &&
    682            Desc.getOperandConstraint(3, MCOI::TIED_TO) == 1)
    683     // Special case for AVX-512 GATHER with 2 TIED_TO operands
    684     // Skip the first 2 operands: dst, mask_wb
    685     CurOp += 2;
    686   else if (NumOps > 3 && Desc.getOperandConstraint(2, MCOI::TIED_TO) == 0 &&
    687            Desc.getOperandConstraint(NumOps - 1, MCOI::TIED_TO) == 1)
    688     // Special case for GATHER with 2 TIED_TO operands
    689     // Skip the first 2 operands: dst, mask_wb
    690     CurOp += 2;
    691   else if (NumOps > 2 && Desc.getOperandConstraint(NumOps - 2, MCOI::TIED_TO) == 0)
    692     // SCATTER
    693     ++CurOp;
    694 
    695   switch (TSFlags & X86II::FormMask) {
    696   case X86II::MRMInitReg: llvm_unreachable("FIXME: Remove this!");
    697   case X86II::MRMDestMem: {
    698     // MRMDestMem instructions forms:
    699     //  MemAddr, src1(ModR/M)
    700     //  MemAddr, src1(VEX_4V), src2(ModR/M)
    701     //  MemAddr, src1(ModR/M), imm8
    702     //
    703     if (X86II::isX86_64ExtendedReg(MI.getOperand(MemOperand +
    704                                                  X86::AddrBaseReg).getReg()))
    705       VEX_B = 0x0;
    706     if (X86II::isX86_64ExtendedReg(MI.getOperand(MemOperand +
    707                                                  X86::AddrIndexReg).getReg()))
    708       VEX_X = 0x0;
    709     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(MemOperand +
    710                                           X86::AddrIndexReg).getReg()))
    711       EVEX_V2 = 0x0;
    712 
    713     CurOp += X86::AddrNumOperands;
    714 
    715     if (HasEVEX_K)
    716       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
    717 
    718     if (HasVEX_4V) {
    719       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
    720       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    721         EVEX_V2 = 0x0;
    722       CurOp++;
    723     }
    724 
    725     const MCOperand &MO = MI.getOperand(CurOp);
    726     if (MO.isReg()) {
    727       if (X86II::isX86_64ExtendedReg(MO.getReg()))
    728         VEX_R = 0x0;
    729       if (HasEVEX && X86II::is32ExtendedReg(MO.getReg()))
    730         EVEX_R2 = 0x0;
    731     }
    732     break;
    733   }
    734   case X86II::MRMSrcMem:
    735     // MRMSrcMem instructions forms:
    736     //  src1(ModR/M), MemAddr
    737     //  src1(ModR/M), src2(VEX_4V), MemAddr
    738     //  src1(ModR/M), MemAddr, imm8
    739     //  src1(ModR/M), MemAddr, src2(VEX_I8IMM)
    740     //
    741     //  FMA4:
    742     //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
    743     //  dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
    744     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
    745       VEX_R = 0x0;
    746     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    747       EVEX_R2 = 0x0;
    748     CurOp++;
    749 
    750     if (HasEVEX_K)
    751       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
    752 
    753     if (HasVEX_4V) {
    754       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
    755       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    756         EVEX_V2 = 0x0;
    757       CurOp++;
    758     }
    759 
    760     if (X86II::isX86_64ExtendedReg(
    761                MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
    762       VEX_B = 0x0;
    763     if (X86II::isX86_64ExtendedReg(
    764                MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
    765       VEX_X = 0x0;
    766     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(MemOperand +
    767                                           X86::AddrIndexReg).getReg()))
    768       EVEX_V2 = 0x0;
    769 
    770     if (HasVEX_4VOp3)
    771       // Instruction format for 4VOp3:
    772       //   src1(ModR/M), MemAddr, src3(VEX_4V)
    773       // CurOp points to start of the MemoryOperand,
    774       //   it skips TIED_TO operands if exist, then increments past src1.
    775       // CurOp + X86::AddrNumOperands will point to src3.
    776       VEX_4V = getVEXRegisterEncoding(MI, CurOp+X86::AddrNumOperands);
    777     break;
    778   case X86II::MRM0m: case X86II::MRM1m:
    779   case X86II::MRM2m: case X86II::MRM3m:
    780   case X86II::MRM4m: case X86II::MRM5m:
    781   case X86II::MRM6m: case X86II::MRM7m: {
    782     // MRM[0-9]m instructions forms:
    783     //  MemAddr
    784     //  src1(VEX_4V), MemAddr
    785     if (HasVEX_4V) {
    786       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
    787       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    788         EVEX_V2 = 0x0;
    789     }
    790     CurOp++;
    791 
    792     if (HasEVEX_K)
    793       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
    794 
    795     if (X86II::isX86_64ExtendedReg(
    796                MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
    797       VEX_B = 0x0;
    798     if (X86II::isX86_64ExtendedReg(
    799                MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
    800       VEX_X = 0x0;
    801     break;
    802   }
    803   case X86II::MRMSrcReg:
    804     // MRMSrcReg instructions forms:
    805     //  dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
    806     //  dst(ModR/M), src1(ModR/M)
    807     //  dst(ModR/M), src1(ModR/M), imm8
    808     //
    809     //  FMA4:
    810     //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
    811     //  dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
    812     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
    813       VEX_R = 0x0;
    814     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    815       EVEX_R2 = 0x0;
    816     CurOp++;
    817 
    818     if (HasEVEX_K)
    819       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
    820 
    821     if (HasVEX_4V) {
    822       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
    823       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    824         EVEX_V2 = 0x0;
    825       CurOp++;
    826     }
    827 
    828     if (HasMemOp4) // Skip second register source (encoded in I8IMM)
    829       CurOp++;
    830 
    831     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
    832       VEX_B = 0x0;
    833     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    834       VEX_X = 0x0;
    835     CurOp++;
    836     if (HasVEX_4VOp3)
    837       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
    838     break;
    839   case X86II::MRMDestReg:
    840     // MRMDestReg instructions forms:
    841     //  dst(ModR/M), src(ModR/M)
    842     //  dst(ModR/M), src(ModR/M), imm8
    843     //  dst(ModR/M), src1(VEX_4V), src2(ModR/M)
    844     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
    845       VEX_B = 0x0;
    846     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    847       VEX_X = 0x0;
    848     CurOp++;
    849 
    850     if (HasEVEX_K)
    851       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
    852 
    853     if (HasVEX_4V) {
    854       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
    855       if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    856         EVEX_V2 = 0x0;
    857       CurOp++;
    858     }
    859 
    860     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
    861       VEX_R = 0x0;
    862     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    863       EVEX_R2 = 0x0;
    864     break;
    865   case X86II::MRM0r: case X86II::MRM1r:
    866   case X86II::MRM2r: case X86II::MRM3r:
    867   case X86II::MRM4r: case X86II::MRM5r:
    868   case X86II::MRM6r: case X86II::MRM7r:
    869     // MRM0r-MRM7r instructions forms:
    870     //  dst(VEX_4V), src(ModR/M), imm8
    871     VEX_4V = getVEXRegisterEncoding(MI, CurOp);
    872     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    873         EVEX_V2 = 0x0;
    874     CurOp++;
    875 
    876     if (HasEVEX_K)
    877       EVEX_aaa = getWriteMaskRegisterEncoding(MI, CurOp++);
    878 
    879     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
    880       VEX_B = 0x0;
    881     if (HasEVEX && X86II::is32ExtendedReg(MI.getOperand(CurOp).getReg()))
    882       VEX_X = 0x0;
    883     break;
    884   default: // RawFrm
    885     break;
    886   }
    887 
    888   // Emit segment override opcode prefix as needed.
    889   EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
    890 
    891   if (!HasEVEX) {
    892     // VEX opcode prefix can have 2 or 3 bytes
    893     //
    894     //  3 bytes:
    895     //    +-----+ +--------------+ +-------------------+
    896     //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
    897     //    +-----+ +--------------+ +-------------------+
    898     //  2 bytes:
    899     //    +-----+ +-------------------+
    900     //    | C5h | | R | vvvv | L | pp |
    901     //    +-----+ +-------------------+
    902     //
    903     unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
    904 
    905     if (VEX_B && VEX_X && !VEX_W && !XOP && (VEX_5M == 1)) { // 2 byte VEX prefix
    906       EmitByte(0xC5, CurByte, OS);
    907       EmitByte(LastByte | (VEX_R << 7), CurByte, OS);
    908       return;
    909     }
    910 
    911     // 3 byte VEX prefix
    912     EmitByte(XOP ? 0x8F : 0xC4, CurByte, OS);
    913     EmitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, CurByte, OS);
    914     EmitByte(LastByte | (VEX_W << 7), CurByte, OS);
    915   } else {
    916     // EVEX opcode prefix can have 4 bytes
    917     //
    918     // +-----+ +--------------+ +-------------------+ +------------------------+
    919     // | 62h | | RXBR' | 00mm | | W | vvvv | U | pp | | z | L'L | b | v' | aaa |
    920     // +-----+ +--------------+ +-------------------+ +------------------------+
    921     assert((VEX_5M & 0x3) == VEX_5M
    922            && "More than 2 significant bits in VEX.m-mmmm fields for EVEX!");
    923 
    924     VEX_5M &= 0x3;
    925 
    926     EmitByte(0x62, CurByte, OS);
    927     EmitByte((VEX_R   << 7) |
    928              (VEX_X   << 6) |
    929              (VEX_B   << 5) |
    930              (EVEX_R2 << 4) |
    931              VEX_5M, CurByte, OS);
    932     EmitByte((VEX_W   << 7) |
    933              (VEX_4V  << 3) |
    934              (EVEX_U  << 2) |
    935              VEX_PP, CurByte, OS);
    936     EmitByte((EVEX_z  << 7) |
    937              (EVEX_L2 << 6) |
    938              (VEX_L   << 5) |
    939              (EVEX_b  << 4) |
    940              (EVEX_V2 << 3) |
    941              EVEX_aaa, CurByte, OS);
    942   }
    943 }
    944 
    945 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
    946 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
    947 /// size, and 3) use of X86-64 extended registers.
    948 static unsigned DetermineREXPrefix(const MCInst &MI, uint64_t TSFlags,
    949                                    const MCInstrDesc &Desc) {
    950   unsigned REX = 0;
    951   if (TSFlags & X86II::REX_W)
    952     REX |= 1 << 3; // set REX.W
    953 
    954   if (MI.getNumOperands() == 0) return REX;
    955 
    956   unsigned NumOps = MI.getNumOperands();
    957   // FIXME: MCInst should explicitize the two-addrness.
    958   bool isTwoAddr = NumOps > 1 &&
    959                       Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1;
    960 
    961   // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
    962   unsigned i = isTwoAddr ? 1 : 0;
    963   for (; i != NumOps; ++i) {
    964     const MCOperand &MO = MI.getOperand(i);
    965     if (!MO.isReg()) continue;
    966     unsigned Reg = MO.getReg();
    967     if (!X86II::isX86_64NonExtLowByteReg(Reg)) continue;
    968     // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
    969     // that returns non-zero.
    970     REX |= 0x40; // REX fixed encoding prefix
    971     break;
    972   }
    973 
    974   switch (TSFlags & X86II::FormMask) {
    975   case X86II::MRMInitReg: llvm_unreachable("FIXME: Remove this!");
    976   case X86II::MRMSrcReg:
    977     if (MI.getOperand(0).isReg() &&
    978         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
    979       REX |= 1 << 2; // set REX.R
    980     i = isTwoAddr ? 2 : 1;
    981     for (; i != NumOps; ++i) {
    982       const MCOperand &MO = MI.getOperand(i);
    983       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
    984         REX |= 1 << 0; // set REX.B
    985     }
    986     break;
    987   case X86II::MRMSrcMem: {
    988     if (MI.getOperand(0).isReg() &&
    989         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
    990       REX |= 1 << 2; // set REX.R
    991     unsigned Bit = 0;
    992     i = isTwoAddr ? 2 : 1;
    993     for (; i != NumOps; ++i) {
    994       const MCOperand &MO = MI.getOperand(i);
    995       if (MO.isReg()) {
    996         if (X86II::isX86_64ExtendedReg(MO.getReg()))
    997           REX |= 1 << Bit; // set REX.B (Bit=0) and REX.X (Bit=1)
    998         Bit++;
    999       }
   1000     }
   1001     break;
   1002   }
   1003   case X86II::MRM0m: case X86II::MRM1m:
   1004   case X86II::MRM2m: case X86II::MRM3m:
   1005   case X86II::MRM4m: case X86II::MRM5m:
   1006   case X86II::MRM6m: case X86II::MRM7m:
   1007   case X86II::MRMDestMem: {
   1008     unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
   1009     i = isTwoAddr ? 1 : 0;
   1010     if (NumOps > e && MI.getOperand(e).isReg() &&
   1011         X86II::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
   1012       REX |= 1 << 2; // set REX.R
   1013     unsigned Bit = 0;
   1014     for (; i != e; ++i) {
   1015       const MCOperand &MO = MI.getOperand(i);
   1016       if (MO.isReg()) {
   1017         if (X86II::isX86_64ExtendedReg(MO.getReg()))
   1018           REX |= 1 << Bit; // REX.B (Bit=0) and REX.X (Bit=1)
   1019         Bit++;
   1020       }
   1021     }
   1022     break;
   1023   }
   1024   default:
   1025     if (MI.getOperand(0).isReg() &&
   1026         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
   1027       REX |= 1 << 0; // set REX.B
   1028     i = isTwoAddr ? 2 : 1;
   1029     for (unsigned e = NumOps; i != e; ++i) {
   1030       const MCOperand &MO = MI.getOperand(i);
   1031       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
   1032         REX |= 1 << 2; // set REX.R
   1033     }
   1034     break;
   1035   }
   1036   return REX;
   1037 }
   1038 
   1039 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
   1040 void X86MCCodeEmitter::EmitSegmentOverridePrefix(uint64_t TSFlags,
   1041                                         unsigned &CurByte, int MemOperand,
   1042                                         const MCInst &MI,
   1043                                         raw_ostream &OS) const {
   1044   switch (TSFlags & X86II::SegOvrMask) {
   1045   default: llvm_unreachable("Invalid segment!");
   1046   case 0:
   1047     // No segment override, check for explicit one on memory operand.
   1048     if (MemOperand != -1) {   // If the instruction has a memory operand.
   1049       switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
   1050       default: llvm_unreachable("Unknown segment register!");
   1051       case 0: break;
   1052       case X86::CS: EmitByte(0x2E, CurByte, OS); break;
   1053       case X86::SS: EmitByte(0x36, CurByte, OS); break;
   1054       case X86::DS: EmitByte(0x3E, CurByte, OS); break;
   1055       case X86::ES: EmitByte(0x26, CurByte, OS); break;
   1056       case X86::FS: EmitByte(0x64, CurByte, OS); break;
   1057       case X86::GS: EmitByte(0x65, CurByte, OS); break;
   1058       }
   1059     }
   1060     break;
   1061   case X86II::FS:
   1062     EmitByte(0x64, CurByte, OS);
   1063     break;
   1064   case X86II::GS:
   1065     EmitByte(0x65, CurByte, OS);
   1066     break;
   1067   }
   1068 }
   1069 
   1070 /// EmitOpcodePrefix - Emit all instruction prefixes prior to the opcode.
   1071 ///
   1072 /// MemOperand is the operand # of the start of a memory operand if present.  If
   1073 /// Not present, it is -1.
   1074 void X86MCCodeEmitter::EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
   1075                                         int MemOperand, const MCInst &MI,
   1076                                         const MCInstrDesc &Desc,
   1077                                         raw_ostream &OS) const {
   1078 
   1079   // Emit the lock opcode prefix as needed.
   1080   if (TSFlags & X86II::LOCK)
   1081     EmitByte(0xF0, CurByte, OS);
   1082 
   1083   // Emit segment override opcode prefix as needed.
   1084   EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
   1085 
   1086   // Emit the repeat opcode prefix as needed.
   1087   if ((TSFlags & X86II::Op0Mask) == X86II::REP)
   1088     EmitByte(0xF3, CurByte, OS);
   1089 
   1090   // Emit the address size opcode prefix as needed.
   1091   bool need_address_override;
   1092   if (TSFlags & X86II::AdSize) {
   1093     need_address_override = true;
   1094   } else if (MemOperand == -1) {
   1095     need_address_override = false;
   1096   } else if (is64BitMode()) {
   1097     assert(!Is16BitMemOperand(MI, MemOperand));
   1098     need_address_override = Is32BitMemOperand(MI, MemOperand);
   1099   } else if (is32BitMode()) {
   1100     assert(!Is64BitMemOperand(MI, MemOperand));
   1101     need_address_override = Is16BitMemOperand(MI, MemOperand);
   1102   } else {
   1103     need_address_override = false;
   1104   }
   1105 
   1106   if (need_address_override)
   1107     EmitByte(0x67, CurByte, OS);
   1108 
   1109   // Emit the operand size opcode prefix as needed.
   1110   if (TSFlags & X86II::OpSize)
   1111     EmitByte(0x66, CurByte, OS);
   1112 
   1113   bool Need0FPrefix = false;
   1114   switch (TSFlags & X86II::Op0Mask) {
   1115   default: llvm_unreachable("Invalid prefix!");
   1116   case 0: break;  // No prefix!
   1117   case X86II::REP: break; // already handled.
   1118   case X86II::TB:  // Two-byte opcode prefix
   1119   case X86II::T8:  // 0F 38
   1120   case X86II::TA:  // 0F 3A
   1121   case X86II::A6:  // 0F A6
   1122   case X86II::A7:  // 0F A7
   1123     Need0FPrefix = true;
   1124     break;
   1125   case X86II::T8XS: // F3 0F 38
   1126     EmitByte(0xF3, CurByte, OS);
   1127     Need0FPrefix = true;
   1128     break;
   1129   case X86II::T8XD: // F2 0F 38
   1130     EmitByte(0xF2, CurByte, OS);
   1131     Need0FPrefix = true;
   1132     break;
   1133   case X86II::TAXD: // F2 0F 3A
   1134     EmitByte(0xF2, CurByte, OS);
   1135     Need0FPrefix = true;
   1136     break;
   1137   case X86II::XS:   // F3 0F
   1138     EmitByte(0xF3, CurByte, OS);
   1139     Need0FPrefix = true;
   1140     break;
   1141   case X86II::XD:   // F2 0F
   1142     EmitByte(0xF2, CurByte, OS);
   1143     Need0FPrefix = true;
   1144     break;
   1145   case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
   1146   case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
   1147   case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
   1148   case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
   1149   case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
   1150   case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
   1151   case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
   1152   case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
   1153   }
   1154 
   1155   // Handle REX prefix.
   1156   // FIXME: Can this come before F2 etc to simplify emission?
   1157   if (is64BitMode()) {
   1158     if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
   1159       EmitByte(0x40 | REX, CurByte, OS);
   1160   }
   1161 
   1162   // 0x0F escape code must be emitted just before the opcode.
   1163   if (Need0FPrefix)
   1164     EmitByte(0x0F, CurByte, OS);
   1165 
   1166   // FIXME: Pull this up into previous switch if REX can be moved earlier.
   1167   switch (TSFlags & X86II::Op0Mask) {
   1168   case X86II::T8XS:  // F3 0F 38
   1169   case X86II::T8XD:  // F2 0F 38
   1170   case X86II::T8:    // 0F 38
   1171     EmitByte(0x38, CurByte, OS);
   1172     break;
   1173   case X86II::TAXD:  // F2 0F 3A
   1174   case X86II::TA:    // 0F 3A
   1175     EmitByte(0x3A, CurByte, OS);
   1176     break;
   1177   case X86II::A6:    // 0F A6
   1178     EmitByte(0xA6, CurByte, OS);
   1179     break;
   1180   case X86II::A7:    // 0F A7
   1181     EmitByte(0xA7, CurByte, OS);
   1182     break;
   1183   }
   1184 }
   1185 
   1186 void X86MCCodeEmitter::
   1187 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
   1188                   SmallVectorImpl<MCFixup> &Fixups) const {
   1189   unsigned Opcode = MI.getOpcode();
   1190   const MCInstrDesc &Desc = MCII.get(Opcode);
   1191   uint64_t TSFlags = Desc.TSFlags;
   1192 
   1193   // Pseudo instructions don't get encoded.
   1194   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
   1195     return;
   1196 
   1197   unsigned NumOps = Desc.getNumOperands();
   1198   unsigned CurOp = X86II::getOperandBias(Desc);
   1199 
   1200   // Keep track of the current byte being emitted.
   1201   unsigned CurByte = 0;
   1202 
   1203   // Is this instruction encoded using the AVX VEX prefix?
   1204   bool HasVEXPrefix = (TSFlags >> X86II::VEXShift) & X86II::VEX;
   1205 
   1206   // It uses the VEX.VVVV field?
   1207   bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
   1208   bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
   1209   bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
   1210   const unsigned MemOp4_I8IMMOperand = 2;
   1211 
   1212   // It uses the EVEX.aaa field?
   1213   bool HasEVEX = (TSFlags >> X86II::VEXShift) & X86II::EVEX;
   1214   bool HasEVEX_K = HasEVEX && ((TSFlags >> X86II::VEXShift) & X86II::EVEX_K);
   1215 
   1216   // Determine where the memory operand starts, if present.
   1217   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags, Opcode);
   1218   if (MemoryOperand != -1) MemoryOperand += CurOp;
   1219 
   1220   if (!HasVEXPrefix)
   1221     EmitOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
   1222   else
   1223     EmitVEXOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
   1224 
   1225   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
   1226 
   1227   if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
   1228     BaseOpcode = 0x0F;   // Weird 3DNow! encoding.
   1229 
   1230   unsigned SrcRegNum = 0;
   1231   switch (TSFlags & X86II::FormMask) {
   1232   case X86II::MRMInitReg:
   1233     llvm_unreachable("FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
   1234   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
   1235     llvm_unreachable("Unknown FormMask value in X86MCCodeEmitter!");
   1236   case X86II::Pseudo:
   1237     llvm_unreachable("Pseudo instruction shouldn't be emitted");
   1238   case X86II::RawFrm:
   1239     EmitByte(BaseOpcode, CurByte, OS);
   1240     break;
   1241   case X86II::RawFrmImm8:
   1242     EmitByte(BaseOpcode, CurByte, OS);
   1243     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
   1244                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
   1245                   CurByte, OS, Fixups);
   1246     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 1, FK_Data_1, CurByte,
   1247                   OS, Fixups);
   1248     break;
   1249   case X86II::RawFrmImm16:
   1250     EmitByte(BaseOpcode, CurByte, OS);
   1251     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
   1252                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
   1253                   CurByte, OS, Fixups);
   1254     EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 2, FK_Data_2, CurByte,
   1255                   OS, Fixups);
   1256     break;
   1257 
   1258   case X86II::AddRegFrm:
   1259     EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
   1260     break;
   1261 
   1262   case X86II::MRMDestReg:
   1263     EmitByte(BaseOpcode, CurByte, OS);
   1264     SrcRegNum = CurOp + 1;
   1265 
   1266     if (HasEVEX_K) // Skip writemask
   1267       SrcRegNum++;
   1268 
   1269     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
   1270       ++SrcRegNum;
   1271 
   1272     EmitRegModRMByte(MI.getOperand(CurOp),
   1273                      GetX86RegNum(MI.getOperand(SrcRegNum)), CurByte, OS);
   1274     CurOp = SrcRegNum + 1;
   1275     break;
   1276 
   1277   case X86II::MRMDestMem:
   1278     EmitByte(BaseOpcode, CurByte, OS);
   1279     SrcRegNum = CurOp + X86::AddrNumOperands;
   1280 
   1281     if (HasEVEX_K) // Skip writemask
   1282       SrcRegNum++;
   1283 
   1284     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
   1285       ++SrcRegNum;
   1286 
   1287     EmitMemModRMByte(MI, CurOp,
   1288                      GetX86RegNum(MI.getOperand(SrcRegNum)),
   1289                      TSFlags, CurByte, OS, Fixups);
   1290     CurOp = SrcRegNum + 1;
   1291     break;
   1292 
   1293   case X86II::MRMSrcReg:
   1294     EmitByte(BaseOpcode, CurByte, OS);
   1295     SrcRegNum = CurOp + 1;
   1296 
   1297     if (HasEVEX_K) // Skip writemask
   1298       SrcRegNum++;
   1299 
   1300     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
   1301       ++SrcRegNum;
   1302 
   1303     if (HasMemOp4) // Skip 2nd src (which is encoded in I8IMM)
   1304       ++SrcRegNum;
   1305 
   1306     EmitRegModRMByte(MI.getOperand(SrcRegNum),
   1307                      GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
   1308 
   1309     // 2 operands skipped with HasMemOp4, compensate accordingly
   1310     CurOp = HasMemOp4 ? SrcRegNum : SrcRegNum + 1;
   1311     if (HasVEX_4VOp3)
   1312       ++CurOp;
   1313     break;
   1314 
   1315   case X86II::MRMSrcMem: {
   1316     int AddrOperands = X86::AddrNumOperands;
   1317     unsigned FirstMemOp = CurOp+1;
   1318 
   1319     if (HasEVEX_K) { // Skip writemask
   1320       ++AddrOperands;
   1321       ++FirstMemOp;
   1322     }
   1323 
   1324     if (HasVEX_4V) {
   1325       ++AddrOperands;
   1326       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_VVVV).
   1327     }
   1328     if (HasMemOp4) // Skip second register source (encoded in I8IMM)
   1329       ++FirstMemOp;
   1330 
   1331     EmitByte(BaseOpcode, CurByte, OS);
   1332 
   1333     EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
   1334                      TSFlags, CurByte, OS, Fixups);
   1335     CurOp += AddrOperands + 1;
   1336     if (HasVEX_4VOp3)
   1337       ++CurOp;
   1338     break;
   1339   }
   1340 
   1341   case X86II::MRM0r: case X86II::MRM1r:
   1342   case X86II::MRM2r: case X86II::MRM3r:
   1343   case X86II::MRM4r: case X86II::MRM5r:
   1344   case X86II::MRM6r: case X86II::MRM7r:
   1345     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
   1346       ++CurOp;
   1347     EmitByte(BaseOpcode, CurByte, OS);
   1348     EmitRegModRMByte(MI.getOperand(CurOp++),
   1349                      (TSFlags & X86II::FormMask)-X86II::MRM0r,
   1350                      CurByte, OS);
   1351     break;
   1352   case X86II::MRM0m: case X86II::MRM1m:
   1353   case X86II::MRM2m: case X86II::MRM3m:
   1354   case X86II::MRM4m: case X86II::MRM5m:
   1355   case X86II::MRM6m: case X86II::MRM7m:
   1356     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
   1357       ++CurOp;
   1358     EmitByte(BaseOpcode, CurByte, OS);
   1359     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
   1360                      TSFlags, CurByte, OS, Fixups);
   1361     CurOp += X86::AddrNumOperands;
   1362     break;
   1363   case X86II::MRM_C1: case X86II::MRM_C2: case X86II::MRM_C3:
   1364   case X86II::MRM_C4: case X86II::MRM_C8: case X86II::MRM_C9:
   1365   case X86II::MRM_CA: case X86II::MRM_CB: case X86II::MRM_D0:
   1366   case X86II::MRM_D1: case X86II::MRM_D4: case X86II::MRM_D5:
   1367   case X86II::MRM_D6: case X86II::MRM_D8: case X86II::MRM_D9:
   1368   case X86II::MRM_DA: case X86II::MRM_DB: case X86II::MRM_DC:
   1369   case X86II::MRM_DD: case X86II::MRM_DE: case X86II::MRM_DF:
   1370   case X86II::MRM_E8: case X86II::MRM_F0: case X86II::MRM_F8:
   1371   case X86II::MRM_F9:
   1372     EmitByte(BaseOpcode, CurByte, OS);
   1373 
   1374     unsigned char MRM;
   1375     switch (TSFlags & X86II::FormMask) {
   1376     default: llvm_unreachable("Invalid Form");
   1377     case X86II::MRM_C1: MRM = 0xC1; break;
   1378     case X86II::MRM_C2: MRM = 0xC2; break;
   1379     case X86II::MRM_C3: MRM = 0xC3; break;
   1380     case X86II::MRM_C4: MRM = 0xC4; break;
   1381     case X86II::MRM_C8: MRM = 0xC8; break;
   1382     case X86II::MRM_C9: MRM = 0xC9; break;
   1383     case X86II::MRM_CA: MRM = 0xCA; break;
   1384     case X86II::MRM_CB: MRM = 0xCB; break;
   1385     case X86II::MRM_D0: MRM = 0xD0; break;
   1386     case X86II::MRM_D1: MRM = 0xD1; break;
   1387     case X86II::MRM_D4: MRM = 0xD4; break;
   1388     case X86II::MRM_D5: MRM = 0xD5; break;
   1389     case X86II::MRM_D6: MRM = 0xD6; break;
   1390     case X86II::MRM_D8: MRM = 0xD8; break;
   1391     case X86II::MRM_D9: MRM = 0xD9; break;
   1392     case X86II::MRM_DA: MRM = 0xDA; break;
   1393     case X86II::MRM_DB: MRM = 0xDB; break;
   1394     case X86II::MRM_DC: MRM = 0xDC; break;
   1395     case X86II::MRM_DD: MRM = 0xDD; break;
   1396     case X86II::MRM_DE: MRM = 0xDE; break;
   1397     case X86II::MRM_DF: MRM = 0xDF; break;
   1398     case X86II::MRM_E8: MRM = 0xE8; break;
   1399     case X86II::MRM_F0: MRM = 0xF0; break;
   1400     case X86II::MRM_F8: MRM = 0xF8; break;
   1401     case X86II::MRM_F9: MRM = 0xF9; break;
   1402     }
   1403     EmitByte(MRM, CurByte, OS);
   1404     break;
   1405   }
   1406 
   1407   // If there is a remaining operand, it must be a trailing immediate.  Emit it
   1408   // according to the right size for the instruction. Some instructions
   1409   // (SSE4a extrq and insertq) have two trailing immediates.
   1410   while (CurOp != NumOps && NumOps - CurOp <= 2) {
   1411     // The last source register of a 4 operand instruction in AVX is encoded
   1412     // in bits[7:4] of a immediate byte.
   1413     if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM) {
   1414       const MCOperand &MO = MI.getOperand(HasMemOp4 ? MemOp4_I8IMMOperand
   1415                                                     : CurOp);
   1416       ++CurOp;
   1417       unsigned RegNum = GetX86RegNum(MO) << 4;
   1418       if (X86II::isX86_64ExtendedReg(MO.getReg()))
   1419         RegNum |= 1 << 7;
   1420       // If there is an additional 5th operand it must be an immediate, which
   1421       // is encoded in bits[3:0]
   1422       if (CurOp != NumOps) {
   1423         const MCOperand &MIMM = MI.getOperand(CurOp++);
   1424         if (MIMM.isImm()) {
   1425           unsigned Val = MIMM.getImm();
   1426           assert(Val < 16 && "Immediate operand value out of range");
   1427           RegNum |= Val;
   1428         }
   1429       }
   1430       EmitImmediate(MCOperand::CreateImm(RegNum), MI.getLoc(), 1, FK_Data_1,
   1431                     CurByte, OS, Fixups);
   1432     } else {
   1433       unsigned FixupKind;
   1434       // FIXME: Is there a better way to know that we need a signed relocation?
   1435       if (MI.getOpcode() == X86::ADD64ri32 ||
   1436           MI.getOpcode() == X86::MOV64ri32 ||
   1437           MI.getOpcode() == X86::MOV64mi32 ||
   1438           MI.getOpcode() == X86::PUSH64i32)
   1439         FixupKind = X86::reloc_signed_4byte;
   1440       else
   1441         FixupKind = getImmFixupKind(TSFlags);
   1442       EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
   1443                     X86II::getSizeOfImm(TSFlags), MCFixupKind(FixupKind),
   1444                     CurByte, OS, Fixups);
   1445     }
   1446   }
   1447 
   1448   if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
   1449     EmitByte(X86II::getBaseOpcodeFor(TSFlags), CurByte, OS);
   1450 
   1451 #ifndef NDEBUG
   1452   // FIXME: Verify.
   1453   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
   1454     errs() << "Cannot encode all operands of: ";
   1455     MI.dump();
   1456     errs() << '\n';
   1457     abort();
   1458   }
   1459 #endif
   1460 }
   1461