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"
23 class X86MCCodeEmitter : public MCCodeEmitter {
24 X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
25 void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
26 const TargetMachine &TM;
27 const TargetInstrInfo &TII;
30 X86MCCodeEmitter(TargetMachine &tm, bool is64Bit)
31 : TM(tm), TII(*TM.getInstrInfo()) {
32 Is64BitMode = is64Bit;
35 ~X86MCCodeEmitter() {}
37 static unsigned GetX86RegNum(const MCOperand &MO) {
38 return X86RegisterInfo::getX86RegNum(MO.getReg());
41 void EmitByte(unsigned char C, raw_ostream &OS) const {
45 void EmitConstant(uint64_t Val, unsigned Size, raw_ostream &OS) const {
46 // Output the constant in little endian byte order.
47 for (unsigned i = 0; i != Size; ++i) {
48 EmitByte(Val & 255, OS);
53 void EmitDisplacementField(const MCOperand *RelocOp, int DispVal,
54 int64_t Adj, bool IsPCRel, raw_ostream &OS) const;
56 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
58 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
59 return RM | (RegOpcode << 3) | (Mod << 6);
62 void EmitRegModRMByte(const MCOperand &ModRMReg, unsigned RegOpcodeFld,
63 raw_ostream &OS) const {
64 EmitByte(ModRMByte(3, RegOpcodeFld, GetX86RegNum(ModRMReg)), OS);
67 void EmitSIBByte(unsigned SS, unsigned Index, unsigned Base,
68 raw_ostream &OS) const {
69 // SIB byte is in the same format as the ModRMByte...
70 EmitByte(ModRMByte(SS, Index, Base), OS);
74 void EmitMemModRMByte(const MCInst &MI, unsigned Op,
75 unsigned RegOpcodeField, intptr_t PCAdj,
76 raw_ostream &OS) const;
78 void EncodeInstruction(const MCInst &MI, raw_ostream &OS) const;
82 } // end anonymous namespace
85 MCCodeEmitter *llvm::createX86_32MCCodeEmitter(const Target &,
87 return new X86MCCodeEmitter(TM, false);
90 MCCodeEmitter *llvm::createX86_64MCCodeEmitter(const Target &,
92 return new X86MCCodeEmitter(TM, true);
96 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
97 /// sign-extended field.
98 static bool isDisp8(int Value) {
99 return Value == (signed char)Value;
102 void X86MCCodeEmitter::
103 EmitDisplacementField(const MCOperand *RelocOp, int DispVal,
104 int64_t Adj, bool IsPCRel, raw_ostream &OS) const {
105 // If this is a simple integer displacement that doesn't require a relocation,
108 EmitConstant(DispVal, 4, OS);
112 assert(0 && "Reloc not handled yet");
114 // Otherwise, this is something that requires a relocation. Emit it as such
116 unsigned RelocType = Is64BitMode ?
117 (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
118 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
119 if (RelocOp->isGlobal()) {
120 // In 64-bit static small code model, we could potentially emit absolute.
121 // But it's probably not beneficial. If the MCE supports using RIP directly
122 // do it, otherwise fallback to absolute (this is determined by IsPCRel).
123 // 89 05 00 00 00 00 mov %eax,0(%rip) # PC-relative
124 // 89 04 25 00 00 00 00 mov %eax,0x0 # Absolute
125 bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
126 emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
128 } else if (RelocOp->isSymbol()) {
129 emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
130 } else if (RelocOp->isCPI()) {
131 emitConstPoolAddress(RelocOp->getIndex(), RelocType,
132 RelocOp->getOffset(), Adj);
134 assert(RelocOp->isJTI() && "Unexpected machine operand!");
135 emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
141 void X86MCCodeEmitter::EmitMemModRMByte(const MCInst &MI, unsigned Op,
142 unsigned RegOpcodeField,
144 raw_ostream &OS) const {
145 const MCOperand &Op3 = MI.getOperand(Op+3);
147 const MCOperand *DispForReloc = 0;
149 // Figure out what sort of displacement we have to handle here.
151 DispVal = Op3.getImm();
153 assert(0 && "relocatable operand");
155 if (Op3.isGlobal()) {
157 } else if (Op3.isSymbol()) {
159 } else if (Op3.isCPI()) {
160 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
163 DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
164 DispVal += Op3.getOffset();
168 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
171 DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
176 const MCOperand &Base = MI.getOperand(Op);
177 const MCOperand &Scale = MI.getOperand(Op+1);
178 const MCOperand &IndexReg = MI.getOperand(Op+2);
179 unsigned BaseReg = Base.getReg();
182 bool IsPCRel = false;
184 // Is a SIB byte needed?
185 // If no BaseReg, issue a RIP relative instruction only if the MCE can
186 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
187 // 2-7) and absolute references.
188 if ((!Is64BitMode || DispForReloc || BaseReg != 0) &&
189 IndexReg.getReg() == 0 &&
190 (BaseReg == X86::RIP || (BaseReg != 0 && BaseReg != X86::ESP))) {
191 if (BaseReg == 0 || BaseReg == X86::RIP) { // Just a displacement?
192 // Emit special case [disp32] encoding
193 EmitByte(ModRMByte(0, RegOpcodeField, 5), OS);
194 EmitDisplacementField(DispForReloc, DispVal, PCAdj, true, OS);
196 unsigned BaseRegNo = GetX86RegNum(Base);
197 if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
198 // Emit simple indirect register encoding... [EAX] f.e.
199 EmitByte(ModRMByte(0, RegOpcodeField, BaseRegNo), OS);
200 } else if (!DispForReloc && isDisp8(DispVal)) {
201 // Emit the disp8 encoding... [REG+disp8]
202 EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), OS);
203 EmitConstant(DispVal, 1, OS);
205 // Emit the most general non-SIB encoding: [REG+disp32]
206 EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), OS);
207 EmitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel, OS);
213 // We need a SIB byte, so start by outputting the ModR/M byte first
214 assert(IndexReg.getReg() != X86::ESP &&
215 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
217 bool ForceDisp32 = false;
218 bool ForceDisp8 = false;
220 // If there is no base register, we emit the special case SIB byte with
221 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
222 EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
224 } else if (DispForReloc) {
225 // Emit the normal disp32 encoding.
226 EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
228 } else if (DispVal == 0 && BaseReg != X86::EBP) {
229 // Emit no displacement ModR/M byte
230 EmitByte(ModRMByte(0, RegOpcodeField, 4), OS);
231 } else if (isDisp8(DispVal)) {
232 // Emit the disp8 encoding.
233 EmitByte(ModRMByte(1, RegOpcodeField, 4), OS);
234 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
236 // Emit the normal disp32 encoding.
237 EmitByte(ModRMByte(2, RegOpcodeField, 4), OS);
240 // Calculate what the SS field value should be...
241 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
242 unsigned SS = SSTable[Scale.getImm()];
245 // Handle the SIB byte for the case where there is no base, see Intel
246 // Manual 2A, table 2-7. The displacement has already been output.
248 if (IndexReg.getReg())
249 IndexRegNo = GetX86RegNum(IndexReg);
250 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
252 EmitSIBByte(SS, IndexRegNo, 5, OS);
255 if (IndexReg.getReg())
256 IndexRegNo = GetX86RegNum(IndexReg);
258 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
259 EmitSIBByte(SS, IndexRegNo, GetX86RegNum(Base), OS);
262 // Do we need to output a displacement?
264 EmitConstant(DispVal, 1, OS);
265 else if (DispVal != 0 || ForceDisp32)
266 EmitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel, OS);
269 /// DetermineREXPrefix - Determine if the MCInst has to be encoded with a X86-64
270 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
271 /// size, and 3) use of X86-64 extended registers.
272 static unsigned DetermineREXPrefix(const MCInst &MI, unsigned TSFlags,
273 const TargetInstrDesc &Desc) {
276 // Pseudo instructions do not need REX prefix byte.
277 if ((TSFlags & X86II::FormMask) == X86II::Pseudo)
279 if (TSFlags & X86II::REX_W)
282 if (MI.getNumOperands() == 0) return REX;
284 unsigned NumOps = MI.getNumOperands();
285 // FIXME: MCInst should explicitize the two-addrness.
286 bool isTwoAddr = NumOps > 1 &&
287 Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
289 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
290 unsigned i = isTwoAddr ? 1 : 0;
291 for (; i != NumOps; ++i) {
292 const MCOperand &MO = MI.getOperand(i);
293 if (!MO.isReg()) continue;
294 unsigned Reg = MO.getReg();
295 if (!X86InstrInfo::isX86_64NonExtLowByteReg(Reg)) continue;
300 switch (TSFlags & X86II::FormMask) {
301 case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
302 case X86II::MRMSrcReg:
303 if (MI.getOperand(0).isReg() &&
304 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
306 i = isTwoAddr ? 2 : 1;
307 for (; i != NumOps; ++i) {
308 const MCOperand &MO = MI.getOperand(i);
309 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
313 case X86II::MRMSrcMem: {
314 if (MI.getOperand(0).isReg() &&
315 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
318 i = isTwoAddr ? 2 : 1;
319 for (; i != NumOps; ++i) {
320 const MCOperand &MO = MI.getOperand(i);
322 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
329 case X86II::MRM0m: case X86II::MRM1m:
330 case X86II::MRM2m: case X86II::MRM3m:
331 case X86II::MRM4m: case X86II::MRM5m:
332 case X86II::MRM6m: case X86II::MRM7m:
333 case X86II::MRMDestMem: {
334 unsigned e = (isTwoAddr ? X86AddrNumOperands+1 : X86AddrNumOperands);
335 i = isTwoAddr ? 1 : 0;
336 if (NumOps > e && MI.getOperand(e).isReg() &&
337 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e).getReg()))
340 for (; i != e; ++i) {
341 const MCOperand &MO = MI.getOperand(i);
343 if (X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
351 if (MI.getOperand(0).isReg() &&
352 X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
354 i = isTwoAddr ? 2 : 1;
355 for (unsigned e = NumOps; i != e; ++i) {
356 const MCOperand &MO = MI.getOperand(i);
357 if (MO.isReg() && X86InstrInfo::isX86_64ExtendedReg(MO.getReg()))
365 void X86MCCodeEmitter::
366 EncodeInstruction(const MCInst &MI, raw_ostream &OS) const {
367 unsigned Opcode = MI.getOpcode();
368 const TargetInstrDesc &Desc = TII.get(Opcode);
369 unsigned TSFlags = Desc.TSFlags;
371 // FIXME: We should emit the prefixes in exactly the same order as GAS does,
372 // in order to provide diffability.
374 // Emit the lock opcode prefix as needed.
375 if (TSFlags & X86II::LOCK)
378 // Emit segment override opcode prefix as needed.
379 switch (TSFlags & X86II::SegOvrMask) {
380 default: assert(0 && "Invalid segment!");
381 case 0: break; // No segment override!
390 // Emit the repeat opcode prefix as needed.
391 if ((TSFlags & X86II::Op0Mask) == X86II::REP)
394 // Emit the operand size opcode prefix as needed.
395 if (TSFlags & X86II::OpSize)
398 // Emit the address size opcode prefix as needed.
399 if (TSFlags & X86II::AdSize)
402 bool Need0FPrefix = false;
403 switch (TSFlags & X86II::Op0Mask) {
404 default: assert(0 && "Invalid prefix!");
405 case 0: break; // No prefix!
406 case X86II::REP: break; // already handled.
407 case X86II::TB: // Two-byte opcode prefix
408 case X86II::T8: // 0F 38
409 case X86II::TA: // 0F 3A
412 case X86II::TF: // F2 0F 38
416 case X86II::XS: // F3 0F
420 case X86II::XD: // F2 0F
424 case X86II::D8: EmitByte(0xD8, OS); break;
425 case X86II::D9: EmitByte(0xD9, OS); break;
426 case X86II::DA: EmitByte(0xDA, OS); break;
427 case X86II::DB: EmitByte(0xDB, OS); break;
428 case X86II::DC: EmitByte(0xDC, OS); break;
429 case X86II::DD: EmitByte(0xDD, OS); break;
430 case X86II::DE: EmitByte(0xDE, OS); break;
431 case X86II::DF: EmitByte(0xDF, OS); break;
434 // Handle REX prefix.
435 // FIXME: Can this come before F2 etc to simplify emission?
437 if (unsigned REX = DetermineREXPrefix(MI, TSFlags, Desc))
438 EmitByte(0x40 | REX, OS);
441 // 0x0F escape code must be emitted just before the opcode.
445 // FIXME: Pull this up into previous switch if REX can be moved earlier.
446 switch (TSFlags & X86II::Op0Mask) {
447 case X86II::TF: // F2 0F 38
448 case X86II::T8: // 0F 38
451 case X86II::TA: // 0F 3A
456 // If this is a two-address instruction, skip one of the register operands.
457 unsigned NumOps = Desc.getNumOperands();
459 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
461 else if (NumOps > 2 && Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
462 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
465 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(TSFlags);
466 switch (TSFlags & X86II::FormMask) {
467 case X86II::MRMInitReg:
468 assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitter!");
469 default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
470 assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
471 case X86II::RawFrm: {
472 EmitByte(BaseOpcode, OS);
477 assert(0 && "Unimpl RawFrm expr");
481 case X86II::AddRegFrm: {
482 EmitByte(BaseOpcode + GetX86RegNum(MI.getOperand(CurOp++)),OS);
486 const MCOperand &MO1 = MI.getOperand(CurOp++);
488 unsigned Size = X86II::getSizeOfImm(TSFlags);
489 EmitConstant(MO1.getImm(), Size, OS);
493 assert(0 && "Unimpl AddRegFrm expr");
497 case X86II::MRMDestReg:
498 EmitByte(BaseOpcode, OS);
499 EmitRegModRMByte(MI.getOperand(CurOp),
500 GetX86RegNum(MI.getOperand(CurOp+1)), OS);
503 EmitConstant(MI.getOperand(CurOp++).getImm(),
504 X86II::getSizeOfImm(TSFlags), OS);
507 case X86II::MRMDestMem:
508 EmitByte(BaseOpcode, OS);
509 EmitMemModRMByte(MI, CurOp,
510 GetX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)),
512 CurOp += X86AddrNumOperands + 1;
514 EmitConstant(MI.getOperand(CurOp++).getImm(),
515 X86II::getSizeOfImm(TSFlags), OS);
518 case X86II::MRMSrcReg:
519 EmitByte(BaseOpcode, OS);
520 EmitRegModRMByte(MI.getOperand(CurOp+1), GetX86RegNum(MI.getOperand(CurOp)),
524 EmitConstant(MI.getOperand(CurOp++).getImm(),
525 X86II::getSizeOfImm(TSFlags), OS);
528 case X86II::MRMSrcMem: {
529 EmitByte(BaseOpcode, OS);
531 // FIXME: Maybe lea should have its own form? This is a horrible hack.
533 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
534 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
535 AddrOperands = X86AddrNumOperands - 1; // No segment register
537 AddrOperands = X86AddrNumOperands;
539 // FIXME: What is this actually doing?
540 intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
541 X86II::getSizeOfImm(TSFlags) : 0;
543 EmitMemModRMByte(MI, CurOp+1, GetX86RegNum(MI.getOperand(CurOp)),
545 CurOp += AddrOperands + 1;
547 EmitConstant(MI.getOperand(CurOp++).getImm(),
548 X86II::getSizeOfImm(TSFlags), OS);
552 case X86II::MRM0r: case X86II::MRM1r:
553 case X86II::MRM2r: case X86II::MRM3r:
554 case X86II::MRM4r: case X86II::MRM5r:
555 case X86II::MRM6r: case X86II::MRM7r: {
556 EmitByte(BaseOpcode, OS);
558 // Special handling of lfence, mfence, monitor, and mwait.
559 // FIXME: This is terrible, they should get proper encoding bits in TSFlags.
560 if (Opcode == X86::LFENCE || Opcode == X86::MFENCE ||
561 Opcode == X86::MONITOR || Opcode == X86::MWAIT) {
562 EmitByte(ModRMByte(3, (TSFlags & X86II::FormMask)-X86II::MRM0r, 0), OS);
566 case X86::MONITOR: EmitByte(0xC8, OS); break;
567 case X86::MWAIT: EmitByte(0xC9, OS); break;
570 EmitRegModRMByte(MI.getOperand(CurOp++),
571 (TSFlags & X86II::FormMask)-X86II::MRM0r,
578 const MCOperand &MO1 = MI.getOperand(CurOp++);
580 EmitConstant(MO1.getImm(), X86II::getSizeOfImm(TSFlags), OS);
584 assert(0 && "relo unimpl");
586 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
587 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
588 if (Opcode == X86::MOV64ri32)
589 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
590 if (MO1.isGlobal()) {
591 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
592 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
594 } else if (MO1.isSymbol())
595 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
596 else if (MO1.isCPI())
597 emitConstPoolAddress(MO1.getIndex(), rt);
598 else if (MO1.isJTI())
599 emitJumpTableAddress(MO1.getIndex(), rt);
603 case X86II::MRM0m: case X86II::MRM1m:
604 case X86II::MRM2m: case X86II::MRM3m:
605 case X86II::MRM4m: case X86II::MRM5m:
606 case X86II::MRM6m: case X86II::MRM7m: {
608 if (CurOp + X86AddrNumOperands != NumOps) {
609 if (MI.getOperand(CurOp+X86AddrNumOperands).isImm())
610 PCAdj = X86II::getSizeOfImm(TSFlags);
615 EmitByte(BaseOpcode, OS);
616 EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
618 CurOp += X86AddrNumOperands;
623 const MCOperand &MO = MI.getOperand(CurOp++);
625 EmitConstant(MO.getImm(), X86II::getSizeOfImm(TSFlags), OS);
629 assert(0 && "relo not handled");
631 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
632 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
633 if (Opcode == X86::MOV64mi32)
634 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
636 bool Indirect = gvNeedsNonLazyPtr(MO, TM);
637 emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
639 } else if (MO.isSymbol())
640 emitExternalSymbolAddress(MO.getSymbolName(), rt);
642 emitConstPoolAddress(MO.getIndex(), rt);
644 emitJumpTableAddress(MO.getIndex(), rt);
652 if (/*!Desc.isVariadic() &&*/ CurOp != NumOps) {
653 errs() << "Cannot encode all operands of: ";