finish up support for callw: PR7195
[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 "x86-emitter"
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/Support/raw_ostream.h"
22 using namespace llvm;
23
24 namespace {
25 class X86MCCodeEmitter : public MCCodeEmitter {
26   X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
27   void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
28   const TargetMachine &TM;
29   const TargetInstrInfo &TII;
30   MCContext &Ctx;
31   bool Is64BitMode;
32 public:
33   X86MCCodeEmitter(TargetMachine &tm, MCContext &ctx, bool is64Bit) 
34     : TM(tm), TII(*TM.getInstrInfo()), Ctx(ctx) {
35     Is64BitMode = is64Bit;
36   }
37
38   ~X86MCCodeEmitter() {}
39
40   unsigned getNumFixupKinds() const {
41     return 5;
42   }
43
44   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
45     const static MCFixupKindInfo Infos[] = {
46       { "reloc_pcrel_4byte", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel },
47       { "reloc_pcrel_1byte", 0, 1 * 8, MCFixupKindInfo::FKF_IsPCRel },
48       { "reloc_pcrel_2byte", 0, 2 * 8, MCFixupKindInfo::FKF_IsPCRel },
49       { "reloc_riprel_4byte", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel },
50       { "reloc_riprel_4byte_movq_load", 0, 4 * 8, MCFixupKindInfo::FKF_IsPCRel }
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       SrcRegNum += 8;
80   
81     // The registers represented through VEX_VVVV should
82     // be encoded in 1's complement form.
83     return (~SrcRegNum) & 0xf;
84   }
85   
86   void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
87     OS << (char)C;
88     ++CurByte;
89   }
90   
91   void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
92                     raw_ostream &OS) const {
93     // Output the constant in little endian byte order.
94     for (unsigned i = 0; i != Size; ++i) {
95       EmitByte(Val & 255, CurByte, OS);
96       Val >>= 8;
97     }
98   }
99
100   void EmitImmediate(const MCOperand &Disp, 
101                      unsigned ImmSize, MCFixupKind FixupKind,
102                      unsigned &CurByte, raw_ostream &OS,
103                      SmallVectorImpl<MCFixup> &Fixups,
104                      int ImmOffset = 0) const;
105   
106   inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
107                                         unsigned RM) {
108     assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
109     return RM | (RegOpcode << 3) | (Mod << 6);
110   }
111   
112   void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
113                         unsigned &CurByte, raw_ostream &OS) const {
114     EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
115   }
116   
117   void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
118                    unsigned &CurByte, raw_ostream &OS) const {
119     // SIB byte is in the same format as the ModRMByte.
120     EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
121   }
122   
123   
124   void EmitSegmentOverridePrefix(const MCOperand &Op, unsigned TSFlags,
125                                  unsigned &CurByte, raw_ostream &OS) const;
126
127   void EmitMemModRMByte(const MCInst &MI, unsigned Op,
128                         unsigned RegOpcodeField, 
129                         uint64_t TSFlags, unsigned &CurByte, raw_ostream &OS,
130                         SmallVectorImpl<MCFixup> &Fixups) const;
131   
132   void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
133                          SmallVectorImpl<MCFixup> &Fixups) const;
134   
135   void EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
136                            const MCInst &MI, const TargetInstrDesc &Desc,
137                            raw_ostream &OS) const;
138
139   void EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
140                         const MCInst &MI, const TargetInstrDesc &Desc,
141                         raw_ostream &OS) const;
142 };
143
144 } // end anonymous namespace
145
146
147 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
148                                                TargetMachine &TM,
149                                                MCContext &Ctx) {
150   return new X86MCCodeEmitter(TM, Ctx, false);
151 }
152
153 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
154                                                TargetMachine &TM,
155                                                MCContext &Ctx) {
156   return new X86MCCodeEmitter(TM, Ctx, true);
157 }
158
159 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
160 /// sign-extended field. 
161 static bool isDisp8(int Value) {
162   return Value == (signed char)Value;
163 }
164
165 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
166 /// in an instruction with the specified TSFlags.
167 static MCFixupKind getImmFixupKind(uint64_t TSFlags) {
168   unsigned Size = X86II::getSizeOfImm(TSFlags);
169   bool isPCRel = X86II::isImmPCRel(TSFlags);
170   
171   switch (Size) {
172   default: assert(0 && "Unknown immediate size");
173   case 1: return isPCRel ? MCFixupKind(X86::reloc_pcrel_1byte) : FK_Data_1;
174   case 2: return isPCRel ? MCFixupKind(X86::reloc_pcrel_2byte) : FK_Data_2;
175   case 4: return isPCRel ? MCFixupKind(X86::reloc_pcrel_4byte) : FK_Data_4;
176   case 8: assert(!isPCRel); return FK_Data_8;
177   }
178 }
179
180
181 void X86MCCodeEmitter::
182 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
183               unsigned &CurByte, raw_ostream &OS,
184               SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
185   // If this is a simple integer displacement that doesn't require a relocation,
186   // emit it now.
187   if (DispOp.isImm()) {
188     // FIXME: is this right for pc-rel encoding??  Probably need to emit this as
189     // a fixup if so.
190     EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
191     return;
192   }
193
194   // If we have an immoffset, add it to the expression.
195   const MCExpr *Expr = DispOp.getExpr();
196   
197   // If the fixup is pc-relative, we need to bias the value to be relative to
198   // the start of the field, not the end of the field.
199   if (FixupKind == MCFixupKind(X86::reloc_pcrel_4byte) ||
200       FixupKind == MCFixupKind(X86::reloc_riprel_4byte) ||
201       FixupKind == MCFixupKind(X86::reloc_riprel_4byte_movq_load))
202     ImmOffset -= 4;
203   if (FixupKind == MCFixupKind(X86::reloc_pcrel_2byte))
204     ImmOffset -= 2;
205   if (FixupKind == MCFixupKind(X86::reloc_pcrel_1byte))
206     ImmOffset -= 1;
207   
208   if (ImmOffset)
209     Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(ImmOffset, Ctx),
210                                    Ctx);
211   
212   // Emit a symbolic constant as a fixup and 4 zeros.
213   Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
214   EmitConstant(0, Size, CurByte, OS);
215 }
216
217 void X86MCCodeEmitter::EmitSegmentOverridePrefix(const MCOperand &Op,
218                                                  unsigned TSFlags,
219                                                  unsigned &CurByte,
220                                                  raw_ostream &OS) const {
221   // If no segment register is present, we don't need anything.
222   if (Op.getReg() == 0)
223     return;
224
225   // Check if we need an override.
226   switch (Op.getReg()) {
227   case X86::CS: EmitByte(0x2E, CurByte, OS); return;
228   case X86::SS: EmitByte(0x36, CurByte, OS); return;
229   case X86::DS: EmitByte(0x3E, CurByte, OS); return;
230   case X86::ES: EmitByte(0x26, CurByte, OS); return;
231   case X86::FS: EmitByte(0x64, CurByte, OS); return;
232   case X86::GS: EmitByte(0x65, CurByte, OS); return;
233   }
234
235   assert(0 && "Invalid segment register!");
236 }
237
238 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
239                                         unsigned RegOpcodeField,
240                                         uint64_t TSFlags, unsigned &CurByte,
241                                         raw_ostream &OS,
242                                         SmallVectorImpl<MCFixup> &Fixups) const{
243   const MCOperand &Disp     = MI.getOperand(Op+3);
244   const MCOperand &Base     = MI.getOperand(Op);
245   const MCOperand &Scale    = MI.getOperand(Op+1);
246   const MCOperand &IndexReg = MI.getOperand(Op+2);
247   unsigned BaseReg = Base.getReg();
248   
249   // Handle %rip relative addressing.
250   if (BaseReg == X86::RIP) {    // [disp32+RIP] in X86-64 mode
251     assert(Is64BitMode && "Rip-relative addressing requires 64-bit mode");
252     assert(IndexReg.getReg() == 0 && "Invalid rip-relative address");
253     EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
254     
255     unsigned FixupKind = X86::reloc_riprel_4byte;
256     
257     // movq loads are handled with a special relocation form which allows the
258     // linker to eliminate some loads for GOT references which end up in the
259     // same linkage unit.
260     if (MI.getOpcode() == X86::MOV64rm ||
261         MI.getOpcode() == X86::MOV64rm_TC)
262       FixupKind = X86::reloc_riprel_4byte_movq_load;
263     
264     // rip-relative addressing is actually relative to the *next* instruction.
265     // Since an immediate can follow the mod/rm byte for an instruction, this
266     // means that we need to bias the immediate field of the instruction with
267     // the size of the immediate field.  If we have this case, add it into the
268     // expression to emit.
269     int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
270     
271     EmitImmediate(Disp, 4, MCFixupKind(FixupKind),
272                   CurByte, OS, Fixups, -ImmSize);
273     return;
274   }
275   
276   unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
277   
278   // Determine whether a SIB byte is needed.
279   // If no BaseReg, issue a RIP relative instruction only if the MCE can 
280   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
281   // 2-7) and absolute references.
282
283   if (// The SIB byte must be used if there is an index register.
284       IndexReg.getReg() == 0 && 
285       // The SIB byte must be used if the base is ESP/RSP/R12, all of which
286       // encode to an R/M value of 4, which indicates that a SIB byte is
287       // present.
288       BaseRegNo != N86::ESP &&
289       // If there is no base register and we're in 64-bit mode, we need a SIB
290       // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
291       (!Is64BitMode || BaseReg != 0)) {
292
293     if (BaseReg == 0) {          // [disp32]     in X86-32 mode
294       EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
295       EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
296       return;
297     }
298     
299     // If the base is not EBP/ESP and there is no displacement, use simple
300     // indirect register encoding, this handles addresses like [EAX].  The
301     // encoding for [EBP] with no displacement means [disp32] so we handle it
302     // by emitting a displacement of 0 below.
303     if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
304       EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
305       return;
306     }
307     
308     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
309     if (Disp.isImm() && isDisp8(Disp.getImm())) {
310       EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
311       EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
312       return;
313     }
314     
315     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
316     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
317     EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
318     return;
319   }
320     
321   // We need a SIB byte, so start by outputting the ModR/M byte first
322   assert(IndexReg.getReg() != X86::ESP &&
323          IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
324   
325   bool ForceDisp32 = false;
326   bool ForceDisp8  = false;
327   if (BaseReg == 0) {
328     // If there is no base register, we emit the special case SIB byte with
329     // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
330     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
331     ForceDisp32 = true;
332   } else if (!Disp.isImm()) {
333     // Emit the normal disp32 encoding.
334     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
335     ForceDisp32 = true;
336   } else if (Disp.getImm() == 0 &&
337              // Base reg can't be anything that ends up with '5' as the base
338              // reg, it is the magic [*] nomenclature that indicates no base.
339              BaseRegNo != N86::EBP) {
340     // Emit no displacement ModR/M byte
341     EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
342   } else if (isDisp8(Disp.getImm())) {
343     // Emit the disp8 encoding.
344     EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
345     ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
346   } else {
347     // Emit the normal disp32 encoding.
348     EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
349   }
350   
351   // Calculate what the SS field value should be...
352   static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
353   unsigned SS = SSTable[Scale.getImm()];
354   
355   if (BaseReg == 0) {
356     // Handle the SIB byte for the case where there is no base, see Intel 
357     // Manual 2A, table 2-7. The displacement has already been output.
358     unsigned IndexRegNo;
359     if (IndexReg.getReg())
360       IndexRegNo = GetX86RegNum(IndexReg);
361     else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
362       IndexRegNo = 4;
363     EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
364   } else {
365     unsigned IndexRegNo;
366     if (IndexReg.getReg())
367       IndexRegNo = GetX86RegNum(IndexReg);
368     else
369       IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
370     EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
371   }
372   
373   // Do we need to output a displacement?
374   if (ForceDisp8)
375     EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
376   else if (ForceDisp32 || Disp.getImm() != 0)
377     EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
378 }
379
380 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode prefix
381 /// called VEX.
382 void X86MCCodeEmitter::EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
383                             const MCInst &MI, const TargetInstrDesc &Desc,
384                             raw_ostream &OS) const {
385
386   // Pseudo instructions never have a VEX prefix.
387   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
388     return;
389
390   bool HasVEX_4V = false;
391   if ((TSFlags >> 32) & 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 >> 32) & X86II::VEX_W)
456     VEX_W = 1;
457
458   switch (TSFlags & X86II::Op0Mask) {
459   default: assert(0 && "Invalid prefix!");
460   case X86II::T8:  // 0F 38
461     VEX_5M = 0x2;
462     break;
463   case X86II::TA:  // 0F 3A
464     VEX_5M = 0x3;
465     break;
466   case X86II::TF:  // F2 0F 38
467     VEX_PP = 0x3;
468     VEX_5M = 0x2;
469     break;
470   case X86II::XS:  // F3 0F
471     VEX_PP = 0x2;
472     break;
473   case X86II::XD:  // F2 0F
474     VEX_PP = 0x3;
475     break;
476   case X86II::TB:  // Bypass: Not used by VEX
477   case 0:
478     break;  // No prefix!
479   }
480
481   unsigned NumOps = MI.getNumOperands();
482   unsigned CurOp = 0;
483
484   switch (TSFlags & X86II::FormMask) {
485   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
486   case X86II::MRM0m: case X86II::MRM1m:
487   case X86II::MRM2m: case X86II::MRM3m:
488   case X86II::MRM4m: case X86II::MRM5m:
489   case X86II::MRM6m: case X86II::MRM7m:
490   case X86II::MRMDestMem:
491     NumOps = CurOp = X86AddrNumOperands;
492   case X86II::MRMSrcMem:
493   case X86II::MRMSrcReg:
494     if (MI.getNumOperands() > CurOp && MI.getOperand(CurOp).isReg() &&
495         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
496       VEX_R = 0x0;
497
498     // CurOp and NumOps are equal when VEX_R represents a register used
499     // to index a memory destination (which is the last operand)
500     CurOp = (CurOp == NumOps) ? 0 : CurOp+1;
501
502     if (HasVEX_4V) {
503       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
504       CurOp++;
505     }
506
507     // If the last register should be encoded in the immediate field
508     // do not use any bit from VEX prefix to this register, ignore it
509     if ((TSFlags >> 32) & X86II::VEX_I8IMM)
510       NumOps--;
511
512     for (; CurOp != NumOps; ++CurOp) {
513       const MCOperand &MO = MI.getOperand(CurOp);
514       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
515         VEX_B = 0x0;
516       if (!VEX_B && MO.isReg() &&
517           ((TSFlags & X86II::FormMask) == X86II::MRMSrcMem) &&
518           X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
519         VEX_X = 0x0;
520     }
521     break;
522   default: // MRMDestReg, MRM0r-MRM7r
523     if (MI.getOperand(CurOp).isReg() &&
524         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
525       VEX_B = 0;
526
527     if (HasVEX_4V)
528       VEX_4V = getVEXRegisterEncoding(MI, CurOp);
529
530     CurOp++;
531     for (; CurOp != NumOps; ++CurOp) {
532       const MCOperand &MO = MI.getOperand(CurOp);
533       if (MO.isReg() && !HasVEX_4V &&
534           X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
535         VEX_R = 0x0;
536     }
537     break;
538     assert(0 && "Not implemented!");
539   }
540
541   // VEX opcode prefix can have 2 or 3 bytes
542   //
543   //  3 bytes:
544   //    +-----+ +--------------+ +-------------------+
545   //    | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
546   //    +-----+ +--------------+ +-------------------+
547   //  2 bytes:
548   //    +-----+ +-------------------+
549   //    | C5h | | R | vvvv | L | pp |
550   //    +-----+ +-------------------+
551   //
552   unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
553
554   if (VEX_B && VEX_X && !VEX_W && (VEX_5M == 1)) { // 2 byte VEX prefix
555     EmitByte(0xC5, CurByte, OS);
556     EmitByte(LastByte | (VEX_R << 7), CurByte, OS);
557     return;
558   }
559
560   // 3 byte VEX prefix
561   EmitByte(0xC4, CurByte, OS);
562   EmitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, CurByte, OS);
563   EmitByte(LastByte | (VEX_W << 7), CurByte, OS);
564 }
565
566 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
567 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
568 /// size, and 3) use of X86-64 extended registers.
569 static unsigned DetermineREXPrefix(const MCInst &MI, uint64_t TSFlags,
570                                    const TargetInstrDesc &Desc) {
571   // Pseudo instructions never have a rex byte.
572   if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
573     return 0;
574   
575   unsigned REX = 0;
576   if (TSFlags & X86II::REX_W)
577     REX |= 1 << 3; // set REX.W
578   
579   if (MI.getNumOperands() == 0) return REX;
580   
581   unsigned NumOps = MI.getNumOperands();
582   // FIXME: MCInst should explicitize the two-addrness.
583   bool isTwoAddr = NumOps > 1 &&
584                       Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
585   
586   // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
587   unsigned i = isTwoAddr ? 1 : 0;
588   for (; i != NumOps; ++i) {
589     const MCOperand &MO = MI.getOperand(i);
590     if (!MO.isReg()) continue;
591     unsigned Reg = MO.getReg();
592     if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
593     // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
594     // that returns non-zero.
595     REX |= 0x40; // REX fixed encoding prefix
596     break;
597   }
598   
599   switch (TSFlags & X86II::FormMask) {
600   case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
601   case X86II::MRMSrcReg:
602     if (MI.getOperand(0).isReg() &&
603         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
604       REX |= 1 << 2; // set REX.R
605     i = isTwoAddr ? 2 : 1;
606     for (; i != NumOps; ++i) {
607       const MCOperand &MO = MI.getOperand(i);
608       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
609         REX |= 1 << 0; // set REX.B
610     }
611     break;
612   case X86II::MRMSrcMem: {
613     if (MI.getOperand(0).isReg() &&
614         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
615       REX |= 1 << 2; // set REX.R
616     unsigned Bit = 0;
617     i = isTwoAddr ? 2 : 1;
618     for (; i != NumOps; ++i) {
619       const MCOperand &MO = MI.getOperand(i);
620       if (MO.isReg()) {
621         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
622           REX |= 1 << Bit; // set REX.B (Bit=0) and REX.X (Bit=1)
623         Bit++;
624       }
625     }
626     break;
627   }
628   case X86II::MRM0m: case X86II::MRM1m:
629   case X86II::MRM2m: case X86II::MRM3m:
630   case X86II::MRM4m: case X86II::MRM5m:
631   case X86II::MRM6m: case X86II::MRM7m:
632   case X86II::MRMDestMem: {
633     unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
634     i = isTwoAddr ? 1 : 0;
635     if (NumOps > e && MI.getOperand(e).isReg() &&
636         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
637       REX |= 1 << 2; // set REX.R
638     unsigned Bit = 0;
639     for (; i != e; ++i) {
640       const MCOperand &MO = MI.getOperand(i);
641       if (MO.isReg()) {
642         if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
643           REX |= 1 << Bit; // REX.B (Bit=0) and REX.X (Bit=1)
644         Bit++;
645       }
646     }
647     break;
648   }
649   default:
650     if (MI.getOperand(0).isReg() &&
651         X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
652       REX |= 1 << 0; // set REX.B
653     i = isTwoAddr ? 2 : 1;
654     for (unsigned e = NumOps; i != e; ++i) {
655       const MCOperand &MO = MI.getOperand(i);
656       if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
657         REX |= 1 << 2; // set REX.R
658     }
659     break;
660   }
661   return REX;
662 }
663
664 /// EmitOpcodePrefix - Emit all instruction prefixes prior to the opcode.
665 void X86MCCodeEmitter::EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte,
666                                         const MCInst &MI, 
667                                         const TargetInstrDesc &Desc,
668                                         raw_ostream &OS) const {
669
670   // Emit the lock opcode prefix as needed.
671   if (TSFlags & X86II::LOCK)
672     EmitByte(0xF0, CurByte, OS);
673   
674   // Emit segment override opcode prefix as needed.
675   switch (TSFlags & X86II::SegOvrMask) {
676   default: assert(0 && "Invalid segment!");
677   case 0: break;  // No segment override!
678   case X86II::FS:
679     EmitByte(0x64, CurByte, OS);
680     break;
681   case X86II::GS:
682     EmitByte(0x65, CurByte, OS);
683     break;
684   }
685   
686   // Emit the repeat opcode prefix as needed.
687   if ((TSFlags & X86II::Op0Mask) == X86II::REP)
688     EmitByte(0xF3, CurByte, OS);
689   
690   // Emit the operand size opcode prefix as needed.
691   if (TSFlags & X86II::OpSize)
692     EmitByte(0x66, CurByte, OS);
693   
694   // Emit the address size opcode prefix as needed.
695   if (TSFlags & X86II::AdSize)
696     EmitByte(0x67, CurByte, OS);
697   
698   bool Need0FPrefix = false;
699   switch (TSFlags & X86II::Op0Mask) {
700   default: assert(0 && "Invalid prefix!");
701   case 0: break;  // No prefix!
702   case X86II::REP: break; // already handled.
703   case X86II::TB:  // Two-byte opcode prefix
704   case X86II::T8:  // 0F 38
705   case X86II::TA:  // 0F 3A
706     Need0FPrefix = true;
707     break;
708   case X86II::TF: // F2 0F 38
709     EmitByte(0xF2, CurByte, OS);
710     Need0FPrefix = true;
711     break;
712   case X86II::XS:   // F3 0F
713     EmitByte(0xF3, CurByte, OS);
714     Need0FPrefix = true;
715     break;
716   case X86II::XD:   // F2 0F
717     EmitByte(0xF2, CurByte, OS);
718     Need0FPrefix = true;
719     break;
720   case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
721   case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
722   case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
723   case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
724   case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
725   case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
726   case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
727   case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
728   }
729   
730   // Handle REX prefix.
731   // FIXME: Can this come before F2 etc to simplify emission?
732   if (Is64BitMode) {
733     if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
734       EmitByte(0x40 | REX, CurByte, OS);
735   }
736   
737   // 0x0F escape code must be emitted just before the opcode.
738   if (Need0FPrefix)
739     EmitByte(0x0F, CurByte, OS);
740   
741   // FIXME: Pull this up into previous switch if REX can be moved earlier.
742   switch (TSFlags & X86II::Op0Mask) {
743   case X86II::TF:    // F2 0F 38
744   case X86II::T8:    // 0F 38
745     EmitByte(0x38, CurByte, OS);
746     break;
747   case X86II::TA:    // 0F 3A
748     EmitByte(0x3A, CurByte, OS);
749     break;
750   }
751 }
752
753 void X86MCCodeEmitter::
754 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
755                   SmallVectorImpl<MCFixup> &Fixups) const {
756   unsigned Opcode = MI.getOpcode();
757   const TargetInstrDesc &Desc = TII.get(Opcode);
758   uint64_t TSFlags = Desc.TSFlags;
759
760   // Keep track of the current byte being emitted.
761   unsigned CurByte = 0;
762   
763   // Is this instruction encoded using the AVX VEX prefix?
764   bool HasVEXPrefix = false;
765
766   // It uses the VEX.VVVV field?
767   bool HasVEX_4V = false;
768
769   if ((TSFlags >> 32) & X86II::VEX)
770     HasVEXPrefix = true;
771   if ((TSFlags >> 32) & X86II::VEX_4V)
772     HasVEX_4V = true;
773
774   // FIXME: We should emit the prefixes in exactly the same order as GAS does,
775   // in order to provide diffability.
776
777   if (!HasVEXPrefix)
778     EmitOpcodePrefix(TSFlags, CurByte, MI, Desc, OS);
779   else
780     EmitVEXOpcodePrefix(TSFlags, CurByte, MI, Desc, OS);
781   
782   // If this is a two-address instruction, skip one of the register operands.
783   unsigned NumOps = Desc.getNumOperands();
784   unsigned CurOp = 0;
785   if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
786     ++CurOp;
787   else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
788     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
789     --NumOps;
790   
791   unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
792   unsigned SrcRegNum = 0;
793   switch (TSFlags & X86II::FormMask) {
794   case X86II::MRMInitReg:
795     assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
796   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
797     assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
798   case X86II::Pseudo: return; // Pseudo instructions encode to nothing.
799   case X86II::RawFrm:
800     EmitByte(BaseOpcode, CurByte, OS);
801     break;
802       
803   case X86II::AddRegFrm:
804     EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
805     break;
806       
807   case X86II::MRMDestReg:
808     EmitByte(BaseOpcode, CurByte, OS);
809     EmitRegModRMByte(MI.getOperand(CurOp),
810                      GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
811     CurOp += 2;
812     break;
813   
814   case X86II::MRMDestMem:
815     EmitSegmentOverridePrefix(MI.getOperand(CurOp + 4), TSFlags, CurByte, OS);
816     EmitByte(BaseOpcode, CurByte, OS);
817     EmitMemModRMByte(MI, CurOp,
818                      GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
819                      TSFlags, CurByte, OS, Fixups);
820     CurOp += X86AddrNumOperands + 1;
821     break;
822       
823   case X86II::MRMSrcReg:
824     EmitByte(BaseOpcode, CurByte, OS);
825     SrcRegNum = CurOp + 1;
826
827     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
828       SrcRegNum++;
829
830     EmitRegModRMByte(MI.getOperand(SrcRegNum),
831                      GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
832     CurOp = SrcRegNum + 1;
833     break;
834     
835   case X86II::MRMSrcMem: {
836     int AddrOperands = X86AddrNumOperands;
837     unsigned FirstMemOp = CurOp+1;
838     if (HasVEX_4V) {
839       ++AddrOperands;
840       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_VVVV).
841     }
842
843     // FIXME: Maybe lea should have its own form?  This is a horrible hack.
844     if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
845         Opcode == X86::LEA16r || Opcode == X86::LEA32r)
846       --AddrOperands; // No segment register
847     else
848       EmitSegmentOverridePrefix(MI.getOperand(FirstMemOp+4),
849                                 TSFlags, CurByte, OS);
850
851     EmitByte(BaseOpcode, CurByte, OS);
852
853     
854     EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
855                      TSFlags, CurByte, OS, Fixups);
856     CurOp += AddrOperands + 1;
857     break;
858   }
859
860   case X86II::MRM0r: case X86II::MRM1r:
861   case X86II::MRM2r: case X86II::MRM3r:
862   case X86II::MRM4r: case X86II::MRM5r:
863   case X86II::MRM6r: case X86II::MRM7r:
864     if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
865       CurOp++;
866     EmitByte(BaseOpcode, CurByte, OS);
867     EmitRegModRMByte(MI.getOperand(CurOp++),
868                      (TSFlags & X86II::FormMask)-X86II::MRM0r,
869                      CurByte, OS);
870     break;
871   case X86II::MRM0m: case X86II::MRM1m:
872   case X86II::MRM2m: case X86II::MRM3m:
873   case X86II::MRM4m: case X86II::MRM5m:
874   case X86II::MRM6m: case X86II::MRM7m:
875     EmitSegmentOverridePrefix(MI.getOperand(CurOp+4), TSFlags, CurByte, OS);
876     EmitByte(BaseOpcode, CurByte, OS);
877     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
878                      TSFlags, CurByte, OS, Fixups);
879     CurOp += X86AddrNumOperands;
880     break;
881   case X86II::MRM_C1:
882     EmitByte(BaseOpcode, CurByte, OS);
883     EmitByte(0xC1, CurByte, OS);
884     break;
885   case X86II::MRM_C2:
886     EmitByte(BaseOpcode, CurByte, OS);
887     EmitByte(0xC2, CurByte, OS);
888     break;
889   case X86II::MRM_C3:
890     EmitByte(BaseOpcode, CurByte, OS);
891     EmitByte(0xC3, CurByte, OS);
892     break;
893   case X86II::MRM_C4:
894     EmitByte(BaseOpcode, CurByte, OS);
895     EmitByte(0xC4, CurByte, OS);
896     break;
897   case X86II::MRM_C8:
898     EmitByte(BaseOpcode, CurByte, OS);
899     EmitByte(0xC8, CurByte, OS);
900     break;
901   case X86II::MRM_C9:
902     EmitByte(BaseOpcode, CurByte, OS);
903     EmitByte(0xC9, CurByte, OS);
904     break;
905   case X86II::MRM_E8:
906     EmitByte(BaseOpcode, CurByte, OS);
907     EmitByte(0xE8, CurByte, OS);
908     break;
909   case X86II::MRM_F0:
910     EmitByte(BaseOpcode, CurByte, OS);
911     EmitByte(0xF0, CurByte, OS);
912     break;
913   case X86II::MRM_F8:
914     EmitByte(BaseOpcode, CurByte, OS);
915     EmitByte(0xF8, CurByte, OS);
916     break;
917   case X86II::MRM_F9:
918     EmitByte(BaseOpcode, CurByte, OS);
919     EmitByte(0xF9, CurByte, OS);
920     break;
921   }
922   
923   // If there is a remaining operand, it must be a trailing immediate.  Emit it
924   // according to the right size for the instruction.
925   if (CurOp != NumOps) {
926     // The last source register of a 4 operand instruction in AVX is encoded
927     // in bits[7:4] of a immediate byte, and bits[3:0] are ignored.
928     if ((TSFlags >> 32) & X86II::VEX_I8IMM) {
929       const MCOperand &MO = MI.getOperand(CurOp++);
930       bool IsExtReg =
931         X86InstrInfo::isX86_64ExtendedReg(MO.getReg());
932       unsigned RegNum = (IsExtReg ? (1 << 7) : 0);
933       RegNum |= GetX86RegNum(MO) << 4;
934       EmitImmediate(MCOperand::CreateImm(RegNum), 1, FK_Data_1, CurByte, OS,
935                     Fixups);
936     } else
937       EmitImmediate(MI.getOperand(CurOp++),
938                     X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
939                     CurByte, OS, Fixups);
940   }
941
942
943 #ifndef NDEBUG
944   // FIXME: Verify.
945   if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
946     errs() << "Cannot encode all operands of: ";
947     MI.dump();
948     errs() << '\n';
949     abort();
950   }
951 #endif
952 }