6c7b386f2d107eb294fbad8739515f6a75178291
[oota-llvm.git] / lib / Target / X86 / MCTargetDesc / X86MCCodeEmitter.cpp
1 //===-- X86/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/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Support/raw_ostream.h"
26
27 using namespace llvm;
28
29 namespace {
30 class X86MCCodeEmitter : public MCCodeEmitter {
31   X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
32   void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
33   const MCInstrInfo &MCII;
34   const MCSubtargetInfo &STI;
35   MCContext &Ctx;
36 public:
37   X86MCCodeEmitter(const MCInstrInfo &mcii, const MCSubtargetInfo &sti,
38                    MCContext &ctx)
39     : MCII(mcii), STI(sti), Ctx(ctx) {
40   }
41
42   ~X86MCCodeEmitter() {}
43
44   bool is64BitMode() const {
45     // FIXME: Can tablegen auto-generate this?
46     return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
47   }
48
49   static unsigned GetX86RegNum(const MCOperand &MO) {
50     return X86_MC::getX86RegNum(MO.getReg());
51   }
52
53   // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
54   // 0-7 and the difference between the 2 groups is given by the REX prefix.
55   // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
56   // in 1's complement form, example:
57   //
58   //  ModRM field => XMM9 => 1
59   //  VEX.VVVV    => XMM9 => ~9
60   //
61   // See table 4-35 of Intel AVX Programming Reference for details.
62   static unsigned char getVEXRegisterEncoding(const MCInst &MI,
63                                               unsigned OpNum) {
64     unsigned SrcReg = MI.getOperand(OpNum).getReg();
65     unsigned SrcRegNum = GetX86RegNum(MI.getOperand(OpNum));
66     if ((SrcReg >= X86::XMM8 && SrcReg <= X86::XMM15) ||
67         (SrcReg >= X86::YMM8 && SrcReg <= X86::YMM15))
68       SrcRegNum += 8;
69
70     // The registers represented through VEX_VVVV should
71     // be encoded in 1's complement form.
72     return (~SrcRegNum) & 0xf;
73   }
74
75   void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
76     OS << (char)C;
77     ++CurByte;
78   }
79
80   void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
81                     raw_ostream &OS) const {
82     // Output the constant in little endian byte order.
83     for (unsigned i = 0; i != Size; ++i) {
84       EmitByte(Val & 255, CurByte, OS);
85       Val >>= 8;
86     }
87   }
88
89   void EmitImmediate(const MCOperand &Disp,
90                      unsigned ImmSize, MCFixupKind FixupKind,
91                      unsigned &CurByte, raw_ostream &OS,
92                      SmallVectorImpl<MCFixup> &Fixups,
93                      int ImmOffset = 0) const;
94
95   inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
96                                         unsigned RM) {
97     assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
98     return RM | (RegOpcode << 3) | (Mod << 6);
99   }
100
101   void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
102                         unsigned &CurByte, raw_ostream &OS) const {
103     EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
104   }
105
106   void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
107                    unsigned &CurByte, raw_ostream &OS) const {
108     // SIB byte is in the same format as the ModRMByte.
109     EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
110   }
111
112
113   void EmitMemModRMByte(const MCInst &MI, unsigned Op,
114                         unsigned RegOpcodeField,
115                         uint64_t TSFlags, unsigned &CurByte, raw_ostream &OS,
116                         SmallVectorImpl<MCFixup> &Fixups) const;
117
118   void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
119                          SmallVectorImpl<MCFixup> &Fixups) const;
120
121   void EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
122                            const MCInst &MI, const MCInstrDesc &Desc,
123                            raw_ostream &OS) const;
124
125   void EmitSegmentOverridePrefix(uint64_t TSFlags, unsigned &CurByte,
126                                  int MemOperand, const MCInst &MI,
127                                  raw_ostream &OS) const;
128
129   void EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
130                         const MCInst &MI, const MCInstrDesc &Desc,
131                         raw_ostream &OS) const;
132 };
133
134 } // end anonymous namespace
135
136
137 MCCodeEmitter *llvm::createX86MCCodeEmitter(const MCInstrInfo &MCII,
138                                             const MCSubtargetInfo &STI,
139                                             MCContext &Ctx) {
140   return new X86MCCodeEmitter(MCII, STI, Ctx);
141 }
142
143 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
144 /// sign-extended field.
145 static bool isDisp8(int Value) {
146   return Value == (signed char)Value;
147 }
148
149 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
150 /// in an 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   return MCFixup::getKindForSize(Size, isPCRel);
156 }
157
158 /// Is32BitMemOperand - Return true if the specified instruction with a memory
159 /// operand should emit the 0x67 prefix byte in 64-bit mode due to a 32-bit
160 /// memory operand.  Op specifies the operand # of the memoperand.
161 static bool Is32BitMemOperand(const MCInst &MI, unsigned Op) {
162   const MCOperand &BaseReg  = MI.getOperand(Op+X86::AddrBaseReg);
163   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
164   
165   if ((BaseReg.getReg() != 0 &&
166        X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
167       (IndexReg.getReg() != 0 &&
168        X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
169     return true;
170   return false;
171 }
172
173 /// StartsWithGlobalOffsetTable - Return true for the simple cases where this
174 /// expression starts with _GLOBAL_OFFSET_TABLE_. This is a needed to support
175 /// PIC on ELF i386 as that symbol is magic. We check only simple case that
176 /// are know to be used: _GLOBAL_OFFSET_TABLE_ by itself or at the start
177 /// of a binary expression.
178 static bool StartsWithGlobalOffsetTable(const MCExpr *Expr) {
179   if (Expr->getKind() == MCExpr::Binary) {
180     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Expr);
181     Expr = BE->getLHS();
182   }
183
184   if (Expr->getKind() != MCExpr::SymbolRef)
185     return false;
186
187   const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Expr);
188   const MCSymbol &S = Ref->getSymbol();
189   return S.getName() == "_GLOBAL_OFFSET_TABLE_";
190 }
191
192 void X86MCCodeEmitter::
193 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
194               unsigned &CurByte, raw_ostream &OS,
195               SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
196   const MCExpr *Expr = NULL;
197   if (DispOp.isImm()) {
198     // If this is a simple integer displacement that doesn't require a relocation,
199     // emit it now.
200     if (FixupKind != FK_PCRel_1 &&
201         FixupKind != FK_PCRel_2 &&
202         FixupKind != FK_PCRel_4) {
203       EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
204       return;
205     }
206     Expr = MCConstantExpr::Create(DispOp.getImm(), Ctx);
207   } else {
208     Expr = DispOp.getExpr();
209   }
210
211   // If we have an immoffset, add it to the expression.
212   if ((FixupKind == FK_Data_4 ||
213        FixupKind == MCFixupKind(X86::reloc_signed_4byte)) &&
214       StartsWithGlobalOffsetTable(Expr)) {
215     assert(ImmOffset == 0);
216
217     FixupKind = MCFixupKind(X86::reloc_global_offset_table);
218     ImmOffset = CurByte;
219   }
220
221   // If the fixup is pc-relative, we need to bias the value to be relative to
222   // the start of the field, not the end of the field.
223   if (FixupKind == FK_PCRel_4 ||
224       FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
225       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load))
226     ImmOffset -= 4;
227   if (FixupKind == FK_PCRel_2)
228     ImmOffset -= 2;
229   if (FixupKind == FK_PCRel_1)
230     ImmOffset -= 1;
231
232   if (ImmOffset)
233     Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(ImmOffset, Ctx),
234                                    Ctx);
235
236   // Emit a symbolic constant as a fixup and 4 zeros.
237   Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
238   EmitConstant(0, Size, CurByte, OS);
239 }
240
241 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
242                                         unsigned RegOpcodeField,
243                                         uint64_t TSFlags, unsigned &CurByte,
244                                         raw_ostream &OS,
245                                         SmallVectorImpl<MCFixup> &Fixups) const{
246   const MCOperand &Disp     = MI.getOperand(Op+X86::AddrDisp);
247   const MCOperand &Base     = MI.getOperand(Op+X86::AddrBaseReg);
248   const MCOperand &Scale    = MI.getOperand(Op+X86::AddrScaleAmt);
249   const MCOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
250   unsigned BaseReg = Base.getReg();
251
252   // Handle %rip relative addressing.
253   if (BaseReg == X86::RIP) {    // [disp32+RIP] in X86-64 mode
254     assert(is64BitMode() && "Rip-relative addressing requires 64-bit mode");
255     assert(IndexReg.getReg() == 0 && "Invalid rip-relative address");
256     EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
257
258     unsigned FixupKind = X86::reloc_riprel_4byte;
259
260     // movq loads are handled with a special relocation form which allows the
261     // linker to eliminate some loads for GOT references which end up in the
262     // same linkage unit.
263     if (MI.getOpcode() == X86::MOV64rm)
264       FixupKind = X86::reloc_riprel_4byte_movq_load;
265
266     // rip-relative addressing is actually relative to the *next* instruction.
267     // Since an immediate can follow the mod/rm byte for an instruction, this
268     // means that we need to bias the immediate field of the instruction with
269     // the size of the immediate field.  If we have this case, add it into the
270     // expression to emit.
271     int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
272
273     EmitImmediate(Disp, 4, MCFixupKind(FixupKind),
274                   CurByte, OS, Fixups, -ImmSize);
275     return;
276   }
277
278   unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
279
280   // Determine whether a SIB byte is needed.
281   // If no BaseReg, issue a RIP relative instruction only if the MCE can
282   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
283   // 2-7) and absolute references.
284
285   if (// The SIB byte must be used if there is an index register.
286       IndexReg.getReg() == 0 &&
287       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
288       // encode to an R/M value of 4, which indicates that a SIB byte is
289       // present.
290       BaseRegNo != N86::ESP &&
291       // If there is no base register and we're in 64-bit mode, we need a SIB
292       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
293       (!is64BitMode() || BaseReg != 0)) {
294
295     if (BaseReg == 0) {          // [disp32]     in X86-32 mode
296       EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
297       EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
298       return;
299     }
300
301     // If the base is not EBP/ESP and there is no displacement, use simple
302     // indirect register encoding, this handles addresses like [EAX].  The
303     // encoding for [EBP] with no displacement means [disp32] so we handle it
304     // by emitting a displacement of 0 below.
305     if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
306       EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
307       return;
308     }
309
310     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
311     if (Disp.isImm() && isDisp8(Disp.getImm())) {
312       EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
313       EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
314       return;
315     }
316
317     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
318     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
319     EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, OS,
320                   Fixups);
321     return;
322   }
323
324   // We need a SIB byte, so start by outputting the ModR/M byte first
325   assert(IndexReg.getReg() != X86::ESP &&
326          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
327
328   bool ForceDisp32 = false;
329   bool ForceDisp8  = false;
330   if (BaseReg == 0) {
331     // If there is no base register, we emit the special case SIB byte with
332     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
333     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
334     ForceDisp32 = true;
335   } else if (!Disp.isImm()) {
336     // Emit the normal disp32 encoding.
337     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
338     ForceDisp32 = true;
339   } else if (Disp.getImm() == 0 &&
340              // Base reg can't be anything that ends up with '5' as the base
341              // reg, it is the magic [*] nomenclature that indicates no base.
342              BaseRegNo != N86::EBP) {
343     // Emit no displacement ModR/M byte
344     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
345   } else if (isDisp8(Disp.getImm())) {
346     // Emit the disp8 encoding.
347     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
348     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
349   } else {
350     // Emit the normal disp32 encoding.
351     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
352   }
353
354   // Calculate what the SS field value should be...
355   static const unsigned SSTable[] = { ~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3 };
356   unsigned SS = SSTable[Scale.getImm()];
357
358   if (BaseReg == 0) {
359     // Handle the SIB byte for the case where there is no base, see Intel
360     // Manual 2A, table 2-7. The displacement has already been output.
361     unsigned IndexRegNo;
362     if (IndexReg.getReg())
363       IndexRegNo = GetX86RegNum(IndexReg);
364     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
365       IndexRegNo = 4;
366     EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
367   } else {
368     unsigned IndexRegNo;
369     if (IndexReg.getReg())
370       IndexRegNo = GetX86RegNum(IndexReg);
371     else
372       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
373     EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
374   }
375
376   // Do we need to output a displacement?
377   if (ForceDisp8)
378     EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
379   else if (ForceDisp32 || Disp.getImm() != 0)
380     EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, OS,
381                   Fixups);
382 }
383
384 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode prefix
385 /// called VEX.
386 void X86MCCodeEmitter::EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
387                                            int MemOperand, const MCInst &MI,
388                                            const MCInstrDesc &Desc,
389                                            raw_ostream &OS) const {
390   bool HasVEX_4V = false;
391   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_4V)
392     HasVEX_4V = true;
393
394   // VEX_R: opcode externsion equivalent to REX.R in
395   // 1's complement (inverted) form
396   //
397   //  1: Same as REX_R=0 (must be 1 in 32-bit mode)
398   //  0: Same as REX_R=1 (64 bit mode only)
399   //
400   unsigned char VEX_R = 0x1;
401
402   // VEX_X: equivalent to REX.X, only used when a
403   // register is used for index in SIB Byte.
404   //
405   //  1: Same as REX.X=0 (must be 1 in 32-bit mode)
406   //  0: Same as REX.X=1 (64-bit mode only)
407   unsigned char VEX_X = 0x1;
408
409   // VEX_B:
410   //
411   //  1: Same as REX_B=0 (ignored in 32-bit mode)
412   //  0: Same as REX_B=1 (64 bit mode only)
413   //
414   unsigned char VEX_B = 0x1;
415
416   // VEX_W: opcode specific (use like REX.W, or used for
417   // opcode extension, or ignored, depending on the opcode byte)
418   unsigned char VEX_W = 0;
419
420   // VEX_5M (VEX m-mmmmm field):
421   //
422   //  0b00000: Reserved for future use
423   //  0b00001: implied 0F leading opcode
424   //  0b00010: implied 0F 38 leading opcode bytes
425   //  0b00011: implied 0F 3A leading opcode bytes
426   //  0b00100-0b11111: Reserved for future use
427   //
428   unsigned char VEX_5M = 0x1;
429
430   // VEX_4V (VEX vvvv field): a register specifier
431   // (in 1's complement form) or 1111 if unused.
432   unsigned char VEX_4V = 0xf;
433
434   // VEX_L (Vector Length):
435   //
436   //  0: scalar or 128-bit vector
437   //  1: 256-bit vector
438   //
439   unsigned char VEX_L = 0;
440
441   // VEX_PP: opcode extension providing equivalent
442   // functionality of a SIMD prefix
443   //
444   //  0b00: None
445   //  0b01: 66
446   //  0b10: F3
447   //  0b11: F2
448   //
449   unsigned char VEX_PP = 0;
450
451   // Encode the operand size opcode prefix as needed.
452   if (TSFlags & X86II::OpSize)
453     VEX_PP = 0x01;
454
455   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
456     VEX_W = 1;
457
458   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
459     VEX_L = 1;
460
461   switch (TSFlags & X86II::Op0Mask) {
462   default: assert(0 && "Invalid prefix!");
463   case X86II::T8:  // 0F 38
464     VEX_5M = 0x2;
465     break;
466   case X86II::TA:  // 0F 3A
467     VEX_5M = 0x3;
468     break;
469   case X86II::TF:  // F2 0F 38
470     VEX_PP = 0x3;
471     VEX_5M = 0x2;
472     break;
473   case X86II::XS:  // F3 0F
474     VEX_PP = 0x2;
475     break;
476   case X86II::XD:  // F2 0F
477     VEX_PP = 0x3;
478     break;
479   case X86II::A6:  // Bypass: Not used by VEX
480   case X86II::A7:  // Bypass: Not used by VEX
481   case X86II::TB:  // Bypass: Not used by VEX
482   case 0:
483     break;  // No prefix!
484   }
485
486   // Set the vector length to 256-bit if YMM0-YMM15 is used
487   for (unsigned i = 0; i != MI.getNumOperands(); ++i) {
488     if (!MI.getOperand(i).isReg())
489       continue;
490     unsigned SrcReg = MI.getOperand(i).getReg();
491     if (SrcReg >= X86::YMM0 && SrcReg <= X86::YMM15)
492       VEX_L = 1;
493   }
494
495   unsigned NumOps = MI.getNumOperands();
496   unsigned CurOp = 0;
497   bool IsDestMem = false;
498
499   switch (TSFlags & X86II::FormMask) {
500   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
501   case X86II::MRMDestMem:
502     IsDestMem = true;
503     // The important info for the VEX prefix is never beyond the address
504     // registers. Don't check beyond that.
505     NumOps = CurOp = X86::AddrNumOperands;
506   case X86II::MRM0m: case X86II::MRM1m:
507   case X86II::MRM2m: case X86II::MRM3m:
508   case X86II::MRM4m: case X86II::MRM5m:
509   case X86II::MRM6m: case X86II::MRM7m:
510   case X86II::MRMSrcMem:
511   case X86II::MRMSrcReg:
512     if (MI.getNumOperands() > CurOp && MI.getOperand(CurOp).isReg() &&
513         X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
514       VEX_R = 0x0;
515     CurOp++;
516
517     if (HasVEX_4V) {
518       VEX_4V = getVEXRegisterEncoding(MI, IsDestMem ? CurOp-1 : CurOp);
519       CurOp++;
520     }
521
522     // To only check operands before the memory address ones, start
523     // the search from the beginning
524     if (IsDestMem)
525       CurOp = 0;
526
527     // If the last register should be encoded in the immediate field
528     // do not use any bit from VEX prefix to this register, ignore it
529     if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM)
530       NumOps--;
531
532     for (; CurOp != NumOps; ++CurOp) {
533       const MCOperand &MO = MI.getOperand(CurOp);
534       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
535         VEX_B = 0x0;
536       // Only set VEX_X if the Index Register is extended
537       if (VEX_B || !MO.isReg())
538         continue;
539       if (!X86II::isX86_64ExtendedReg(MO.getReg()))
540         continue;
541       unsigned Frm = TSFlags & X86II::FormMask;
542       if ((Frm == X86II::MRMSrcMem && CurOp-1 == X86::AddrIndexReg) ||
543           (Frm == X86II::MRMDestMem && CurOp == X86::AddrIndexReg))
544         VEX_X = 0x0;
545     }
546     break;
547   default: // MRMDestReg, MRM0r-MRM7r, RawFrm
548     if (!MI.getNumOperands())
549       break;
550
551     if (MI.getOperand(CurOp).isReg() &&
552         X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
553       VEX_B = 0;
554
555     if (HasVEX_4V)
556       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
557
558     CurOp++;
559     for (; CurOp != NumOps; ++CurOp) {
560       const MCOperand &MO = MI.getOperand(CurOp);
561       if (MO.isReg() && !HasVEX_4V &&
562           X86II::isX86_64ExtendedReg(MO.getReg()))
563         VEX_R = 0x0;
564     }
565     break;
566   }
567
568   // Emit segment override opcode prefix as needed.
569   EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
570
571   // VEX opcode prefix can have 2 or 3 bytes
572   //
573   //  3 bytes:
574   //    +-----+ +--------------+ +-------------------+
575   //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
576   //    +-----+ +--------------+ +-------------------+
577   //  2 bytes:
578   //    +-----+ +-------------------+
579   //    | C5h | | R | vvvv | L | pp |
580   //    +-----+ +-------------------+
581   //
582   unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
583
584   if (VEX_B && VEX_X && !VEX_W && (VEX_5M == 1)) { // 2 byte VEX prefix
585     EmitByte(0xC5, CurByte, OS);
586     EmitByte(LastByte | (VEX_R << 7), CurByte, OS);
587     return;
588   }
589
590   // 3 byte VEX prefix
591   EmitByte(0xC4, CurByte, OS);
592   EmitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, CurByte, OS);
593   EmitByte(LastByte | (VEX_W << 7), CurByte, OS);
594 }
595
596 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
597 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
598 /// size, and 3) use of X86-64 extended registers.
599 static unsigned DetermineREXPrefix(const MCInst &MI, uint64_t TSFlags,
600                                    const MCInstrDesc &Desc) {
601   unsigned REX = 0;
602   if (TSFlags & X86II::REX_W)
603     REX |= 1 << 3; // set REX.W
604
605   if (MI.getNumOperands() == 0) return REX;
606
607   unsigned NumOps = MI.getNumOperands();
608   // FIXME: MCInst should explicitize the two-addrness.
609   bool isTwoAddr = NumOps > 1 &&
610                       Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1;
611
612   // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
613   unsigned i = isTwoAddr ? 1 : 0;
614   for (; i != NumOps; ++i) {
615     const MCOperand &MO = MI.getOperand(i);
616     if (!MO.isReg()) continue;
617     unsigned Reg = MO.getReg();
618     if (!X86II::isX86_64NonExtLowByteReg(Reg)) continue;
619     // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
620     // that returns non-zero.
621     REX |= 0x40; // REX fixed encoding prefix
622     break;
623   }
624
625   switch (TSFlags & X86II::FormMask) {
626   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
627   case X86II::MRMSrcReg:
628     if (MI.getOperand(0).isReg() &&
629         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
630       REX |= 1 << 2; // set REX.R
631     i = isTwoAddr ? 2 : 1;
632     for (; i != NumOps; ++i) {
633       const MCOperand &MO = MI.getOperand(i);
634       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
635         REX |= 1 << 0; // set REX.B
636     }
637     break;
638   case X86II::MRMSrcMem: {
639     if (MI.getOperand(0).isReg() &&
640         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
641       REX |= 1 << 2; // set REX.R
642     unsigned Bit = 0;
643     i = isTwoAddr ? 2 : 1;
644     for (; i != NumOps; ++i) {
645       const MCOperand &MO = MI.getOperand(i);
646       if (MO.isReg()) {
647         if (X86II::isX86_64ExtendedReg(MO.getReg()))
648           REX |= 1 << Bit; // set REX.B (Bit=0) and REX.X (Bit=1)
649         Bit++;
650       }
651     }
652     break;
653   }
654   case X86II::MRM0m: case X86II::MRM1m:
655   case X86II::MRM2m: case X86II::MRM3m:
656   case X86II::MRM4m: case X86II::MRM5m:
657   case X86II::MRM6m: case X86II::MRM7m:
658   case X86II::MRMDestMem: {
659     unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
660     i = isTwoAddr ? 1 : 0;
661     if (NumOps > e && MI.getOperand(e).isReg() &&
662         X86II::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
663       REX |= 1 << 2; // set REX.R
664     unsigned Bit = 0;
665     for (; i != e; ++i) {
666       const MCOperand &MO = MI.getOperand(i);
667       if (MO.isReg()) {
668         if (X86II::isX86_64ExtendedReg(MO.getReg()))
669           REX |= 1 << Bit; // REX.B (Bit=0) and REX.X (Bit=1)
670         Bit++;
671       }
672     }
673     break;
674   }
675   default:
676     if (MI.getOperand(0).isReg() &&
677         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
678       REX |= 1 << 0; // set REX.B
679     i = isTwoAddr ? 2 : 1;
680     for (unsigned e = NumOps; i != e; ++i) {
681       const MCOperand &MO = MI.getOperand(i);
682       if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
683         REX |= 1 << 2; // set REX.R
684     }
685     break;
686   }
687   return REX;
688 }
689
690 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
691 void X86MCCodeEmitter::EmitSegmentOverridePrefix(uint64_t TSFlags,
692                                         unsigned &CurByte, int MemOperand,
693                                         const MCInst &MI,
694                                         raw_ostream &OS) const {
695   switch (TSFlags & X86II::SegOvrMask) {
696   default: assert(0 && "Invalid segment!");
697   case 0:
698     // No segment override, check for explicit one on memory operand.
699     if (MemOperand != -1) {   // If the instruction has a memory operand.
700       switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
701       default: assert(0 && "Unknown segment register!");
702       case 0: break;
703       case X86::CS: EmitByte(0x2E, CurByte, OS); break;
704       case X86::SS: EmitByte(0x36, CurByte, OS); break;
705       case X86::DS: EmitByte(0x3E, CurByte, OS); break;
706       case X86::ES: EmitByte(0x26, CurByte, OS); break;
707       case X86::FS: EmitByte(0x64, CurByte, OS); break;
708       case X86::GS: EmitByte(0x65, CurByte, OS); break;
709       }
710     }
711     break;
712   case X86II::FS:
713     EmitByte(0x64, CurByte, OS);
714     break;
715   case X86II::GS:
716     EmitByte(0x65, CurByte, OS);
717     break;
718   }
719 }
720
721 /// EmitOpcodePrefix - Emit all instruction prefixes prior to the opcode.
722 ///
723 /// MemOperand is the operand # of the start of a memory operand if present.  If
724 /// Not present, it is -1.
725 void X86MCCodeEmitter::EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
726                                         int MemOperand, const MCInst &MI,
727                                         const MCInstrDesc &Desc,
728                                         raw_ostream &OS) const {
729
730   // Emit the lock opcode prefix as needed.
731   if (TSFlags & X86II::LOCK)
732     EmitByte(0xF0, CurByte, OS);
733
734   // Emit segment override opcode prefix as needed.
735   EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
736
737   // Emit the repeat opcode prefix as needed.
738   if ((TSFlags & X86II::Op0Mask) == X86II::REP)
739     EmitByte(0xF3, CurByte, OS);
740
741   // Emit the address size opcode prefix as needed.
742   if ((TSFlags & X86II::AdSize) ||
743       (MemOperand != -1 && is64BitMode() && Is32BitMemOperand(MI, MemOperand)))
744     EmitByte(0x67, CurByte, OS);
745   
746   // Emit the operand size opcode prefix as needed.
747   if (TSFlags & X86II::OpSize)
748     EmitByte(0x66, CurByte, OS);
749
750   bool Need0FPrefix = false;
751   switch (TSFlags & X86II::Op0Mask) {
752   default: assert(0 && "Invalid prefix!");
753   case 0: break;  // No prefix!
754   case X86II::REP: break; // already handled.
755   case X86II::TB:  // Two-byte opcode prefix
756   case X86II::T8:  // 0F 38
757   case X86II::TA:  // 0F 3A
758   case X86II::A6:  // 0F A6
759   case X86II::A7:  // 0F A7
760     Need0FPrefix = true;
761     break;
762   case X86II::TF: // F2 0F 38
763     EmitByte(0xF2, CurByte, OS);
764     Need0FPrefix = true;
765     break;
766   case X86II::XS:   // F3 0F
767     EmitByte(0xF3, CurByte, OS);
768     Need0FPrefix = true;
769     break;
770   case X86II::XD:   // F2 0F
771     EmitByte(0xF2, CurByte, OS);
772     Need0FPrefix = true;
773     break;
774   case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
775   case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
776   case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
777   case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
778   case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
779   case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
780   case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
781   case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
782   }
783
784   // Handle REX prefix.
785   // FIXME: Can this come before F2 etc to simplify emission?
786   if (is64BitMode()) {
787     if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
788       EmitByte(0x40 | REX, CurByte, OS);
789   }
790
791   // 0x0F escape code must be emitted just before the opcode.
792   if (Need0FPrefix)
793     EmitByte(0x0F, CurByte, OS);
794
795   // FIXME: Pull this up into previous switch if REX can be moved earlier.
796   switch (TSFlags & X86II::Op0Mask) {
797   case X86II::TF:    // F2 0F 38
798   case X86II::T8:    // 0F 38
799     EmitByte(0x38, CurByte, OS);
800     break;
801   case X86II::TA:    // 0F 3A
802     EmitByte(0x3A, CurByte, OS);
803     break;
804   case X86II::A6:    // 0F A6
805     EmitByte(0xA6, CurByte, OS);
806     break;
807   case X86II::A7:    // 0F A7
808     EmitByte(0xA7, CurByte, OS);
809     break;
810   }
811 }
812
813 void X86MCCodeEmitter::
814 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
815                   SmallVectorImpl<MCFixup> &Fixups) const {
816   unsigned Opcode = MI.getOpcode();
817   const MCInstrDesc &Desc = MCII.get(Opcode);
818   uint64_t TSFlags = Desc.TSFlags;
819
820   // Pseudo instructions don't get encoded.
821   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
822     return;
823
824   // If this is a two-address instruction, skip one of the register operands.
825   // FIXME: This should be handled during MCInst lowering.
826   unsigned NumOps = Desc.getNumOperands();
827   unsigned CurOp = 0;
828   if (NumOps > 1 && Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1)
829     ++CurOp;
830   else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, MCOI::TIED_TO)== 0)
831     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
832     --NumOps;
833
834   // Keep track of the current byte being emitted.
835   unsigned CurByte = 0;
836
837   // Is this instruction encoded using the AVX VEX prefix?
838   bool HasVEXPrefix = false;
839
840   // It uses the VEX.VVVV field?
841   bool HasVEX_4V = false;
842
843   if ((TSFlags >> X86II::VEXShift) & X86II::VEX)
844     HasVEXPrefix = true;
845   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_4V)
846     HasVEX_4V = true;
847
848   
849   // Determine where the memory operand starts, if present.
850   int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
851   if (MemoryOperand != -1) MemoryOperand += CurOp;
852
853   if (!HasVEXPrefix)
854     EmitOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
855   else
856     EmitVEXOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
857
858   
859   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
860   
861   if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
862     BaseOpcode = 0x0F;   // Weird 3DNow! encoding.
863   
864   unsigned SrcRegNum = 0;
865   switch (TSFlags & X86II::FormMask) {
866   case X86II::MRMInitReg:
867     assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
868   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
869     assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
870   case X86II::Pseudo:
871     assert(0 && "Pseudo instruction shouldn't be emitted");
872   case X86II::RawFrm:
873     EmitByte(BaseOpcode, CurByte, OS);
874     break;
875       
876   case X86II::RawFrmImm8:
877     EmitByte(BaseOpcode, CurByte, OS);
878     EmitImmediate(MI.getOperand(CurOp++),
879                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
880                   CurByte, OS, Fixups);
881     EmitImmediate(MI.getOperand(CurOp++), 1, FK_Data_1, CurByte, OS, Fixups);
882     break;
883   case X86II::RawFrmImm16:
884     EmitByte(BaseOpcode, CurByte, OS);
885     EmitImmediate(MI.getOperand(CurOp++),
886                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
887                   CurByte, OS, Fixups);
888     EmitImmediate(MI.getOperand(CurOp++), 2, FK_Data_2, CurByte, OS, Fixups);
889     break;
890
891   case X86II::AddRegFrm:
892     EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
893     break;
894
895   case X86II::MRMDestReg:
896     EmitByte(BaseOpcode, CurByte, OS);
897     EmitRegModRMByte(MI.getOperand(CurOp),
898                      GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
899     CurOp += 2;
900     break;
901
902   case X86II::MRMDestMem:
903     EmitByte(BaseOpcode, CurByte, OS);
904     SrcRegNum = CurOp + X86::AddrNumOperands;
905
906     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
907       SrcRegNum++;
908
909     EmitMemModRMByte(MI, CurOp,
910                      GetX86RegNum(MI.getOperand(SrcRegNum)),
911                      TSFlags, CurByte, OS, Fixups);
912     CurOp = SrcRegNum + 1;
913     break;
914
915   case X86II::MRMSrcReg:
916     EmitByte(BaseOpcode, CurByte, OS);
917     SrcRegNum = CurOp + 1;
918
919     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
920       SrcRegNum++;
921
922     EmitRegModRMByte(MI.getOperand(SrcRegNum),
923                      GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
924     CurOp = SrcRegNum + 1;
925     break;
926
927   case X86II::MRMSrcMem: {
928     int AddrOperands = X86::AddrNumOperands;
929     unsigned FirstMemOp = CurOp+1;
930     if (HasVEX_4V) {
931       ++AddrOperands;
932       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_VVVV).
933     }
934
935     EmitByte(BaseOpcode, CurByte, OS);
936
937     EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
938                      TSFlags, CurByte, OS, Fixups);
939     CurOp += AddrOperands + 1;
940     break;
941   }
942
943   case X86II::MRM0r: case X86II::MRM1r:
944   case X86II::MRM2r: case X86II::MRM3r:
945   case X86II::MRM4r: case X86II::MRM5r:
946   case X86II::MRM6r: case X86II::MRM7r:
947     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
948       CurOp++;
949     EmitByte(BaseOpcode, CurByte, OS);
950     EmitRegModRMByte(MI.getOperand(CurOp++),
951                      (TSFlags & X86II::FormMask)-X86II::MRM0r,
952                      CurByte, OS);
953     break;
954   case X86II::MRM0m: case X86II::MRM1m:
955   case X86II::MRM2m: case X86II::MRM3m:
956   case X86II::MRM4m: case X86II::MRM5m:
957   case X86II::MRM6m: case X86II::MRM7m:
958     EmitByte(BaseOpcode, CurByte, OS);
959     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
960                      TSFlags, CurByte, OS, Fixups);
961     CurOp += X86::AddrNumOperands;
962     break;
963   case X86II::MRM_C1:
964     EmitByte(BaseOpcode, CurByte, OS);
965     EmitByte(0xC1, CurByte, OS);
966     break;
967   case X86II::MRM_C2:
968     EmitByte(BaseOpcode, CurByte, OS);
969     EmitByte(0xC2, CurByte, OS);
970     break;
971   case X86II::MRM_C3:
972     EmitByte(BaseOpcode, CurByte, OS);
973     EmitByte(0xC3, CurByte, OS);
974     break;
975   case X86II::MRM_C4:
976     EmitByte(BaseOpcode, CurByte, OS);
977     EmitByte(0xC4, CurByte, OS);
978     break;
979   case X86II::MRM_C8:
980     EmitByte(BaseOpcode, CurByte, OS);
981     EmitByte(0xC8, CurByte, OS);
982     break;
983   case X86II::MRM_C9:
984     EmitByte(BaseOpcode, CurByte, OS);
985     EmitByte(0xC9, CurByte, OS);
986     break;
987   case X86II::MRM_E8:
988     EmitByte(BaseOpcode, CurByte, OS);
989     EmitByte(0xE8, CurByte, OS);
990     break;
991   case X86II::MRM_F0:
992     EmitByte(BaseOpcode, CurByte, OS);
993     EmitByte(0xF0, CurByte, OS);
994     break;
995   case X86II::MRM_F8:
996     EmitByte(BaseOpcode, CurByte, OS);
997     EmitByte(0xF8, CurByte, OS);
998     break;
999   case X86II::MRM_F9:
1000     EmitByte(BaseOpcode, CurByte, OS);
1001     EmitByte(0xF9, CurByte, OS);
1002     break;
1003   case X86II::MRM_D0:
1004     EmitByte(BaseOpcode, CurByte, OS);
1005     EmitByte(0xD0, CurByte, OS);
1006     break;
1007   case X86II::MRM_D1:
1008     EmitByte(BaseOpcode, CurByte, OS);
1009     EmitByte(0xD1, CurByte, OS);
1010     break;
1011   }
1012
1013   // If there is a remaining operand, it must be a trailing immediate.  Emit it
1014   // according to the right size for the instruction.
1015   if (CurOp != NumOps) {
1016     // The last source register of a 4 operand instruction in AVX is encoded
1017     // in bits[7:4] of a immediate byte, and bits[3:0] are ignored.
1018     if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM) {
1019       const MCOperand &MO = MI.getOperand(CurOp++);
1020       bool IsExtReg =
1021         X86II::isX86_64ExtendedReg(MO.getReg());
1022       unsigned RegNum = (IsExtReg ? (1 << 7) : 0);
1023       RegNum |= GetX86RegNum(MO) << 4;
1024       EmitImmediate(MCOperand::CreateImm(RegNum), 1, FK_Data_1, CurByte, OS,
1025                     Fixups);
1026     } else {
1027       unsigned FixupKind;
1028       // FIXME: Is there a better way to know that we need a signed relocation?
1029       if (MI.getOpcode() == X86::ADD64ri32 ||
1030           MI.getOpcode() == X86::MOV64ri32 ||
1031           MI.getOpcode() == X86::MOV64mi32 ||
1032           MI.getOpcode() == X86::PUSH64i32)
1033         FixupKind = X86::reloc_signed_4byte;
1034       else
1035         FixupKind = getImmFixupKind(TSFlags);
1036       EmitImmediate(MI.getOperand(CurOp++),
1037                     X86II::getSizeOfImm(TSFlags), MCFixupKind(FixupKind),
1038                     CurByte, OS, Fixups);
1039     }
1040   }
1041
1042   if ((TSFlags >> X86II::VEXShift) & X86II::Has3DNow0F0FOpcode)
1043     EmitByte(X86II::getBaseOpcodeFor(TSFlags), CurByte, OS);
1044   
1045
1046 #ifndef NDEBUG
1047   // FIXME: Verify.
1048   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
1049     errs() << "Cannot encode all operands of: ";
1050     MI.dump();
1051     errs() << '\n';
1052     abort();
1053   }
1054 #endif
1055 }