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,
84 unsigned ImmSize, MCFixupKind FixupKind,
85 unsigned &CurByte, raw_ostream &OS,
86 SmallVectorImpl<MCFixup> &Fixups) const;
88 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
90 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
91 return RM | (RegOpcode << 3) | (Mod << 6);
94 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
95 unsigned &CurByte, raw_ostream &OS) const {
96 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), CurByte, OS);
99 void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
100 unsigned &CurByte, raw_ostream &OS) const {
101 // SIB byte is in the same format as the ModRMByte.
102 EmitByte(ModRMByte(SS, Index, Base), CurByte, OS);
106 void EmitMemModRMByte(const MCInst &MI, unsigned Op,
107 unsigned RegOpcodeField,
108 unsigned &CurByte, raw_ostream &OS,
109 SmallVectorImpl<MCFixup> &Fixups) const;
111 void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
112 SmallVectorImpl<MCFixup> &Fixups) const;
116 } // end anonymous namespace
119 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
121 return new X86MCCodeEmitter(TM, false);
124 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
126 return new X86MCCodeEmitter(TM, true);
130 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
131 /// sign-extended field.
132 static bool isDisp8(int Value) {
133 return Value == (signed char)Value;
136 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
137 /// in an instruction with the specified TSFlags.
138 static MCFixupKind getImmFixupKind(unsigned TSFlags) {
139 unsigned Size = X86II::getSizeOfImm(TSFlags);
140 bool isPCRel = X86II::isImmPCRel(TSFlags);
143 default: assert(0 && "Unknown immediate size");
144 case 1: return isPCRel ? MCFixupKind(X86::reloc_pcrel_1byte) : FK_Data_1;
145 case 4: return isPCRel ? MCFixupKind(X86::reloc_pcrel_4byte) : FK_Data_4;
146 case 2: assert(!isPCRel); return FK_Data_2;
147 case 8: assert(!isPCRel); return FK_Data_8;
152 void X86MCCodeEmitter::
153 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
154 unsigned &CurByte, raw_ostream &OS,
155 SmallVectorImpl<MCFixup> &Fixups) const {
156 // If this is a simple integer displacement that doesn't require a relocation,
158 if (DispOp.isImm()) {
159 EmitConstant(DispOp.getImm(), Size, CurByte, OS);
163 // Emit a symbolic constant as a fixup and 4 zeros.
164 Fixups.push_back(MCFixup::Create(CurByte, DispOp.getExpr(), FixupKind));
165 EmitConstant(0, Size, CurByte, OS);
169 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
170 unsigned RegOpcodeField,
173 SmallVectorImpl<MCFixup> &Fixups) const{
174 const MCOperand &Disp = MI.getOperand(Op+3);
175 const MCOperand &Base = MI.getOperand(Op);
176 const MCOperand &Scale = MI.getOperand(Op+1);
177 const MCOperand &IndexReg = MI.getOperand(Op+2);
178 unsigned BaseReg = Base.getReg();
179 unsigned BaseRegNo = -1U;
180 if (BaseReg != 0 && BaseReg != X86::RIP)
181 BaseRegNo = GetX86RegNum(Base);
183 // Determine whether a SIB byte is needed.
184 // If no BaseReg, issue a RIP relative instruction only if the MCE can
185 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
186 // 2-7) and absolute references.
188 if (// The SIB byte must be used if there is an index register.
189 IndexReg.getReg() == 0 &&
190 // The SIB byte must be used if the base is ESP/RSP/R12, all of which
191 // encode to an R/M value of 4, which indicates that a SIB byte is
193 BaseRegNo != N86::ESP &&
194 // If there is no base register and we're in 64-bit mode, we need a SIB
195 // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
196 (!Is64BitMode || BaseReg != 0)) {
198 if (BaseReg == 0 || // [disp32] in X86-32 mode
199 BaseReg == X86::RIP) { // [disp32+RIP] in X86-64 mode
200 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
201 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
205 // If the base is not EBP/ESP and there is no displacement, use simple
206 // indirect register encoding, this handles addresses like [EAX]. The
207 // encoding for [EBP] with no displacement means [disp32] so we handle it
208 // by emitting a displacement of 0 below.
209 if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
210 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
214 // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
215 if (Disp.isImm() && isDisp8(Disp.getImm())) {
216 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
217 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
221 // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
222 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
223 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
227 // We need a SIB byte, so start by outputting the ModR/M byte first
228 assert(IndexReg.getReg() != X86::ESP &&
229 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
231 bool ForceDisp32 = false;
232 bool ForceDisp8 = false;
234 // If there is no base register, we emit the special case SIB byte with
235 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
236 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
238 } else if (!Disp.isImm()) {
239 // Emit the normal disp32 encoding.
240 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
242 } else if (Disp.getImm() == 0 && BaseReg != X86::EBP) {
243 // Emit no displacement ModR/M byte
244 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
245 } else if (isDisp8(Disp.getImm())) {
246 // Emit the disp8 encoding.
247 EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
248 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
250 // Emit the normal disp32 encoding.
251 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
254 // Calculate what the SS field value should be...
255 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
256 unsigned SS = SSTable[Scale.getImm()];
259 // Handle the SIB byte for the case where there is no base, see Intel
260 // Manual 2A, table 2-7. The displacement has already been output.
262 if (IndexReg.getReg())
263 IndexRegNo = GetX86RegNum(IndexReg);
264 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
266 EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
269 if (IndexReg.getReg())
270 IndexRegNo = GetX86RegNum(IndexReg);
272 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
273 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
276 // Do we need to output a displacement?
278 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
279 else if (ForceDisp32 || Disp.getImm() != 0)
280 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
283 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
284 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
285 /// size, and 3) use of X86-64 extended registers.
286 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
287 const TargetInstrDesc &Desc) {
288 // Pseudo instructions shouldn't get here.
289 assert((TSFlags & X86II::FormMask) != X86II::Pseudo &&
290 "Can't encode pseudo instrs");
293 if (TSFlags & X86II::REX_W)
296 if (MI.getNumOperands() == 0) return REX;
298 unsigned NumOps = MI.getNumOperands();
299 // FIXME: MCInst should explicitize the two-addrness.
300 bool isTwoAddr = NumOps > 1 &&
301 Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
303 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
304 unsigned i = isTwoAddr ? 1 : 0;
305 for (; i != NumOps; ++i) {
306 const MCOperand &MO = MI.getOperand(i);
307 if (!MO.isReg()) continue;
308 unsigned Reg = MO.getReg();
309 if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
310 // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
311 // that returns non-zero.
316 switch (TSFlags & X86II::FormMask) {
317 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
318 case X86II::MRMSrcReg:
319 if (MI.getOperand(0).isReg() &&
320 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
322 i = isTwoAddr ? 2 : 1;
323 for (; i != NumOps; ++i) {
324 const MCOperand &MO = MI.getOperand(i);
325 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
329 case X86II::MRMSrcMem: {
330 if (MI.getOperand(0).isReg() &&
331 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
334 i = isTwoAddr ? 2 : 1;
335 for (; i != NumOps; ++i) {
336 const MCOperand &MO = MI.getOperand(i);
338 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
345 case X86II::MRM0m: case X86II::MRM1m:
346 case X86II::MRM2m: case X86II::MRM3m:
347 case X86II::MRM4m: case X86II::MRM5m:
348 case X86II::MRM6m: case X86II::MRM7m:
349 case X86II::MRMDestMem: {
350 unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
351 i = isTwoAddr ? 1 : 0;
352 if (NumOps > e && MI.getOperand(e).isReg() &&
353 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
356 for (; i != e; ++i) {
357 const MCOperand &MO = MI.getOperand(i);
359 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
367 if (MI.getOperand(0).isReg() &&
368 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
370 i = isTwoAddr ? 2 : 1;
371 for (unsigned e = NumOps; i != e; ++i) {
372 const MCOperand &MO = MI.getOperand(i);
373 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
381 void X86MCCodeEmitter::
382 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
383 SmallVectorImpl<MCFixup> &Fixups) const {
384 unsigned Opcode = MI.getOpcode();
385 const TargetInstrDesc &Desc = TII.get(Opcode);
386 unsigned TSFlags = Desc.TSFlags;
388 // Keep track of the current byte being emitted.
389 unsigned CurByte = 0;
391 // FIXME: We should emit the prefixes in exactly the same order as GAS does,
392 // in order to provide diffability.
394 // Emit the lock opcode prefix as needed.
395 if (TSFlags & X86II::LOCK)
396 EmitByte(0xF0, CurByte, OS);
398 // Emit segment override opcode prefix as needed.
399 switch (TSFlags & X86II::SegOvrMask) {
400 default: assert(0 && "Invalid segment!");
401 case 0: break; // No segment override!
403 EmitByte(0x64, CurByte, OS);
406 EmitByte(0x65, CurByte, OS);
410 // Emit the repeat opcode prefix as needed.
411 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
412 EmitByte(0xF3, CurByte, OS);
414 // Emit the operand size opcode prefix as needed.
415 if (TSFlags & X86II::OpSize)
416 EmitByte(0x66, CurByte, OS);
418 // Emit the address size opcode prefix as needed.
419 if (TSFlags & X86II::AdSize)
420 EmitByte(0x67, CurByte, OS);
422 bool Need0FPrefix = false;
423 switch (TSFlags & X86II::Op0Mask) {
424 default: assert(0 && "Invalid prefix!");
425 case 0: break; // No prefix!
426 case X86II::REP: break; // already handled.
427 case X86II::TB: // Two-byte opcode prefix
428 case X86II::T8: // 0F 38
429 case X86II::TA: // 0F 3A
432 case X86II::TF: // F2 0F 38
433 EmitByte(0xF2, CurByte, OS);
436 case X86II::XS: // F3 0F
437 EmitByte(0xF3, CurByte, OS);
440 case X86II::XD: // F2 0F
441 EmitByte(0xF2, CurByte, OS);
444 case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
445 case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
446 case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
447 case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
448 case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
449 case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
450 case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
451 case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
454 // Handle REX prefix.
455 // FIXME: Can this come before F2 etc to simplify emission?
457 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
458 EmitByte(0x40 | REX, CurByte, OS);
461 // 0x0F escape code must be emitted just before the opcode.
463 EmitByte(0x0F, CurByte, OS);
465 // FIXME: Pull this up into previous switch if REX can be moved earlier.
466 switch (TSFlags & X86II::Op0Mask) {
467 case X86II::TF: // F2 0F 38
468 case X86II::T8: // 0F 38
469 EmitByte(0x38, CurByte, OS);
471 case X86II::TA: // 0F 3A
472 EmitByte(0x3A, CurByte, OS);
476 // If this is a two-address instruction, skip one of the register operands.
477 unsigned NumOps = Desc.getNumOperands();
479 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
481 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
482 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
485 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
486 switch (TSFlags & X86II::FormMask) {
487 case X86II::MRMInitReg:
488 assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
489 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
490 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
492 EmitByte(BaseOpcode, CurByte, OS);
495 case X86II::AddRegFrm:
496 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
499 case X86II::MRMDestReg:
500 EmitByte(BaseOpcode, CurByte, OS);
501 EmitRegModRMByte(MI.getOperand(CurOp),
502 GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
506 case X86II::MRMDestMem:
507 EmitByte(BaseOpcode, CurByte, OS);
508 EmitMemModRMByte(MI, CurOp,
509 GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
510 CurByte, OS, Fixups);
511 CurOp += X86AddrNumOperands + 1;
514 case X86II::MRMSrcReg:
515 EmitByte(BaseOpcode, CurByte, OS);
516 EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
521 case X86II::MRMSrcMem: {
522 EmitByte(BaseOpcode, CurByte, OS);
524 // FIXME: Maybe lea should have its own form? This is a horrible hack.
526 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
527 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
528 AddrOperands = X86AddrNumOperands - 1; // No segment register
530 AddrOperands = X86AddrNumOperands;
532 EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
533 CurByte, OS, Fixups);
534 CurOp += AddrOperands + 1;
538 case X86II::MRM0r: case X86II::MRM1r:
539 case X86II::MRM2r: case X86II::MRM3r:
540 case X86II::MRM4r: case X86II::MRM5r:
541 case X86II::MRM6r: case X86II::MRM7r:
542 EmitByte(BaseOpcode, CurByte, OS);
544 // Special handling of lfence, mfence, monitor, and mwait.
545 // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
546 if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
547 Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
548 EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r,
549 Opcode == X86::MWAIT),
552 EmitRegModRMByte(MI.getOperand(CurOp++),
553 (TSFlags & X86II::FormMask)-X86II::MRM0r,
557 case X86II::MRM0m: case X86II::MRM1m:
558 case X86II::MRM2m: case X86II::MRM3m:
559 case X86II::MRM4m: case X86II::MRM5m:
560 case X86II::MRM6m: case X86II::MRM7m:
561 EmitByte(BaseOpcode, CurByte, OS);
562 EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
563 CurByte, OS, Fixups);
564 CurOp += X86AddrNumOperands;
567 EmitByte(BaseOpcode, CurByte, OS);
568 EmitByte(0xC1, CurByte, OS);
571 EmitByte(BaseOpcode, CurByte, OS);
572 EmitByte(0xC8, CurByte, OS);
575 EmitByte(BaseOpcode, CurByte, OS);
576 EmitByte(0xC9, CurByte, OS);
579 EmitByte(BaseOpcode, CurByte, OS);
580 EmitByte(0xE8, CurByte, OS);
583 EmitByte(BaseOpcode, CurByte, OS);
584 EmitByte(0xF0, CurByte, OS);
588 // If there is a remaining operand, it must be a trailing immediate. Emit it
589 // according to the right size for the instruction.
590 // FIXME: This should pass in whether the value is pc relative or not. This
591 // information should be aquired from TSFlags as well.
593 EmitImmediate(MI.getOperand(CurOp++),
594 X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
595 CurByte, OS, Fixups);
599 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
600 errs() << "Cannot encode all operands of: ";