1 //===-- X86/X86CodeEmitter.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 contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-emitter"
16 #include "X86InstrInfo.h"
17 #include "X86JITInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "X86Relocations.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/CodeGen/JITCodeEmitter.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/Function.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/MC/MCCodeEmitter.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
40 STATISTIC(NumEmitted, "Number of machine instructions emitted");
43 template<class CodeEmitter>
44 class Emitter : public MachineFunctionPass {
45 const X86InstrInfo *II;
49 intptr_t PICBaseOffset;
54 explicit Emitter(X86TargetMachine &tm, CodeEmitter &mce)
55 : MachineFunctionPass(&ID), II(0), TD(0), TM(tm),
56 MCE(mce), PICBaseOffset(0), Is64BitMode(false),
57 IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
58 Emitter(X86TargetMachine &tm, CodeEmitter &mce,
59 const X86InstrInfo &ii, const TargetData &td, bool is64)
60 : MachineFunctionPass(&ID), II(&ii), TD(&td), TM(tm),
61 MCE(mce), PICBaseOffset(0), Is64BitMode(is64),
62 IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
64 bool runOnMachineFunction(MachineFunction &MF);
66 virtual const char *getPassName() const {
67 return "X86 Machine Code Emitter";
70 void emitInstruction(const MachineInstr &MI,
71 const TargetInstrDesc *Desc);
73 void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<MachineModuleInfo>();
76 MachineFunctionPass::getAnalysisUsage(AU);
80 void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
81 void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
82 intptr_t Disp = 0, intptr_t PCAdj = 0,
83 bool Indirect = false);
84 void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
85 void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
87 void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
90 void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
91 intptr_t Adj = 0, bool IsPCRel = true);
93 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
94 void emitRegModRMByte(unsigned RegOpcodeField);
95 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
96 void emitConstant(uint64_t Val, unsigned Size);
98 void emitMemModRMByte(const MachineInstr &MI,
99 unsigned Op, unsigned RegOpcodeField,
102 unsigned getX86RegNum(unsigned RegNo) const;
105 template<class CodeEmitter>
106 char Emitter<CodeEmitter>::ID = 0;
107 } // end anonymous namespace.
109 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
110 /// to the specified templated MachineCodeEmitter object.
111 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
112 JITCodeEmitter &JCE) {
113 return new Emitter<JITCodeEmitter>(TM, JCE);
116 template<class CodeEmitter>
117 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
119 MCE.setModuleInfo(&getAnalysis<MachineModuleInfo>());
121 II = TM.getInstrInfo();
122 TD = TM.getTargetData();
123 Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
124 IsPIC = TM.getRelocationModel() == Reloc::PIC_;
127 DEBUG(dbgs() << "JITTing function '"
128 << MF.getFunction()->getName() << "'\n");
129 MCE.startFunction(MF);
130 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
132 MCE.StartMachineBasicBlock(MBB);
133 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
135 const TargetInstrDesc &Desc = I->getDesc();
136 emitInstruction(*I, &Desc);
137 // MOVPC32r is basically a call plus a pop instruction.
138 if (Desc.getOpcode() == X86::MOVPC32r)
139 emitInstruction(*I, &II->get(X86::POP32r));
140 NumEmitted++; // Keep track of the # of mi's emitted
143 } while (MCE.finishFunction(MF));
148 /// emitPCRelativeBlockAddress - This method keeps track of the information
149 /// necessary to resolve the address of this block later and emits a dummy
152 template<class CodeEmitter>
153 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
154 // Remember where this reference was and where it is to so we can
155 // deal with it later.
156 MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
157 X86::reloc_pcrel_word, MBB));
161 /// emitGlobalAddress - Emit the specified address to the code stream assuming
162 /// this is part of a "take the address of a global" instruction.
164 template<class CodeEmitter>
165 void Emitter<CodeEmitter>::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
166 intptr_t Disp /* = 0 */,
167 intptr_t PCAdj /* = 0 */,
168 bool Indirect /* = false */) {
169 intptr_t RelocCST = Disp;
170 if (Reloc == X86::reloc_picrel_word)
171 RelocCST = PICBaseOffset;
172 else if (Reloc == X86::reloc_pcrel_word)
174 MachineRelocation MR = Indirect
175 ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
177 : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
178 GV, RelocCST, false);
179 MCE.addRelocation(MR);
180 // The relocated value will be added to the displacement
181 if (Reloc == X86::reloc_absolute_dword)
182 MCE.emitDWordLE(Disp);
184 MCE.emitWordLE((int32_t)Disp);
187 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
188 /// be emitted to the current location in the function, and allow it to be PC
190 template<class CodeEmitter>
191 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
193 intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
194 MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
195 Reloc, ES, RelocCST));
196 if (Reloc == X86::reloc_absolute_dword)
202 /// emitConstPoolAddress - Arrange for the address of an constant pool
203 /// to be emitted to the current location in the function, and allow it to be PC
205 template<class CodeEmitter>
206 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
207 intptr_t Disp /* = 0 */,
208 intptr_t PCAdj /* = 0 */) {
209 intptr_t RelocCST = 0;
210 if (Reloc == X86::reloc_picrel_word)
211 RelocCST = PICBaseOffset;
212 else if (Reloc == X86::reloc_pcrel_word)
214 MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
215 Reloc, CPI, RelocCST));
216 // The relocated value will be added to the displacement
217 if (Reloc == X86::reloc_absolute_dword)
218 MCE.emitDWordLE(Disp);
220 MCE.emitWordLE((int32_t)Disp);
223 /// emitJumpTableAddress - Arrange for the address of a jump table to
224 /// be emitted to the current location in the function, and allow it to be PC
226 template<class CodeEmitter>
227 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
228 intptr_t PCAdj /* = 0 */) {
229 intptr_t RelocCST = 0;
230 if (Reloc == X86::reloc_picrel_word)
231 RelocCST = PICBaseOffset;
232 else if (Reloc == X86::reloc_pcrel_word)
234 MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
235 Reloc, JTI, RelocCST));
236 // The relocated value will be added to the displacement
237 if (Reloc == X86::reloc_absolute_dword)
243 template<class CodeEmitter>
244 unsigned Emitter<CodeEmitter>::getX86RegNum(unsigned RegNo) const {
245 return II->getRegisterInfo().getX86RegNum(RegNo);
248 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
250 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
251 return RM | (RegOpcode << 3) | (Mod << 6);
254 template<class CodeEmitter>
255 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
256 unsigned RegOpcodeFld){
257 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
260 template<class CodeEmitter>
261 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
262 MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
265 template<class CodeEmitter>
266 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS,
269 // SIB byte is in the same format as the ModRMByte...
270 MCE.emitByte(ModRMByte(SS, Index, Base));
273 template<class CodeEmitter>
274 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
275 // Output the constant in little endian byte order...
276 for (unsigned i = 0; i != Size; ++i) {
277 MCE.emitByte(Val & 255);
282 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
283 /// sign-extended field.
284 static bool isDisp8(int Value) {
285 return Value == (signed char)Value;
288 static bool gvNeedsNonLazyPtr(const MachineOperand &GVOp,
289 const TargetMachine &TM) {
290 // For Darwin-64, simulate the linktime GOT by using the same non-lazy-pointer
291 // mechanism as 32-bit mode.
292 if (TM.getSubtarget<X86Subtarget>().is64Bit() &&
293 !TM.getSubtarget<X86Subtarget>().isTargetDarwin())
296 // Return true if this is a reference to a stub containing the address of the
297 // global, not the global itself.
298 return isGlobalStubReference(GVOp.getTargetFlags());
301 template<class CodeEmitter>
302 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
304 intptr_t Adj /* = 0 */,
305 bool IsPCRel /* = true */) {
306 // If this is a simple integer displacement that doesn't require a relocation,
309 emitConstant(DispVal, 4);
313 // Otherwise, this is something that requires a relocation. Emit it as such
315 unsigned RelocType = Is64BitMode ?
316 (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
317 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
318 if (RelocOp->isGlobal()) {
319 // In 64-bit static small code model, we could potentially emit absolute.
320 // But it's probably not beneficial. If the MCE supports using RIP directly
321 // do it, otherwise fallback to absolute (this is determined by IsPCRel).
322 // 89 05 00 00 00 00 mov %eax,0(%rip) # PC-relative
323 // 89 04 25 00 00 00 00 mov %eax,0x0 # Absolute
324 bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
325 emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
327 } else if (RelocOp->isSymbol()) {
328 emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
329 } else if (RelocOp->isCPI()) {
330 emitConstPoolAddress(RelocOp->getIndex(), RelocType,
331 RelocOp->getOffset(), Adj);
333 assert(RelocOp->isJTI() && "Unexpected machine operand!");
334 emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
338 template<class CodeEmitter>
339 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
340 unsigned Op,unsigned RegOpcodeField,
342 const MachineOperand &Op3 = MI.getOperand(Op+3);
344 const MachineOperand *DispForReloc = 0;
346 // Figure out what sort of displacement we have to handle here.
347 if (Op3.isGlobal()) {
349 } else if (Op3.isSymbol()) {
351 } else if (Op3.isCPI()) {
352 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
355 DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
356 DispVal += Op3.getOffset();
358 } else if (Op3.isJTI()) {
359 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
362 DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
365 DispVal = Op3.getImm();
368 const MachineOperand &Base = MI.getOperand(Op);
369 const MachineOperand &Scale = MI.getOperand(Op+1);
370 const MachineOperand &IndexReg = MI.getOperand(Op+2);
372 unsigned BaseReg = Base.getReg();
374 // Indicate that the displacement will use an pcrel or absolute reference
375 // by default. MCEs able to resolve addresses on-the-fly use pcrel by default
376 // while others, unless explicit asked to use RIP, use absolute references.
377 bool IsPCRel = MCE.earlyResolveAddresses() ? true : false;
379 // Is a SIB byte needed?
380 // If no BaseReg, issue a RIP relative instruction only if the MCE can
381 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
382 // 2-7) and absolute references.
383 if ((!Is64BitMode || DispForReloc || BaseReg != 0) &&
384 IndexReg.getReg() == 0 &&
385 ((BaseReg == 0 && MCE.earlyResolveAddresses()) || BaseReg == X86::RIP ||
386 (BaseReg != 0 && getX86RegNum(BaseReg) != N86::ESP))) {
387 if (BaseReg == 0 || BaseReg == X86::RIP) { // Just a displacement?
388 // Emit special case [disp32] encoding
389 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
390 emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
392 unsigned BaseRegNo = getX86RegNum(BaseReg);
393 if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
394 // Emit simple indirect register encoding... [EAX] f.e.
395 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
396 } else if (!DispForReloc && isDisp8(DispVal)) {
397 // Emit the disp8 encoding... [REG+disp8]
398 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
399 emitConstant(DispVal, 1);
401 // Emit the most general non-SIB encoding: [REG+disp32]
402 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
403 emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
407 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
408 assert(IndexReg.getReg() != X86::ESP &&
409 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
411 bool ForceDisp32 = false;
412 bool ForceDisp8 = false;
414 // If there is no base register, we emit the special case SIB byte with
415 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
416 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
418 } else if (DispForReloc) {
419 // Emit the normal disp32 encoding.
420 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
422 } else if (DispVal == 0 && getX86RegNum(BaseReg) != N86::EBP) {
423 // Emit no displacement ModR/M byte
424 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
425 } else if (isDisp8(DispVal)) {
426 // Emit the disp8 encoding...
427 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
428 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
430 // Emit the normal disp32 encoding...
431 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
434 // Calculate what the SS field value should be...
435 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
436 unsigned SS = SSTable[Scale.getImm()];
439 // Handle the SIB byte for the case where there is no base, see Intel
440 // Manual 2A, table 2-7. The displacement has already been output.
442 if (IndexReg.getReg())
443 IndexRegNo = getX86RegNum(IndexReg.getReg());
444 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
446 emitSIBByte(SS, IndexRegNo, 5);
448 unsigned BaseRegNo = getX86RegNum(BaseReg);
450 if (IndexReg.getReg())
451 IndexRegNo = getX86RegNum(IndexReg.getReg());
453 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
454 emitSIBByte(SS, IndexRegNo, BaseRegNo);
457 // Do we need to output a displacement?
459 emitConstant(DispVal, 1);
460 } else if (DispVal != 0 || ForceDisp32) {
461 emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
466 template<class CodeEmitter>
467 void Emitter<CodeEmitter>::emitInstruction(const MachineInstr &MI,
468 const TargetInstrDesc *Desc) {
471 MCE.processDebugLoc(MI.getDebugLoc(), true);
473 unsigned Opcode = Desc->Opcode;
475 // Emit the lock opcode prefix as needed.
476 if (Desc->TSFlags & X86II::LOCK)
479 // Emit segment override opcode prefix as needed.
480 switch (Desc->TSFlags & X86II::SegOvrMask) {
487 default: llvm_unreachable("Invalid segment!");
488 case 0: break; // No segment override!
491 // Emit the repeat opcode prefix as needed.
492 if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP)
495 // Emit the operand size opcode prefix as needed.
496 if (Desc->TSFlags & X86II::OpSize)
499 // Emit the address size opcode prefix as needed.
500 if (Desc->TSFlags & X86II::AdSize)
503 bool Need0FPrefix = false;
504 switch (Desc->TSFlags & X86II::Op0Mask) {
505 case X86II::TB: // Two-byte opcode prefix
506 case X86II::T8: // 0F 38
507 case X86II::TA: // 0F 3A
510 case X86II::TF: // F2 0F 38
514 case X86II::REP: break; // already handled.
515 case X86II::XS: // F3 0F
519 case X86II::XD: // F2 0F
523 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
524 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
526 (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
527 >> X86II::Op0Shift));
528 break; // Two-byte opcode prefix
529 default: llvm_unreachable("Invalid prefix!");
530 case 0: break; // No prefix!
533 // Handle REX prefix.
535 if (unsigned REX = X86InstrInfo::determineREX(MI))
536 MCE.emitByte(0x40 | REX);
539 // 0x0F escape code must be emitted just before the opcode.
543 switch (Desc->TSFlags & X86II::Op0Mask) {
544 case X86II::TF: // F2 0F 38
545 case X86II::T8: // 0F 38
548 case X86II::TA: // 0F 3A
553 // If this is a two-address instruction, skip one of the register operands.
554 unsigned NumOps = Desc->getNumOperands();
556 if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
558 else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
559 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
562 unsigned char BaseOpcode = II->getBaseOpcodeFor(Desc);
563 switch (Desc->TSFlags & X86II::FormMask) {
565 llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
567 // Remember the current PC offset, this is the PIC relocation
571 llvm_unreachable("psuedo instructions should be removed before code"
574 case TargetInstrInfo::INLINEASM:
575 // We allow inline assembler nodes with empty bodies - they can
576 // implicitly define registers, which is ok for JIT.
577 if (MI.getOperand(0).getSymbolName()[0])
578 llvm_report_error("JIT does not support inline asm!");
580 case TargetInstrInfo::DBG_LABEL:
581 case TargetInstrInfo::EH_LABEL:
582 case TargetInstrInfo::GC_LABEL:
583 MCE.emitLabel(MI.getOperand(0).getImm());
585 case TargetInstrInfo::IMPLICIT_DEF:
586 case TargetInstrInfo::KILL:
587 case X86::FP_REG_KILL:
589 case X86::MOVPC32r: {
590 // This emits the "call" portion of this pseudo instruction.
591 MCE.emitByte(BaseOpcode);
592 emitConstant(0, X86InstrInfo::sizeOfImm(Desc));
593 // Remember PIC base.
594 PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
595 X86JITInfo *JTI = TM.getJITInfo();
596 JTI->setPICBase(MCE.getCurrentPCValue());
602 case X86II::RawFrm: {
603 MCE.emitByte(BaseOpcode);
608 const MachineOperand &MO = MI.getOperand(CurOp++);
610 DEBUG(dbgs() << "RawFrm CurOp " << CurOp << "\n");
611 DEBUG(dbgs() << "isMBB " << MO.isMBB() << "\n");
612 DEBUG(dbgs() << "isGlobal " << MO.isGlobal() << "\n");
613 DEBUG(dbgs() << "isSymbol " << MO.isSymbol() << "\n");
614 DEBUG(dbgs() << "isImm " << MO.isImm() << "\n");
617 emitPCRelativeBlockAddress(MO.getMBB());
622 emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
628 emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
632 assert(MO.isImm() && "Unknown RawFrm operand!");
633 if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
634 // Fix up immediate operand for pc relative calls.
635 intptr_t Imm = (intptr_t)MO.getImm();
636 Imm = Imm - MCE.getCurrentPCValue() - 4;
637 emitConstant(Imm, X86InstrInfo::sizeOfImm(Desc));
639 emitConstant(MO.getImm(), X86InstrInfo::sizeOfImm(Desc));
643 case X86II::AddRegFrm: {
644 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
649 const MachineOperand &MO1 = MI.getOperand(CurOp++);
650 unsigned Size = X86InstrInfo::sizeOfImm(Desc);
652 emitConstant(MO1.getImm(), Size);
656 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
657 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
658 if (Opcode == X86::MOV64ri64i32)
659 rt = X86::reloc_absolute_word; // FIXME: add X86II flag?
660 // This should not occur on Darwin for relocatable objects.
661 if (Opcode == X86::MOV64ri)
662 rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?
663 if (MO1.isGlobal()) {
664 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
665 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
667 } else if (MO1.isSymbol())
668 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
669 else if (MO1.isCPI())
670 emitConstPoolAddress(MO1.getIndex(), rt);
671 else if (MO1.isJTI())
672 emitJumpTableAddress(MO1.getIndex(), rt);
676 case X86II::MRMDestReg: {
677 MCE.emitByte(BaseOpcode);
678 emitRegModRMByte(MI.getOperand(CurOp).getReg(),
679 getX86RegNum(MI.getOperand(CurOp+1).getReg()));
682 emitConstant(MI.getOperand(CurOp++).getImm(),
683 X86InstrInfo::sizeOfImm(Desc));
686 case X86II::MRMDestMem: {
687 MCE.emitByte(BaseOpcode);
688 emitMemModRMByte(MI, CurOp,
689 getX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)
691 CurOp += X86AddrNumOperands + 1;
693 emitConstant(MI.getOperand(CurOp++).getImm(),
694 X86InstrInfo::sizeOfImm(Desc));
698 case X86II::MRMSrcReg:
699 MCE.emitByte(BaseOpcode);
700 emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
701 getX86RegNum(MI.getOperand(CurOp).getReg()));
704 emitConstant(MI.getOperand(CurOp++).getImm(),
705 X86InstrInfo::sizeOfImm(Desc));
708 case X86II::MRMSrcMem: {
709 // FIXME: Maybe lea should have its own form?
711 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
712 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
713 AddrOperands = X86AddrNumOperands - 1; // No segment register
715 AddrOperands = X86AddrNumOperands;
717 intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
718 X86InstrInfo::sizeOfImm(Desc) : 0;
720 MCE.emitByte(BaseOpcode);
721 emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
723 CurOp += AddrOperands + 1;
725 emitConstant(MI.getOperand(CurOp++).getImm(),
726 X86InstrInfo::sizeOfImm(Desc));
730 case X86II::MRM0r: case X86II::MRM1r:
731 case X86II::MRM2r: case X86II::MRM3r:
732 case X86II::MRM4r: case X86II::MRM5r:
733 case X86II::MRM6r: case X86II::MRM7r: {
734 MCE.emitByte(BaseOpcode);
736 // Special handling of lfence, mfence, monitor, and mwait.
737 if (Desc->getOpcode() == X86::LFENCE ||
738 Desc->getOpcode() == X86::MFENCE ||
739 Desc->getOpcode() == X86::MONITOR ||
740 Desc->getOpcode() == X86::MWAIT) {
741 emitRegModRMByte((Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
743 switch (Desc->getOpcode()) {
753 emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
754 (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
760 const MachineOperand &MO1 = MI.getOperand(CurOp++);
761 unsigned Size = X86InstrInfo::sizeOfImm(Desc);
763 emitConstant(MO1.getImm(), Size);
767 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
768 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
769 if (Opcode == X86::MOV64ri32)
770 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
771 if (MO1.isGlobal()) {
772 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
773 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
775 } else if (MO1.isSymbol())
776 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
777 else if (MO1.isCPI())
778 emitConstPoolAddress(MO1.getIndex(), rt);
779 else if (MO1.isJTI())
780 emitJumpTableAddress(MO1.getIndex(), rt);
784 case X86II::MRM0m: case X86II::MRM1m:
785 case X86II::MRM2m: case X86II::MRM3m:
786 case X86II::MRM4m: case X86II::MRM5m:
787 case X86II::MRM6m: case X86II::MRM7m: {
788 intptr_t PCAdj = (CurOp + X86AddrNumOperands != NumOps) ?
789 (MI.getOperand(CurOp+X86AddrNumOperands).isImm() ?
790 X86InstrInfo::sizeOfImm(Desc) : 4) : 0;
792 MCE.emitByte(BaseOpcode);
793 emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
795 CurOp += X86AddrNumOperands;
800 const MachineOperand &MO = MI.getOperand(CurOp++);
801 unsigned Size = X86InstrInfo::sizeOfImm(Desc);
803 emitConstant(MO.getImm(), Size);
807 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
808 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
809 if (Opcode == X86::MOV64mi32)
810 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
812 bool Indirect = gvNeedsNonLazyPtr(MO, TM);
813 emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
815 } else if (MO.isSymbol())
816 emitExternalSymbolAddress(MO.getSymbolName(), rt);
818 emitConstPoolAddress(MO.getIndex(), rt);
820 emitJumpTableAddress(MO.getIndex(), rt);
824 case X86II::MRMInitReg:
825 MCE.emitByte(BaseOpcode);
826 // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
827 emitRegModRMByte(MI.getOperand(CurOp).getReg(),
828 getX86RegNum(MI.getOperand(CurOp).getReg()));
833 if (!Desc->isVariadic() && CurOp != NumOps) {
835 dbgs() << "Cannot encode all operands of: " << MI << "\n";
840 MCE.processDebugLoc(MI.getDebugLoc(), false);
843 // Adapt the Emitter / CodeEmitter interfaces to MCCodeEmitter.
845 // FIXME: This is a total hack designed to allow work on llvm-mc to proceed
846 // without being blocked on various cleanups needed to support a clean interface
847 // to instruction encoding.
851 #include "llvm/DerivedTypes.h"
854 class MCSingleInstructionCodeEmitter : public MachineCodeEmitter {
858 MCSingleInstructionCodeEmitter() { reset(); }
862 BufferEnd = array_endof(Data);
867 return StringRef(reinterpret_cast<char*>(BufferBegin),
868 CurBufferPtr - BufferBegin);
871 virtual void startFunction(MachineFunction &F) {}
872 virtual bool finishFunction(MachineFunction &F) { return false; }
873 virtual void emitLabel(uint64_t LabelID) {}
874 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {}
875 virtual bool earlyResolveAddresses() const { return false; }
876 virtual void addRelocation(const MachineRelocation &MR) { }
877 virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
880 virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const {
883 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
886 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
889 virtual void setModuleInfo(MachineModuleInfo* Info) {}
892 class X86MCCodeEmitter : public MCCodeEmitter {
893 X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
894 void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
897 X86TargetMachine &TM;
898 llvm::Function *DummyF;
900 mutable llvm::MachineFunction *DummyMF;
901 llvm::MachineBasicBlock *DummyMBB;
903 MCSingleInstructionCodeEmitter *InstrEmitter;
904 Emitter<MachineCodeEmitter> *Emit;
907 X86MCCodeEmitter(X86TargetMachine &_TM) : TM(_TM) {
908 // Verily, thou shouldst avert thine eyes.
909 const llvm::FunctionType *FTy =
910 FunctionType::get(llvm::Type::getVoidTy(getGlobalContext()), false);
911 DummyF = Function::Create(FTy, GlobalValue::InternalLinkage);
912 DummyTD = new TargetData("");
913 DummyMF = new MachineFunction(DummyF, TM, 0);
914 DummyMBB = DummyMF->CreateMachineBasicBlock();
916 InstrEmitter = new MCSingleInstructionCodeEmitter();
917 Emit = new Emitter<MachineCodeEmitter>(TM, *InstrEmitter,
921 ~X86MCCodeEmitter() {
928 bool AddRegToInstr(const MCInst &MI, MachineInstr *Instr,
929 unsigned Start) const {
930 if (Start + 1 > MI.getNumOperands())
933 const MCOperand &Op = MI.getOperand(Start);
934 if (!Op.isReg()) return false;
936 Instr->addOperand(MachineOperand::CreateReg(Op.getReg(), false));
940 bool AddImmToInstr(const MCInst &MI, MachineInstr *Instr,
941 unsigned Start) const {
942 if (Start + 1 > MI.getNumOperands())
945 const MCOperand &Op = MI.getOperand(Start);
947 Instr->addOperand(MachineOperand::CreateImm(Op.getImm()));
953 const MCExpr *Expr = Op.getExpr();
954 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) {
955 Instr->addOperand(MachineOperand::CreateImm(CE->getValue()));
959 // FIXME: Relocation / fixup.
960 Instr->addOperand(MachineOperand::CreateImm(0));
964 bool AddLMemToInstr(const MCInst &MI, MachineInstr *Instr,
965 unsigned Start) const {
966 return (AddRegToInstr(MI, Instr, Start + 0) &&
967 AddImmToInstr(MI, Instr, Start + 1) &&
968 AddRegToInstr(MI, Instr, Start + 2) &&
969 AddImmToInstr(MI, Instr, Start + 3));
972 bool AddMemToInstr(const MCInst &MI, MachineInstr *Instr,
973 unsigned Start) const {
974 return (AddRegToInstr(MI, Instr, Start + 0) &&
975 AddImmToInstr(MI, Instr, Start + 1) &&
976 AddRegToInstr(MI, Instr, Start + 2) &&
977 AddImmToInstr(MI, Instr, Start + 3) &&
978 AddRegToInstr(MI, Instr, Start + 4));
981 void EncodeInstruction(const MCInst &MI, raw_ostream &OS) const {
984 // Convert the MCInst to a MachineInstr so we can (ab)use the regular
986 const X86InstrInfo &II = *TM.getInstrInfo();
987 const TargetInstrDesc &Desc = II.get(MI.getOpcode());
988 MachineInstr *Instr = DummyMF->CreateMachineInstr(Desc, DebugLoc());
989 DummyMBB->push_back(Instr);
991 unsigned Opcode = MI.getOpcode();
992 unsigned NumOps = MI.getNumOperands();
994 bool AddTied = false;
995 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1)
997 else if (NumOps > 2 &&
998 Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
999 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
1003 switch (Desc.TSFlags & X86II::FormMask) {
1004 case X86II::MRMDestReg:
1005 case X86II::MRMSrcReg:
1006 // Matching doesn't fill this in completely, we have to choose operand 0
1007 // for a tied register.
1008 OK &= AddRegToInstr(MI, Instr, CurOp++);
1010 OK &= AddRegToInstr(MI, Instr, CurOp++ - 1);
1011 OK &= AddRegToInstr(MI, Instr, CurOp++);
1013 OK &= AddImmToInstr(MI, Instr, CurOp);
1017 if (CurOp < NumOps) {
1018 // Hack to make branches work.
1019 if (!(Desc.TSFlags & X86II::ImmMask) &&
1020 MI.getOperand(0).isExpr() &&
1021 isa<MCSymbolRefExpr>(MI.getOperand(0).getExpr()))
1022 Instr->addOperand(MachineOperand::CreateMBB(DummyMBB));
1024 OK &= AddImmToInstr(MI, Instr, CurOp);
1028 case X86II::AddRegFrm:
1029 // Matching doesn't fill this in completely, we have to choose operand 0
1030 // for a tied register.
1031 OK &= AddRegToInstr(MI, Instr, CurOp++);
1033 OK &= AddRegToInstr(MI, Instr, CurOp++ - 1);
1035 OK &= AddImmToInstr(MI, Instr, CurOp);
1038 case X86II::MRM0r: case X86II::MRM1r:
1039 case X86II::MRM2r: case X86II::MRM3r:
1040 case X86II::MRM4r: case X86II::MRM5r:
1041 case X86II::MRM6r: case X86II::MRM7r:
1042 // Matching doesn't fill this in completely, we have to choose operand 0
1043 // for a tied register.
1044 OK &= AddRegToInstr(MI, Instr, CurOp++);
1046 OK &= AddRegToInstr(MI, Instr, CurOp++ - 1);
1048 OK &= AddImmToInstr(MI, Instr, CurOp);
1051 case X86II::MRM0m: case X86II::MRM1m:
1052 case X86II::MRM2m: case X86II::MRM3m:
1053 case X86II::MRM4m: case X86II::MRM5m:
1054 case X86II::MRM6m: case X86II::MRM7m:
1055 OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1057 OK &= AddImmToInstr(MI, Instr, CurOp);
1060 case X86II::MRMSrcMem:
1061 // Matching doesn't fill this in completely, we have to choose operand 0
1062 // for a tied register.
1063 OK &= AddRegToInstr(MI, Instr, CurOp++);
1065 OK &= AddRegToInstr(MI, Instr, CurOp++ - 1);
1066 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
1067 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
1068 OK &= AddLMemToInstr(MI, Instr, CurOp);
1070 OK &= AddMemToInstr(MI, Instr, CurOp);
1073 case X86II::MRMDestMem:
1074 OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1075 OK &= AddRegToInstr(MI, Instr, CurOp);
1079 case X86II::MRMInitReg:
1086 dbgs() << "couldn't convert inst '";
1088 dbgs() << "' to machine instr:\n";
1092 InstrEmitter->reset();
1094 Emit->emitInstruction(*Instr, &Desc);
1095 OS << InstrEmitter->str();
1097 Instr->eraseFromParent();
1102 // Ok, now you can look.
1103 MCCodeEmitter *llvm::createX86MCCodeEmitter(const Target &,
1104 TargetMachine &TM) {
1105 return new X86MCCodeEmitter(static_cast<X86TargetMachine&>(TM));