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