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 "x86-emitter"
16 #include "X86InstrInfo.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/Support/raw_ostream.h"
22 // FIXME: This should move to a header.
26 reloc_pcrel_4byte = FirstTargetFixupKind, // 32-bit pcrel, e.g. a branch.
27 reloc_pcrel_1byte // 8-bit pcrel, e.g. branch_1
33 class X86MCCodeEmitter : public MCCodeEmitter {
34 X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
35 void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
36 const TargetMachine &TM;
37 const TargetInstrInfo &TII;
40 X86MCCodeEmitter(TargetMachine &tm, bool is64Bit)
41 : TM(tm), TII(*TM.getInstrInfo()) {
42 Is64BitMode = is64Bit;
45 ~X86MCCodeEmitter() {}
47 unsigned getNumFixupKinds() const {
51 const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
52 const static MCFixupKindInfo Infos[] = {
53 { "reloc_pcrel_4byte", 0, 4 * 8 },
54 { "reloc_pcrel_1byte", 0, 1 * 8 }
57 if (Kind < FirstTargetFixupKind)
58 return MCCodeEmitter::getFixupKindInfo(Kind);
60 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
62 return Infos[Kind - FirstTargetFixupKind];
65 static unsigned GetX86RegNum(const MCOperand &MO) {
66 return X86RegisterInfo::getX86RegNum(MO.getReg());
69 void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
74 void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
75 raw_ostream &OS) const {
76 // Output the constant in little endian byte order.
77 for (unsigned i = 0; i != Size; ++i) {
78 EmitByte(Val & 255, CurByte, OS);
83 void EmitImmediate(const MCOperand &Disp, unsigned ImmSize,
84 unsigned &CurByte, raw_ostream &OS,
85 SmallVectorImpl<MCFixup> &Fixups) const;
87 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
89 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
90 return RM | (RegOpcode << 3) | (Mod << 6);
93 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
94 unsigned &CurByte, raw_ostream &OS) const {
95 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
98 void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
99 unsigned &CurByte, raw_ostream &OS) const {
100 // SIB byte is in the same format as the ModRMByte.
101 EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
105 void EmitMemModRMByte(const MCInst &MI, unsigned Op,
106 unsigned RegOpcodeField,
107 unsigned &CurByte, raw_ostream &OS,
108 SmallVectorImpl<MCFixup> &Fixups) const;
110 void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
111 SmallVectorImpl<MCFixup> &Fixups) const;
115 } // end anonymous namespace
118 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
120 return new X86MCCodeEmitter(TM, false);
123 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
125 return new X86MCCodeEmitter(TM, true);
129 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
130 /// sign-extended field.
131 static bool isDisp8(int Value) {
132 return Value == (signed char)Value;
135 void X86MCCodeEmitter::
136 EmitImmediate(const MCOperand &DispOp, unsigned Size,
137 unsigned &CurByte, raw_ostream &OS,
138 SmallVectorImpl<MCFixup> &Fixups) const {
139 // If this is a simple integer displacement that doesn't require a relocation,
141 if (DispOp.isImm()) {
142 EmitConstant(DispOp.getImm(), Size, CurByte, OS);
146 // FIXME: Pass in the relocation type, this is just a hack..
149 FixupKind = FK_Data_1;
151 FixupKind = FK_Data_2;
153 FixupKind = FK_Data_4;
155 assert(Size == 8 && "Unknown immediate size");
156 FixupKind = FK_Data_8;
159 // Emit a symbolic constant as a fixup and 4 zeros.
160 Fixups.push_back(MCFixup::Create(CurByte, DispOp.getExpr(),
161 MCFixupKind(FixupKind)));
162 EmitConstant(0, Size, CurByte, OS);
166 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
167 unsigned RegOpcodeField,
170 SmallVectorImpl<MCFixup> &Fixups) const{
171 const MCOperand &Disp = MI.getOperand(Op+3);
172 const MCOperand &Base = MI.getOperand(Op);
173 const MCOperand &Scale = MI.getOperand(Op+1);
174 const MCOperand &IndexReg = MI.getOperand(Op+2);
175 unsigned BaseReg = Base.getReg();
176 unsigned BaseRegNo = -1U;
177 if (BaseReg != 0 && BaseReg != X86::RIP)
178 BaseRegNo = GetX86RegNum(Base);
180 // Determine whether a SIB byte is needed.
181 // If no BaseReg, issue a RIP relative instruction only if the MCE can
182 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
183 // 2-7) and absolute references.
185 if (// The SIB byte must be used if there is an index register.
186 IndexReg.getReg() == 0 &&
187 // The SIB byte must be used if the base is ESP/RSP/R12, all of which
188 // encode to an R/M value of 4, which indicates that a SIB byte is
190 BaseRegNo != N86::ESP &&
191 // If there is no base register and we're in 64-bit mode, we need a SIB
192 // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
193 (!Is64BitMode || BaseReg != 0)) {
195 if (BaseReg == 0 || // [disp32] in X86-32 mode
196 BaseReg == X86::RIP) { // [disp32+RIP] in X86-64 mode
197 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
198 EmitImmediate(Disp, 4, CurByte, OS, Fixups);
202 // If the base is not EBP/ESP and there is no displacement, use simple
203 // indirect register encoding, this handles addresses like [EAX]. The
204 // encoding for [EBP] with no displacement means [disp32] so we handle it
205 // by emitting a displacement of 0 below.
206 if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
207 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
211 // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
212 if (Disp.isImm() && isDisp8(Disp.getImm())) {
213 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
214 EmitImmediate(Disp, 1, CurByte, OS, Fixups);
218 // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
219 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
220 EmitImmediate(Disp, 4, CurByte, OS, Fixups);
224 // We need a SIB byte, so start by outputting the ModR/M byte first
225 assert(IndexReg.getReg() != X86::ESP &&
226 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
228 bool ForceDisp32 = false;
229 bool ForceDisp8 = false;
231 // If there is no base register, we emit the special case SIB byte with
232 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
233 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
235 } else if (!Disp.isImm()) {
236 // Emit the normal disp32 encoding.
237 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
239 } else if (Disp.getImm() == 0 && BaseReg != X86::EBP) {
240 // Emit no displacement ModR/M byte
241 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
242 } else if (isDisp8(Disp.getImm())) {
243 // Emit the disp8 encoding.
244 EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
245 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
247 // Emit the normal disp32 encoding.
248 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
251 // Calculate what the SS field value should be...
252 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
253 unsigned SS = SSTable[Scale.getImm()];
256 // Handle the SIB byte for the case where there is no base, see Intel
257 // Manual 2A, table 2-7. The displacement has already been output.
259 if (IndexReg.getReg())
260 IndexRegNo = GetX86RegNum(IndexReg);
261 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
263 EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
266 if (IndexReg.getReg())
267 IndexRegNo = GetX86RegNum(IndexReg);
269 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
270 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
273 // Do we need to output a displacement?
275 EmitImmediate(Disp, 1, CurByte, OS, Fixups);
276 else if (ForceDisp32 || Disp.getImm() != 0)
277 EmitImmediate(Disp, 4, CurByte, OS, Fixups);
280 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
281 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
282 /// size, and 3) use of X86-64 extended registers.
283 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
284 const TargetInstrDesc &Desc) {
287 // Pseudo instructions do not need REX prefix byte.
288 if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
290 if (TSFlags & X86II::REX_W)
293 if (MI.getNumOperands() == 0) return REX;
295 unsigned NumOps = MI.getNumOperands();
296 // FIXME: MCInst should explicitize the two-addrness.
297 bool isTwoAddr = NumOps > 1 &&
298 Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
300 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
301 unsigned i = isTwoAddr ? 1 : 0;
302 for (; i != NumOps; ++i) {
303 const MCOperand &MO = MI.getOperand(i);
304 if (!MO.isReg()) continue;
305 unsigned Reg = MO.getReg();
306 if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
307 // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
308 // that returns non-zero.
313 switch (TSFlags & X86II::FormMask) {
314 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
315 case X86II::MRMSrcReg:
316 if (MI.getOperand(0).isReg() &&
317 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
319 i = isTwoAddr ? 2 : 1;
320 for (; i != NumOps; ++i) {
321 const MCOperand &MO = MI.getOperand(i);
322 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
326 case X86II::MRMSrcMem: {
327 if (MI.getOperand(0).isReg() &&
328 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
331 i = isTwoAddr ? 2 : 1;
332 for (; i != NumOps; ++i) {
333 const MCOperand &MO = MI.getOperand(i);
335 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
342 case X86II::MRM0m: case X86II::MRM1m:
343 case X86II::MRM2m: case X86II::MRM3m:
344 case X86II::MRM4m: case X86II::MRM5m:
345 case X86II::MRM6m: case X86II::MRM7m:
346 case X86II::MRMDestMem: {
347 unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
348 i = isTwoAddr ? 1 : 0;
349 if (NumOps > e && MI.getOperand(e).isReg() &&
350 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
353 for (; i != e; ++i) {
354 const MCOperand &MO = MI.getOperand(i);
356 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
364 if (MI.getOperand(0).isReg() &&
365 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
367 i = isTwoAddr ? 2 : 1;
368 for (unsigned e = NumOps; i != e; ++i) {
369 const MCOperand &MO = MI.getOperand(i);
370 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
378 void X86MCCodeEmitter::
379 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
380 SmallVectorImpl<MCFixup> &Fixups) const {
381 unsigned Opcode = MI.getOpcode();
382 const TargetInstrDesc &Desc = TII.get(Opcode);
383 unsigned TSFlags = Desc.TSFlags;
385 // Keep track of the current byte being emitted.
386 unsigned CurByte = 0;
388 // FIXME: We should emit the prefixes in exactly the same order as GAS does,
389 // in order to provide diffability.
391 // Emit the lock opcode prefix as needed.
392 if (TSFlags & X86II::LOCK)
393 EmitByte(0xF0, CurByte, OS);
395 // Emit segment override opcode prefix as needed.
396 switch (TSFlags & X86II::SegOvrMask) {
397 default: assert(0 && "Invalid segment!");
398 case 0: break; // No segment override!
400 EmitByte(0x64, CurByte, OS);
403 EmitByte(0x65, CurByte, OS);
407 // Emit the repeat opcode prefix as needed.
408 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
409 EmitByte(0xF3, CurByte, OS);
411 // Emit the operand size opcode prefix as needed.
412 if (TSFlags & X86II::OpSize)
413 EmitByte(0x66, CurByte, OS);
415 // Emit the address size opcode prefix as needed.
416 if (TSFlags & X86II::AdSize)
417 EmitByte(0x67, CurByte, OS);
419 bool Need0FPrefix = false;
420 switch (TSFlags & X86II::Op0Mask) {
421 default: assert(0 && "Invalid prefix!");
422 case 0: break; // No prefix!
423 case X86II::REP: break; // already handled.
424 case X86II::TB: // Two-byte opcode prefix
425 case X86II::T8: // 0F 38
426 case X86II::TA: // 0F 3A
429 case X86II::TF: // F2 0F 38
430 EmitByte(0xF2, CurByte, OS);
433 case X86II::XS: // F3 0F
434 EmitByte(0xF3, CurByte, OS);
437 case X86II::XD: // F2 0F
438 EmitByte(0xF2, CurByte, OS);
441 case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
442 case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
443 case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
444 case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
445 case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
446 case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
447 case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
448 case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
451 // Handle REX prefix.
452 // FIXME: Can this come before F2 etc to simplify emission?
454 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
455 EmitByte(0x40 | REX, CurByte, OS);
458 // 0x0F escape code must be emitted just before the opcode.
460 EmitByte(0x0F, CurByte, OS);
462 // FIXME: Pull this up into previous switch if REX can be moved earlier.
463 switch (TSFlags & X86II::Op0Mask) {
464 case X86II::TF: // F2 0F 38
465 case X86II::T8: // 0F 38
466 EmitByte(0x38, CurByte, OS);
468 case X86II::TA: // 0F 3A
469 EmitByte(0x3A, CurByte, OS);
473 // If this is a two-address instruction, skip one of the register operands.
474 unsigned NumOps = Desc.getNumOperands();
476 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
478 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
479 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
482 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
483 switch (TSFlags & X86II::FormMask) {
484 case X86II::MRMInitReg:
485 assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
486 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
487 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
489 EmitByte(BaseOpcode, CurByte, OS);
492 case X86II::AddRegFrm:
493 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
496 case X86II::MRMDestReg:
497 EmitByte(BaseOpcode, CurByte, OS);
498 EmitRegModRMByte(MI.getOperand(CurOp),
499 GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
503 case X86II::MRMDestMem:
504 EmitByte(BaseOpcode, CurByte, OS);
505 EmitMemModRMByte(MI, CurOp,
506 GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
507 CurByte, OS, Fixups);
508 CurOp += X86AddrNumOperands + 1;
511 case X86II::MRMSrcReg:
512 EmitByte(BaseOpcode, CurByte, OS);
513 EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
518 case X86II::MRMSrcMem: {
519 EmitByte(BaseOpcode, CurByte, OS);
521 // FIXME: Maybe lea should have its own form? This is a horrible hack.
523 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
524 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
525 AddrOperands = X86AddrNumOperands - 1; // No segment register
527 AddrOperands = X86AddrNumOperands;
529 EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
530 CurByte, OS, Fixups);
531 CurOp += AddrOperands + 1;
535 case X86II::MRM0r: case X86II::MRM1r:
536 case X86II::MRM2r: case X86II::MRM3r:
537 case X86II::MRM4r: case X86II::MRM5r:
538 case X86II::MRM6r: case X86II::MRM7r:
539 EmitByte(BaseOpcode, CurByte, OS);
541 // Special handling of lfence, mfence, monitor, and mwait.
542 // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
543 if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
544 Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
545 EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r, 0),
550 case X86::MONITOR: EmitByte(0xC8, CurByte, OS); break;
551 case X86::MWAIT: EmitByte(0xC9, CurByte, OS); break;
554 EmitRegModRMByte(MI.getOperand(CurOp++),
555 (TSFlags & X86II::FormMask)-X86II::MRM0r,
559 case X86II::MRM0m: case X86II::MRM1m:
560 case X86II::MRM2m: case X86II::MRM3m:
561 case X86II::MRM4m: case X86II::MRM5m:
562 case X86II::MRM6m: case X86II::MRM7m:
563 EmitByte(BaseOpcode, CurByte, OS);
564 EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
565 CurByte, OS, Fixups);
566 CurOp += X86AddrNumOperands;
570 // If there is a remaining operand, it must be a trailing immediate. Emit it
571 // according to the right size for the instruction.
572 // FIXME: This should pass in whether the value is pc relative or not. This
573 // information should be aquired from TSFlags as well.
575 EmitImmediate(MI.getOperand(CurOp++), X86II::getSizeOfImm(TSFlags),
576 CurByte, OS, Fixups);
580 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
581 errs() << "Cannot encode all operands of: ";