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 &,
125 return new X86MCCodeEmitter(TM, false);
128 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
131 return new X86MCCodeEmitter(TM, true);
135 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
136 /// sign-extended field.
137 static bool isDisp8(int Value) {
138 return Value == (signed char)Value;
141 /// getImmFixupKind - Return the appropriate fixup kind to use for an immediate
142 /// in an instruction with the specified TSFlags.
143 static MCFixupKind getImmFixupKind(unsigned TSFlags) {
144 unsigned Size = X86II::getSizeOfImm(TSFlags);
145 bool isPCRel = X86II::isImmPCRel(TSFlags);
148 default: assert(0 && "Unknown immediate size");
149 case 1: return isPCRel ? MCFixupKind(X86::reloc_pcrel_1byte) : FK_Data_1;
150 case 4: return isPCRel ? MCFixupKind(X86::reloc_pcrel_4byte) : FK_Data_4;
151 case 2: assert(!isPCRel); return FK_Data_2;
152 case 8: assert(!isPCRel); return FK_Data_8;
157 void X86MCCodeEmitter::
158 EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKind,
159 unsigned &CurByte, raw_ostream &OS,
160 SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
161 // If this is a simple integer displacement that doesn't require a relocation,
163 if (DispOp.isImm()) {
164 EmitConstant(DispOp.getImm()+ImmOffset, Size, CurByte, OS);
168 // If we have an immoffset, add it to the expression.
169 const MCExpr *Expr = DispOp.getExpr();
170 // FIXME: NO CONTEXT.
172 // Emit a symbolic constant as a fixup and 4 zeros.
173 Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
174 EmitConstant(0, Size, CurByte, OS);
178 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
179 unsigned RegOpcodeField,
180 unsigned TSFlags, unsigned &CurByte,
182 SmallVectorImpl<MCFixup> &Fixups) const{
183 const MCOperand &Disp = MI.getOperand(Op+3);
184 const MCOperand &Base = MI.getOperand(Op);
185 const MCOperand &Scale = MI.getOperand(Op+1);
186 const MCOperand &IndexReg = MI.getOperand(Op+2);
187 unsigned BaseReg = Base.getReg();
189 // Handle %rip relative addressing.
190 if (BaseReg == X86::RIP) { // [disp32+RIP] in X86-64 mode
191 assert(IndexReg.getReg() == 0 && Is64BitMode &&
192 "Invalid rip-relative address");
193 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
195 // rip-relative addressing is actually relative to the *next* instruction.
196 // Since an immediate can follow the mod/rm byte for an instruction, this
197 // means that we need to bias the immediate field of the instruction with
198 // the size of the immediate field. If we have this case, add it into the
199 // expression to emit.
200 int ImmSize = X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) : 0;
201 EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_riprel_4byte),
202 CurByte, OS, Fixups, -ImmSize);
206 unsigned BaseRegNo = BaseReg ? GetX86RegNum(Base) : -1U;
208 // Determine whether a SIB byte is needed.
209 // If no BaseReg, issue a RIP relative instruction only if the MCE can
210 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
211 // 2-7) and absolute references.
213 if (// The SIB byte must be used if there is an index register.
214 IndexReg.getReg() == 0 &&
215 // The SIB byte must be used if the base is ESP/RSP/R12, all of which
216 // encode to an R/M value of 4, which indicates that a SIB byte is
218 BaseRegNo != N86::ESP &&
219 // If there is no base register and we're in 64-bit mode, we need a SIB
220 // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
221 (!Is64BitMode || BaseReg != 0)) {
223 if (BaseReg == 0) { // [disp32] in X86-32 mode
224 EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
225 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
229 // If the base is not EBP/ESP and there is no displacement, use simple
230 // indirect register encoding, this handles addresses like [EAX]. The
231 // encoding for [EBP] with no displacement means [disp32] so we handle it
232 // by emitting a displacement of 0 below.
233 if (Disp.isImm() && Disp.getImm() == 0 && BaseRegNo != N86::EBP) {
234 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), CurByte, OS);
238 // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
239 if (Disp.isImm() && isDisp8(Disp.getImm())) {
240 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
241 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
245 // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
246 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
247 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
251 // We need a SIB byte, so start by outputting the ModR/M byte first
252 assert(IndexReg.getReg() != X86::ESP &&
253 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
255 bool ForceDisp32 = false;
256 bool ForceDisp8 = false;
258 // If there is no base register, we emit the special case SIB byte with
259 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
260 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
262 } else if (!Disp.isImm()) {
263 // Emit the normal disp32 encoding.
264 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
266 } else if (Disp.getImm() == 0 && BaseReg != X86::EBP) {
267 // Emit no displacement ModR/M byte
268 EmitByte(ModRMByte(0, RegOpcodeField, 4), CurByte, OS);
269 } else if (isDisp8(Disp.getImm())) {
270 // Emit the disp8 encoding.
271 EmitByte(ModRMByte(1, RegOpcodeField, 4), CurByte, OS);
272 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
274 // Emit the normal disp32 encoding.
275 EmitByte(ModRMByte(2, RegOpcodeField, 4), CurByte, OS);
278 // Calculate what the SS field value should be...
279 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
280 unsigned SS = SSTable[Scale.getImm()];
283 // Handle the SIB byte for the case where there is no base, see Intel
284 // Manual 2A, table 2-7. The displacement has already been output.
286 if (IndexReg.getReg())
287 IndexRegNo = GetX86RegNum(IndexReg);
288 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
290 EmitSIBByte(SS, IndexRegNo, 5, CurByte, OS);
293 if (IndexReg.getReg())
294 IndexRegNo = GetX86RegNum(IndexReg);
296 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
297 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), CurByte, OS);
300 // Do we need to output a displacement?
302 EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
303 else if (ForceDisp32 || Disp.getImm() != 0)
304 EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
307 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
308 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
309 /// size, and 3) use of X86-64 extended registers.
310 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
311 const TargetInstrDesc &Desc) {
312 // Pseudo instructions shouldn't get here.
313 assert((TSFlags & X86II::FormMask) != X86II::Pseudo &&
314 "Can't encode pseudo instrs");
317 if (TSFlags & X86II::REX_W)
320 if (MI.getNumOperands() == 0) return REX;
322 unsigned NumOps = MI.getNumOperands();
323 // FIXME: MCInst should explicitize the two-addrness.
324 bool isTwoAddr = NumOps > 1 &&
325 Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
327 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
328 unsigned i = isTwoAddr ? 1 : 0;
329 for (; i != NumOps; ++i) {
330 const MCOperand &MO = MI.getOperand(i);
331 if (!MO.isReg()) continue;
332 unsigned Reg = MO.getReg();
333 if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
334 // FIXME: The caller of DetermineREXPrefix slaps this prefix onto anything
335 // that returns non-zero.
340 switch (TSFlags & X86II::FormMask) {
341 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
342 case X86II::MRMSrcReg:
343 if (MI.getOperand(0).isReg() &&
344 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
346 i = isTwoAddr ? 2 : 1;
347 for (; i != NumOps; ++i) {
348 const MCOperand &MO = MI.getOperand(i);
349 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
353 case X86II::MRMSrcMem: {
354 if (MI.getOperand(0).isReg() &&
355 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
358 i = isTwoAddr ? 2 : 1;
359 for (; i != NumOps; ++i) {
360 const MCOperand &MO = MI.getOperand(i);
362 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
369 case X86II::MRM0m: case X86II::MRM1m:
370 case X86II::MRM2m: case X86II::MRM3m:
371 case X86II::MRM4m: case X86II::MRM5m:
372 case X86II::MRM6m: case X86II::MRM7m:
373 case X86II::MRMDestMem: {
374 unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
375 i = isTwoAddr ? 1 : 0;
376 if (NumOps > e && MI.getOperand(e).isReg() &&
377 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
380 for (; i != e; ++i) {
381 const MCOperand &MO = MI.getOperand(i);
383 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
391 if (MI.getOperand(0).isReg() &&
392 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
394 i = isTwoAddr ? 2 : 1;
395 for (unsigned e = NumOps; i != e; ++i) {
396 const MCOperand &MO = MI.getOperand(i);
397 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
405 void X86MCCodeEmitter::
406 EncodeInstruction(const MCInst &MI, raw_ostream &OS,
407 SmallVectorImpl<MCFixup> &Fixups) const {
408 unsigned Opcode = MI.getOpcode();
409 const TargetInstrDesc &Desc = TII.get(Opcode);
410 unsigned TSFlags = Desc.TSFlags;
412 // Keep track of the current byte being emitted.
413 unsigned CurByte = 0;
415 // FIXME: We should emit the prefixes in exactly the same order as GAS does,
416 // in order to provide diffability.
418 // Emit the lock opcode prefix as needed.
419 if (TSFlags & X86II::LOCK)
420 EmitByte(0xF0, CurByte, OS);
422 // Emit segment override opcode prefix as needed.
423 switch (TSFlags & X86II::SegOvrMask) {
424 default: assert(0 && "Invalid segment!");
425 case 0: break; // No segment override!
427 EmitByte(0x64, CurByte, OS);
430 EmitByte(0x65, CurByte, OS);
434 // Emit the repeat opcode prefix as needed.
435 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
436 EmitByte(0xF3, CurByte, OS);
438 // Emit the operand size opcode prefix as needed.
439 if (TSFlags & X86II::OpSize)
440 EmitByte(0x66, CurByte, OS);
442 // Emit the address size opcode prefix as needed.
443 if (TSFlags & X86II::AdSize)
444 EmitByte(0x67, CurByte, OS);
446 bool Need0FPrefix = false;
447 switch (TSFlags & X86II::Op0Mask) {
448 default: assert(0 && "Invalid prefix!");
449 case 0: break; // No prefix!
450 case X86II::REP: break; // already handled.
451 case X86II::TB: // Two-byte opcode prefix
452 case X86II::T8: // 0F 38
453 case X86II::TA: // 0F 3A
456 case X86II::TF: // F2 0F 38
457 EmitByte(0xF2, CurByte, OS);
460 case X86II::XS: // F3 0F
461 EmitByte(0xF3, CurByte, OS);
464 case X86II::XD: // F2 0F
465 EmitByte(0xF2, CurByte, OS);
468 case X86II::D8: EmitByte(0xD8, CurByte, OS); break;
469 case X86II::D9: EmitByte(0xD9, CurByte, OS); break;
470 case X86II::DA: EmitByte(0xDA, CurByte, OS); break;
471 case X86II::DB: EmitByte(0xDB, CurByte, OS); break;
472 case X86II::DC: EmitByte(0xDC, CurByte, OS); break;
473 case X86II::DD: EmitByte(0xDD, CurByte, OS); break;
474 case X86II::DE: EmitByte(0xDE, CurByte, OS); break;
475 case X86II::DF: EmitByte(0xDF, CurByte, OS); break;
478 // Handle REX prefix.
479 // FIXME: Can this come before F2 etc to simplify emission?
481 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
482 EmitByte(0x40 | REX, CurByte, OS);
485 // 0x0F escape code must be emitted just before the opcode.
487 EmitByte(0x0F, CurByte, OS);
489 // FIXME: Pull this up into previous switch if REX can be moved earlier.
490 switch (TSFlags & X86II::Op0Mask) {
491 case X86II::TF: // F2 0F 38
492 case X86II::T8: // 0F 38
493 EmitByte(0x38, CurByte, OS);
495 case X86II::TA: // 0F 3A
496 EmitByte(0x3A, CurByte, OS);
500 // If this is a two-address instruction, skip one of the register operands.
501 unsigned NumOps = Desc.getNumOperands();
503 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
505 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
506 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
509 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
510 switch (TSFlags & X86II::FormMask) {
511 case X86II::MRMInitReg:
512 assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
513 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
514 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
516 EmitByte(BaseOpcode, CurByte, OS);
519 case X86II::AddRegFrm:
520 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)), CurByte, OS);
523 case X86II::MRMDestReg:
524 EmitByte(BaseOpcode, CurByte, OS);
525 EmitRegModRMByte(MI.getOperand(CurOp),
526 GetX86RegNum(MI.getOperand(CurOp+1)), CurByte, OS);
530 case X86II::MRMDestMem:
531 EmitByte(BaseOpcode, CurByte, OS);
532 EmitMemModRMByte(MI, CurOp,
533 GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
534 TSFlags, CurByte, OS, Fixups);
535 CurOp += X86AddrNumOperands + 1;
538 case X86II::MRMSrcReg:
539 EmitByte(BaseOpcode, CurByte, OS);
540 EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
545 case X86II::MRMSrcMem: {
546 EmitByte(BaseOpcode, CurByte, OS);
548 // FIXME: Maybe lea should have its own form? This is a horrible hack.
550 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
551 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
552 AddrOperands = X86AddrNumOperands - 1; // No segment register
554 AddrOperands = X86AddrNumOperands;
556 EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
557 TSFlags, CurByte, OS, Fixups);
558 CurOp += AddrOperands + 1;
562 case X86II::MRM0r: case X86II::MRM1r:
563 case X86II::MRM2r: case X86II::MRM3r:
564 case X86II::MRM4r: case X86II::MRM5r:
565 case X86II::MRM6r: case X86II::MRM7r:
566 EmitByte(BaseOpcode, CurByte, OS);
568 // Special handling of lfence, mfence, monitor, and mwait.
569 // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
570 if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
571 Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
572 EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r,
573 Opcode == X86::MWAIT),
576 EmitRegModRMByte(MI.getOperand(CurOp++),
577 (TSFlags & X86II::FormMask)-X86II::MRM0r,
581 case X86II::MRM0m: case X86II::MRM1m:
582 case X86II::MRM2m: case X86II::MRM3m:
583 case X86II::MRM4m: case X86II::MRM5m:
584 case X86II::MRM6m: case X86II::MRM7m:
585 EmitByte(BaseOpcode, CurByte, OS);
586 EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
587 TSFlags, CurByte, OS, Fixups);
588 CurOp += X86AddrNumOperands;
591 EmitByte(BaseOpcode, CurByte, OS);
592 EmitByte(0xC1, CurByte, OS);
595 EmitByte(BaseOpcode, CurByte, OS);
596 EmitByte(0xC8, CurByte, OS);
599 EmitByte(BaseOpcode, CurByte, OS);
600 EmitByte(0xC9, CurByte, OS);
603 EmitByte(BaseOpcode, CurByte, OS);
604 EmitByte(0xE8, CurByte, OS);
607 EmitByte(BaseOpcode, CurByte, OS);
608 EmitByte(0xF0, CurByte, OS);
612 // If there is a remaining operand, it must be a trailing immediate. Emit it
613 // according to the right size for the instruction.
614 // FIXME: This should pass in whether the value is pc relative or not. This
615 // information should be aquired from TSFlags as well.
617 EmitImmediate(MI.getOperand(CurOp++),
618 X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
619 CurByte, OS, Fixups);
623 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
624 errs() << "Cannot encode all operands of: ";