1 //===-- X86/X86MCCodeEmitter.cpp - Convert X86 code to machine code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the X86MCCodeEmitter class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "mccodeemitter"
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"
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;
34 X86MCCodeEmitter(TargetMachine &tm, MCContext &ctx, bool is64Bit)
35 : TM(tm), TII(*TM.getInstrInfo()), Ctx(ctx) {
36 Is64BitMode = is64Bit;
39 ~X86MCCodeEmitter() {}
41 unsigned getNumFixupKinds() const {
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}
53 if (Kind < FirstTargetFixupKind)
54 return MCCodeEmitter::getFixupKindInfo(Kind);
56 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
58 return Infos[Kind - FirstTargetFixupKind];
61 static unsigned GetX86RegNum(const MCOperand &MO) {
62 return X86RegisterInfo::getX86RegNum(MO.getReg());
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:
70 // ModRM field => XMM9 => 1
71 // VEX.VVVV => XMM9 => ~9
73 // See table 4-35 of Intel AVX Programming Reference for details.
74 static unsigned char getVEXRegisterEncoding(const MCInst &MI,
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))
82 // The registers represented through VEX_VVVV should
83 // be encoded in 1's complement form.
84 return (~SrcRegNum) & 0xf;
87 void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
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);
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;
107 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
109 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
110 return RM | (RegOpcode << 3) | (Mod << 6);
113 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
114 unsigned &CurByte, raw_ostream &OS) const {
115 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
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);
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;
130 void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
131 SmallVectorImpl<MCFixup> &Fixups) const;
133 void EmitVEXOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
134 const MCInst &MI, const TargetInstrDesc &Desc,
135 raw_ostream &OS) const;
137 void EmitSegmentOverridePrefix(uint64_t TSFlags, unsigned &CurByte,
138 int MemOperand, const MCInst &MI,
139 raw_ostream &OS) const;
141 void EmitOpcodePrefix(uint64_t TSFlags, unsigned &CurByte, int MemOperand,
142 const MCInst &MI, const TargetInstrDesc &Desc,
143 raw_ostream &OS) const;
146 } // end anonymous namespace
149 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
152 return new X86MCCodeEmitter(TM, Ctx, false);
155 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
158 return new X86MCCodeEmitter(TM, Ctx, true);
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;
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);
173 return MCFixup::getKindForSize(Size, isPCRel);
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);
183 if ((BaseReg.getReg() != 0 && X86::GR32RegClass.contains(BaseReg.getReg())) ||
184 (IndexReg.getReg() != 0 && X86::GR32RegClass.contains(IndexReg.getReg())))
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);
200 if (Expr->getKind() != MCExpr::SymbolRef)
203 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Expr);
204 const MCSymbol &S = Ref->getSymbol();
205 return S.getName() == "_GLOBAL_OFFSET_TABLE_";
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,
216 if (FixupKind != FK_PCRel_1 &&
217 FixupKind != FK_PCRel_2 &&
218 FixupKind != FK_PCRel_4) {
219 EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
222 Expr = MCConstantExpr::Create(DispOp.getImm(), Ctx);
224 Expr = DispOp.getExpr();
227 // If we have an immoffset, add it to the expression.
228 if (FixupKind == FK_Data_4 && StartsWithGlobalOffsetTable(Expr)) {
229 assert(ImmOffset == 0);
231 FixupKind = MCFixupKind(X86::reloc_global_offset_table);
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))
241 if (FixupKind == FK_PCRel_2)
243 if (FixupKind == FK_PCRel_1)
247 Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(ImmOffset, Ctx),
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);
255 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
256 unsigned RegOpcodeField,
257 uint64_t TSFlags, unsigned &CurByte,
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();
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);
272 unsigned FixupKind = X86::reloc_riprel_4byte;
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;
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;
287 EmitImmediate(Disp, 4, MCFixupKind(FixupKind),
288 CurByte, OS, Fixups, -ImmSize);
292 unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
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.
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
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)) {
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);
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);
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);
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,
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!");
342 bool ForceDisp32 = false;
343 bool ForceDisp8 = false;
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);
349 } else if (!Disp.isImm()) {
350 // Emit the normal disp32 encoding.
351 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
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
364 // Emit the normal disp32 encoding.
365 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
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()];
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.
376 if (IndexReg.getReg())
377 IndexRegNo = GetX86RegNum(IndexReg);
378 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
380 EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
383 if (IndexReg.getReg())
384 IndexRegNo = GetX86RegNum(IndexReg);
386 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
387 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
390 // Do we need to output a displacement?
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,
398 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode prefix
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)
408 // VEX_R: opcode externsion equivalent to REX.R in
409 // 1's complement (inverted) form
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)
414 unsigned char VEX_R = 0x1;
416 // VEX_X: equivalent to REX.X, only used when a
417 // register is used for index in SIB Byte.
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;
425 // 1: Same as REX_B=0 (ignored in 32-bit mode)
426 // 0: Same as REX_B=1 (64 bit mode only)
428 unsigned char VEX_B = 0x1;
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;
434 // VEX_5M (VEX m-mmmmm field):
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
442 unsigned char VEX_5M = 0x1;
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;
448 // VEX_L (Vector Length):
450 // 0: scalar or 128-bit vector
453 unsigned char VEX_L = 0;
455 // VEX_PP: opcode extension providing equivalent
456 // functionality of a SIMD prefix
463 unsigned char VEX_PP = 0;
465 // Encode the operand size opcode prefix as needed.
466 if (TSFlags & X86II::OpSize)
469 if ((TSFlags >> 32) & X86II::VEX_W)
472 if ((TSFlags >> 32) & X86II::VEX_L)
475 switch (TSFlags & X86II::Op0Mask) {
476 default: assert(0 && "Invalid prefix!");
477 case X86II::T8: // 0F 38
480 case X86II::TA: // 0F 3A
483 case X86II::TF: // F2 0F 38
487 case X86II::XS: // F3 0F
490 case X86II::XD: // F2 0F
493 case X86II::TB: // Bypass: Not used by VEX
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())
502 unsigned SrcReg = MI.getOperand(i).getReg();
503 if (SrcReg >= X86::YMM0 && SrcReg <= X86::YMM15)
507 unsigned NumOps = MI.getNumOperands();
509 bool IsDestMem = false;
511 switch (TSFlags & X86II::FormMask) {
512 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
513 case X86II::MRMDestMem:
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()))
530 VEX_4V = getVEXRegisterEncoding(MI, IsDestMem ? CurOp-1 : CurOp);
534 // To only check operands before the memory address ones, start
535 // the search from the begining
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)
544 for (; CurOp != NumOps; ++CurOp) {
545 const MCOperand &MO = MI.getOperand(CurOp);
546 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
548 if (!VEX_B && MO.isReg() &&
549 ((TSFlags & X86II::FormMask) == X86II::MRMSrcMem) &&
550 X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
554 default: // MRMDestReg, MRM0r-MRM7r, RawFrm
555 if (!MI.getNumOperands())
558 if (MI.getOperand(CurOp).isReg() &&
559 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
563 VEX_4V = getVEXRegisterEncoding(MI, 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()))
575 // Emit segment override opcode prefix as needed.
576 EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
578 // VEX opcode prefix can have 2 or 3 bytes
581 // +-----+ +--------------+ +-------------------+
582 // | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
583 // +-----+ +--------------+ +-------------------+
585 // +-----+ +-------------------+
586 // | C5h | | R | vvvv | L | pp |
587 // +-----+ +-------------------+
589 unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
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);
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);
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) {
609 if (TSFlags & X86II::REX_W)
610 REX |= 1 << 3; // set REX.W
612 if (MI.getNumOperands() == 0) return REX;
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;
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
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
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
650 i = isTwoAddr ? 2 : 1;
651 for (; i != NumOps; ++i) {
652 const MCOperand &MO = MI.getOperand(i);
654 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
655 REX |= 1 << Bit; // set REX.B (Bit=0) and REX.X (Bit=1)
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
672 for (; i != e; ++i) {
673 const MCOperand &MO = MI.getOperand(i);
675 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
676 REX |= 1 << Bit; // REX.B (Bit=0) and REX.X (Bit=1)
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
697 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
698 void X86MCCodeEmitter::EmitSegmentOverridePrefix(uint64_t TSFlags,
699 unsigned &CurByte, int MemOperand,
701 raw_ostream &OS) const {
702 switch (TSFlags & X86II::SegOvrMask) {
703 default: assert(0 && "Invalid segment!");
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!");
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;
720 EmitByte(0x64, CurByte, OS);
723 EmitByte(0x65, CurByte, OS);
728 /// EmitOpcodePrefix - Emit all instruction prefixes prior to the opcode.
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 {
737 // Emit the lock opcode prefix as needed.
738 if (TSFlags & X86II::LOCK)
739 EmitByte(0xF0, CurByte, OS);
741 // Emit segment override opcode prefix as needed.
742 EmitSegmentOverridePrefix(TSFlags, CurByte, MemOperand, MI, OS);
744 // Emit the repeat opcode prefix as needed.
745 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
746 EmitByte(0xF3, CurByte, OS);
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);
753 // Emit the operand size opcode prefix as needed.
754 if (TSFlags & X86II::OpSize)
755 EmitByte(0x66, CurByte, OS);
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
767 case X86II::TF: // F2 0F 38
768 EmitByte(0xF2, CurByte, OS);
771 case X86II::XS: // F3 0F
772 EmitByte(0xF3, CurByte, OS);
775 case X86II::XD: // F2 0F
776 EmitByte(0xF2, CurByte, OS);
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;
789 // Handle REX prefix.
790 // FIXME: Can this come before F2 etc to simplify emission?
792 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
793 EmitByte(0x40 | REX, CurByte, OS);
796 // 0x0F escape code must be emitted just before the opcode.
798 EmitByte(0x0F, CurByte, OS);
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);
806 case X86II::TA: // 0F 3A
807 EmitByte(0x3A, CurByte, OS);
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;
819 // Pseudo instructions don't get encoded.
820 if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
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();
827 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
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
833 // Keep track of the current byte being emitted.
834 unsigned CurByte = 0;
836 // Is this instruction encoded using the AVX VEX prefix?
837 bool HasVEXPrefix = false;
839 // It uses the VEX.VVVV field?
840 bool HasVEX_4V = false;
842 if ((TSFlags >> 32) & X86II::VEX)
844 if ((TSFlags >> 32) & X86II::VEX_4V)
848 // Determine where the memory operand starts, if present.
849 int MemoryOperand = X86II::getMemoryOperandNo(TSFlags);
850 if (MemoryOperand != -1) MemoryOperand += CurOp;
853 EmitOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
855 EmitVEXOpcodePrefix(TSFlags, CurByte, MemoryOperand, MI, Desc, OS);
858 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
860 if ((TSFlags >> 32) & X86II::Has3DNow0F0FOpcode)
861 BaseOpcode = 0x0F; // Weird 3DNow! encoding.
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!");
870 assert(0 && "Pseudo instruction shouldn't be emitted");
872 EmitByte(BaseOpcode, CurByte, OS);
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);
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);
890 case X86II::AddRegFrm:
891 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
894 case X86II::MRMDestReg:
895 EmitByte(BaseOpcode, CurByte, OS);
896 EmitRegModRMByte(MI.getOperand(CurOp),
897 GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
901 case X86II::MRMDestMem:
902 EmitByte(BaseOpcode, CurByte, OS);
903 SrcRegNum = CurOp + X86::AddrNumOperands;
905 if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
908 EmitMemModRMByte(MI, CurOp,
909 GetX86RegNum(MI.getOperand(SrcRegNum)),
910 TSFlags, CurByte, OS, Fixups);
911 CurOp = SrcRegNum + 1;
914 case X86II::MRMSrcReg:
915 EmitByte(BaseOpcode, CurByte, OS);
916 SrcRegNum = CurOp + 1;
918 if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
921 EmitRegModRMByte(MI.getOperand(SrcRegNum),
922 GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
923 CurOp = SrcRegNum + 1;
926 case X86II::MRMSrcMem: {
927 int AddrOperands = X86::AddrNumOperands;
928 unsigned FirstMemOp = CurOp+1;
931 ++FirstMemOp; // Skip the register source (which is encoded in VEX_VVVV).
934 EmitByte(BaseOpcode, CurByte, OS);
936 EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
937 TSFlags, CurByte, OS, Fixups);
938 CurOp += AddrOperands + 1;
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).
948 EmitByte(BaseOpcode, CurByte, OS);
949 EmitRegModRMByte(MI.getOperand(CurOp++),
950 (TSFlags & X86II::FormMask)-X86II::MRM0r,
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;
963 EmitByte(BaseOpcode, CurByte, OS);
964 EmitByte(0xC1, CurByte, OS);
967 EmitByte(BaseOpcode, CurByte, OS);
968 EmitByte(0xC2, CurByte, OS);
971 EmitByte(BaseOpcode, CurByte, OS);
972 EmitByte(0xC3, CurByte, OS);
975 EmitByte(BaseOpcode, CurByte, OS);
976 EmitByte(0xC4, CurByte, OS);
979 EmitByte(BaseOpcode, CurByte, OS);
980 EmitByte(0xC8, CurByte, OS);
983 EmitByte(BaseOpcode, CurByte, OS);
984 EmitByte(0xC9, CurByte, OS);
987 EmitByte(BaseOpcode, CurByte, OS);
988 EmitByte(0xE8, CurByte, OS);
991 EmitByte(BaseOpcode, CurByte, OS);
992 EmitByte(0xF0, CurByte, OS);
995 EmitByte(BaseOpcode, CurByte, OS);
996 EmitByte(0xF8, CurByte, OS);
999 EmitByte(BaseOpcode, CurByte, OS);
1000 EmitByte(0xF9, CurByte, OS);
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++);
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,
1019 if (MI.getOpcode() == X86::MOV64ri32 || MI.getOpcode() == X86::MOV64mi32)
1020 FixupKind = X86::reloc_signed_4byte;
1022 FixupKind = getImmFixupKind(TSFlags);
1023 EmitImmediate(MI.getOperand(CurOp++),
1024 X86II::getSizeOfImm(TSFlags), MCFixupKind(FixupKind),
1025 CurByte, OS, Fixups);
1029 if ((TSFlags >> 32) & X86II::Has3DNow0F0FOpcode)
1030 EmitByte(X86II::getBaseOpcodeFor(TSFlags), CurByte, OS);
1035 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
1036 errs() << "Cannot encode all operands of: ";