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
28 reloc_riprel_4byte // 32-bit rip-relative
34 class X86MCCodeEmitter : public MCCodeEmitter {
35 X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
36 void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
37 const TargetMachine &TM;
38 const TargetInstrInfo &TII;
41 X86MCCodeEmitter(TargetMachine &tm, bool is64Bit)
42 : TM(tm), TII(*TM.getInstrInfo()) {
43 Is64BitMode = is64Bit;
46 ~X86MCCodeEmitter() {}
48 unsigned getNumFixupKinds() const {
52 const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
53 const static MCFixupKindInfo Infos[] = {
54 { "reloc_pcrel_4byte", 0, 4 * 8 },
55 { "reloc_pcrel_1byte", 0, 1 * 8 },
56 { "reloc_riprel_4byte", 0, 4 * 8 }
59 if (Kind < FirstTargetFixupKind)
60 return MCCodeEmitter::getFixupKindInfo(Kind);
62 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
64 return Infos[Kind - FirstTargetFixupKind];
67 static unsigned GetX86RegNum(const MCOperand &MO) {
68 return X86RegisterInfo::getX86RegNum(MO.getReg());
71 void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const {
76 void EmitConstant(uint64_t Val, unsigned Size, unsigned &CurByte,
77 raw_ostream &OS) const {
78 // Output the constant in little endian byte order.
79 for (unsigned i = 0; i != Size; ++i) {
80 EmitByte(Val & 255, CurByte, OS);
85 void EmitImmediate(const MCOperand &Disp,
86 unsigned ImmSize, MCFixupKind FixupKind,
87 unsigned &CurByte, raw_ostream &OS,
88 SmallVectorImpl<MCFixup> &Fixups,
89 int ImmOffset = 0) const;
91 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
93 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
94 return RM | (RegOpcode << 3) | (Mod << 6);
97 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
98 unsigned &CurByte, raw_ostream &OS) const {
99 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
102 void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
103 unsigned &CurByte, raw_ostream &OS) const {
104 // SIB byte is in the same format as the ModRMByte.
105 EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
109 void EmitMemModRMByte(const MCInst &MI, unsigned Op,
110 unsigned RegOpcodeField,
111 unsigned TSFlags, unsigned &CurByte, raw_ostream &OS,
112 SmallVectorImpl<MCFixup> &Fixups) const;
114 void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
115 SmallVectorImpl<MCFixup> &Fixups) const;
119 } // end anonymous namespace
122 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
124 return new X86MCCodeEmitter(TM, false);
127 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
129 return new X86MCCodeEmitter(TM, true);
133 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
134 /// sign-extended field.
135 static bool isDisp8(int Value) {
136 return Value == (signed char)Value;
139 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
140 /// in an instruction with the specified TSFlags.
141 static MCFixupKind getImmFixupKind(unsigned TSFlags) {
142 unsigned Size = X86II::getSizeOfImm(TSFlags);
143 bool isPCRel = X86II::isImmPCRel(TSFlags);
146 default: assert(0 && "Unknown immediate size");
147 case 1: return isPCRel ? MCFixupKind(X86::reloc_pcrel_1byte) : FK_Data_1;
148 case 4: return isPCRel ? MCFixupKind(X86::reloc_pcrel_4byte) : FK_Data_4;
149 case 2: assert(!isPCRel); return FK_Data_2;
150 case 8: assert(!isPCRel); return FK_Data_8;
155 void X86MCCodeEmitter::
156 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
157 unsigned &CurByte, raw_ostream &OS,
158 SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
159 // If this is a simple integer displacement that doesn't require a relocation,
161 if (DispOp.isImm()) {
162 EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
166 // If we have an immoffset, add it to the expression.
167 const MCExpr *Expr = DispOp.getExpr();
168 // FIXME: NO CONTEXT.
170 // Emit a symbolic constant as a fixup and 4 zeros.
171 Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
172 EmitConstant(0, Size, CurByte, OS);
176 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
177 unsigned RegOpcodeField,
178 unsigned TSFlags, unsigned &CurByte,
180 SmallVectorImpl<MCFixup> &Fixups) const{
181 const MCOperand &Disp = MI.getOperand(Op+3);
182 const MCOperand &Base = MI.getOperand(Op);
183 const MCOperand &Scale = MI.getOperand(Op+1);
184 const MCOperand &IndexReg = MI.getOperand(Op+2);
185 unsigned BaseReg = Base.getReg();
187 // Handle %rip relative addressing.
188 if (BaseReg == X86::RIP) { // [disp32+RIP] in X86-64 mode
189 assert(IndexReg.getReg() == 0 && Is64BitMode &&
190 "Invalid rip-relative address");
191 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
193 // rip-relative addressing is actually relative to the *next* instruction.
194 // Since an immediate can follow the mod/rm byte for an instruction, this
195 // means that we need to bias the immediate field of the instruction with
196 // the size of the immediate field. If we have this case, add it into the
197 // expression to emit.
198 int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
199 EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_riprel_4byte),
200 CurByte, OS, Fixups, -ImmSize);
204 unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
206 // Determine whether a SIB byte is needed.
207 // If no BaseReg, issue a RIP relative instruction only if the MCE can
208 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
209 // 2-7) and absolute references.
211 if (// The SIB byte must be used if there is an index register.
212 IndexReg.getReg() == 0 &&
213 // The SIB byte must be used if the base is ESP/RSP/R12, all of which
214 // encode to an R/M value of 4, which indicates that a SIB byte is
216 BaseRegNo != N86::ESP &&
217 // If there is no base register and we're in 64-bit mode, we need a SIB
218 // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
219 (!Is64BitMode || BaseReg != 0)) {
221 if (BaseReg == 0) { // [disp32] in X86-32 mode
222 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
223 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
227 // If the base is not EBP/ESP and there is no displacement, use simple
228 // indirect register encoding, this handles addresses like [EAX]. The
229 // encoding for [EBP] with no displacement means [disp32] so we handle it
230 // by emitting a displacement of 0 below.
231 if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
232 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
236 // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
237 if (Disp.isImm() && isDisp8(Disp.getImm())) {
238 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
239 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
243 // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
244 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
245 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
249 // We need a SIB byte, so start by outputting the ModR/M byte first
250 assert(IndexReg.getReg() != X86::ESP &&
251 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
253 bool ForceDisp32 = false;
254 bool ForceDisp8 = false;
256 // If there is no base register, we emit the special case SIB byte with
257 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
258 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
260 } else if (!Disp.isImm()) {
261 // Emit the normal disp32 encoding.
262 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
264 } else if (Disp.getImm() == 0 && BaseReg != X86::EBP) {
265 // Emit no displacement ModR/M byte
266 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
267 } else if (isDisp8(Disp.getImm())) {
268 // Emit the disp8 encoding.
269 EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
270 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
272 // Emit the normal disp32 encoding.
273 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
276 // Calculate what the SS field value should be...
277 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
278 unsigned SS = SSTable[Scale.getImm()];
281 // Handle the SIB byte for the case where there is no base, see Intel
282 // Manual 2A, table 2-7. The displacement has already been output.
284 if (IndexReg.getReg())
285 IndexRegNo = GetX86RegNum(IndexReg);
286 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
288 EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
291 if (IndexReg.getReg())
292 IndexRegNo = GetX86RegNum(IndexReg);
294 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
295 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
298 // Do we need to output a displacement?
300 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
301 else if (ForceDisp32 || Disp.getImm() != 0)
302 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
305 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
306 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
307 /// size, and 3) use of X86-64 extended registers.
308 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
309 const TargetInstrDesc &Desc) {
310 // Pseudo instructions shouldn't get here.
311 assert((TSFlags & X86II::FormMask) != X86II::Pseudo &&
312 "Can't encode pseudo instrs");
315 if (TSFlags & X86II::REX_W)
318 if (MI.getNumOperands() == 0) return REX;
320 unsigned NumOps = MI.getNumOperands();
321 // FIXME: MCInst should explicitize the two-addrness.
322 bool isTwoAddr = NumOps > 1 &&
323 Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
325 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
326 unsigned i = isTwoAddr ? 1 : 0;
327 for (; i != NumOps; ++i) {
328 const MCOperand &MO = MI.getOperand(i);
329 if (!MO.isReg()) continue;
330 unsigned Reg = MO.getReg();
331 if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
332 // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
333 // that returns non-zero.
338 switch (TSFlags & X86II::FormMask) {
339 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
340 case X86II::MRMSrcReg:
341 if (MI.getOperand(0).isReg() &&
342 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
344 i = isTwoAddr ? 2 : 1;
345 for (; i != NumOps; ++i) {
346 const MCOperand &MO = MI.getOperand(i);
347 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
351 case X86II::MRMSrcMem: {
352 if (MI.getOperand(0).isReg() &&
353 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
356 i = isTwoAddr ? 2 : 1;
357 for (; i != NumOps; ++i) {
358 const MCOperand &MO = MI.getOperand(i);
360 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
367 case X86II::MRM0m: case X86II::MRM1m:
368 case X86II::MRM2m: case X86II::MRM3m:
369 case X86II::MRM4m: case X86II::MRM5m:
370 case X86II::MRM6m: case X86II::MRM7m:
371 case X86II::MRMDestMem: {
372 unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
373 i = isTwoAddr ? 1 : 0;
374 if (NumOps > e && MI.getOperand(e).isReg() &&
375 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
378 for (; i != e; ++i) {
379 const MCOperand &MO = MI.getOperand(i);
381 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
389 if (MI.getOperand(0).isReg() &&
390 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
392 i = isTwoAddr ? 2 : 1;
393 for (unsigned e = NumOps; i != e; ++i) {
394 const MCOperand &MO = MI.getOperand(i);
395 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
403 void X86MCCodeEmitter::
404 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
405 SmallVectorImpl<MCFixup> &Fixups) const {
406 unsigned Opcode = MI.getOpcode();
407 const TargetInstrDesc &Desc = TII.get(Opcode);
408 unsigned TSFlags = Desc.TSFlags;
410 // Keep track of the current byte being emitted.
411 unsigned CurByte = 0;
413 // FIXME: We should emit the prefixes in exactly the same order as GAS does,
414 // in order to provide diffability.
416 // Emit the lock opcode prefix as needed.
417 if (TSFlags & X86II::LOCK)
418 EmitByte(0xF0, CurByte, OS);
420 // Emit segment override opcode prefix as needed.
421 switch (TSFlags & X86II::SegOvrMask) {
422 default: assert(0 && "Invalid segment!");
423 case 0: break; // No segment override!
425 EmitByte(0x64, CurByte, OS);
428 EmitByte(0x65, CurByte, OS);
432 // Emit the repeat opcode prefix as needed.
433 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
434 EmitByte(0xF3, CurByte, OS);
436 // Emit the operand size opcode prefix as needed.
437 if (TSFlags & X86II::OpSize)
438 EmitByte(0x66, CurByte, OS);
440 // Emit the address size opcode prefix as needed.
441 if (TSFlags & X86II::AdSize)
442 EmitByte(0x67, CurByte, OS);
444 bool Need0FPrefix = false;
445 switch (TSFlags & X86II::Op0Mask) {
446 default: assert(0 && "Invalid prefix!");
447 case 0: break; // No prefix!
448 case X86II::REP: break; // already handled.
449 case X86II::TB: // Two-byte opcode prefix
450 case X86II::T8: // 0F 38
451 case X86II::TA: // 0F 3A
454 case X86II::TF: // F2 0F 38
455 EmitByte(0xF2, CurByte, OS);
458 case X86II::XS: // F3 0F
459 EmitByte(0xF3, CurByte, OS);
462 case X86II::XD: // F2 0F
463 EmitByte(0xF2, CurByte, OS);
466 case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
467 case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
468 case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
469 case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
470 case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
471 case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
472 case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
473 case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
476 // Handle REX prefix.
477 // FIXME: Can this come before F2 etc to simplify emission?
479 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
480 EmitByte(0x40 | REX, CurByte, OS);
483 // 0x0F escape code must be emitted just before the opcode.
485 EmitByte(0x0F, CurByte, OS);
487 // FIXME: Pull this up into previous switch if REX can be moved earlier.
488 switch (TSFlags & X86II::Op0Mask) {
489 case X86II::TF: // F2 0F 38
490 case X86II::T8: // 0F 38
491 EmitByte(0x38, CurByte, OS);
493 case X86II::TA: // 0F 3A
494 EmitByte(0x3A, CurByte, OS);
498 // If this is a two-address instruction, skip one of the register operands.
499 unsigned NumOps = Desc.getNumOperands();
501 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
503 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
504 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
507 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
508 switch (TSFlags & X86II::FormMask) {
509 case X86II::MRMInitReg:
510 assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
511 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
512 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
514 EmitByte(BaseOpcode, CurByte, OS);
517 case X86II::AddRegFrm:
518 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
521 case X86II::MRMDestReg:
522 EmitByte(BaseOpcode, CurByte, OS);
523 EmitRegModRMByte(MI.getOperand(CurOp),
524 GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
528 case X86II::MRMDestMem:
529 EmitByte(BaseOpcode, CurByte, OS);
530 EmitMemModRMByte(MI, CurOp,
531 GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
532 TSFlags, CurByte, OS, Fixups);
533 CurOp += X86AddrNumOperands + 1;
536 case X86II::MRMSrcReg:
537 EmitByte(BaseOpcode, CurByte, OS);
538 EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
543 case X86II::MRMSrcMem: {
544 EmitByte(BaseOpcode, CurByte, OS);
546 // FIXME: Maybe lea should have its own form? This is a horrible hack.
548 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
549 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
550 AddrOperands = X86AddrNumOperands - 1; // No segment register
552 AddrOperands = X86AddrNumOperands;
554 EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
555 TSFlags, CurByte, OS, Fixups);
556 CurOp += AddrOperands + 1;
560 case X86II::MRM0r: case X86II::MRM1r:
561 case X86II::MRM2r: case X86II::MRM3r:
562 case X86II::MRM4r: case X86II::MRM5r:
563 case X86II::MRM6r: case X86II::MRM7r:
564 EmitByte(BaseOpcode, CurByte, OS);
566 // Special handling of lfence, mfence, monitor, and mwait.
567 // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
568 if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
569 Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
570 EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r,
571 Opcode == X86::MWAIT),
574 EmitRegModRMByte(MI.getOperand(CurOp++),
575 (TSFlags & X86II::FormMask)-X86II::MRM0r,
579 case X86II::MRM0m: case X86II::MRM1m:
580 case X86II::MRM2m: case X86II::MRM3m:
581 case X86II::MRM4m: case X86II::MRM5m:
582 case X86II::MRM6m: case X86II::MRM7m:
583 EmitByte(BaseOpcode, CurByte, OS);
584 EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
585 TSFlags, CurByte, OS, Fixups);
586 CurOp += X86AddrNumOperands;
589 EmitByte(BaseOpcode, CurByte, OS);
590 EmitByte(0xC1, CurByte, OS);
593 EmitByte(BaseOpcode, CurByte, OS);
594 EmitByte(0xC8, CurByte, OS);
597 EmitByte(BaseOpcode, CurByte, OS);
598 EmitByte(0xC9, CurByte, OS);
601 EmitByte(BaseOpcode, CurByte, OS);
602 EmitByte(0xE8, CurByte, OS);
605 EmitByte(BaseOpcode, CurByte, OS);
606 EmitByte(0xF0, CurByte, OS);
610 // If there is a remaining operand, it must be a trailing immediate. Emit it
611 // according to the right size for the instruction.
612 // FIXME: This should pass in whether the value is pc relative or not. This
613 // information should be aquired from TSFlags as well.
615 EmitImmediate(MI.getOperand(CurOp++),
616 X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
617 CurByte, OS, Fixups);
621 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
622 errs() << "Cannot encode all operands of: ";