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/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/JITCodeEmitter.h"
26 #include "llvm/CodeGen/ObjectCodeEmitter.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/Function.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/MC/MCCodeEmitter.h"
34 #include "llvm/MC/MCExpr.h"
35 #include "llvm/MC/MCInst.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
42 STATISTIC(NumEmitted, "Number of machine instructions emitted");
45 template<class CodeEmitter>
46 class Emitter : public MachineFunctionPass {
47 const X86InstrInfo *II;
51 intptr_t PICBaseOffset;
56 explicit Emitter(X86TargetMachine &tm, CodeEmitter &mce)
57 : MachineFunctionPass(&ID), II(0), TD(0), TM(tm),
58 MCE(mce), PICBaseOffset(0), Is64BitMode(false),
59 IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
60 Emitter(X86TargetMachine &tm, CodeEmitter &mce,
61 const X86InstrInfo &ii, const TargetData &td, bool is64)
62 : MachineFunctionPass(&ID), II(&ii), TD(&td), TM(tm),
63 MCE(mce), PICBaseOffset(0), Is64BitMode(is64),
64 IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
66 bool runOnMachineFunction(MachineFunction &MF);
68 virtual const char *getPassName() const {
69 return "X86 Machine Code Emitter";
72 void emitInstruction(const MachineInstr &MI,
73 const TargetInstrDesc *Desc);
75 void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addRequired<MachineModuleInfo>();
78 MachineFunctionPass::getAnalysisUsage(AU);
82 void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
83 void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
84 intptr_t Disp = 0, intptr_t PCAdj = 0,
85 bool Indirect = false);
86 void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
87 void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
89 void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
92 void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
93 intptr_t Adj = 0, bool IsPCRel = true);
95 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
96 void emitRegModRMByte(unsigned RegOpcodeField);
97 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
98 void emitConstant(uint64_t Val, unsigned Size);
100 void emitMemModRMByte(const MachineInstr &MI,
101 unsigned Op, unsigned RegOpcodeField,
104 unsigned getX86RegNum(unsigned RegNo) const;
107 template<class CodeEmitter>
108 char Emitter<CodeEmitter>::ID = 0;
109 } // end anonymous namespace.
111 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
112 /// to the specified templated MachineCodeEmitter object.
114 FunctionPass *llvm::createX86CodeEmitterPass(X86TargetMachine &TM,
115 MachineCodeEmitter &MCE) {
116 return new Emitter<MachineCodeEmitter>(TM, MCE);
118 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
119 JITCodeEmitter &JCE) {
120 return new Emitter<JITCodeEmitter>(TM, JCE);
122 FunctionPass *llvm::createX86ObjectCodeEmitterPass(X86TargetMachine &TM,
123 ObjectCodeEmitter &OCE) {
124 return new Emitter<ObjectCodeEmitter>(TM, OCE);
127 template<class CodeEmitter>
128 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
130 MCE.setModuleInfo(&getAnalysis<MachineModuleInfo>());
132 II = TM.getInstrInfo();
133 TD = TM.getTargetData();
134 Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
135 IsPIC = TM.getRelocationModel() == Reloc::PIC_;
138 DEBUG(errs() << "JITTing function '"
139 << MF.getFunction()->getName() << "'\n");
140 MCE.startFunction(MF);
141 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
143 MCE.StartMachineBasicBlock(MBB);
144 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
146 const TargetInstrDesc &Desc = I->getDesc();
147 emitInstruction(*I, &Desc);
148 // MOVPC32r is basically a call plus a pop instruction.
149 if (Desc.getOpcode() == X86::MOVPC32r)
150 emitInstruction(*I, &II->get(X86::POP32r));
151 NumEmitted++; // Keep track of the # of mi's emitted
154 } while (MCE.finishFunction(MF));
159 /// emitPCRelativeBlockAddress - This method keeps track of the information
160 /// necessary to resolve the address of this block later and emits a dummy
163 template<class CodeEmitter>
164 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
165 // Remember where this reference was and where it is to so we can
166 // deal with it later.
167 MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
168 X86::reloc_pcrel_word, MBB));
172 /// emitGlobalAddress - Emit the specified address to the code stream assuming
173 /// this is part of a "take the address of a global" instruction.
175 template<class CodeEmitter>
176 void Emitter<CodeEmitter>::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
177 intptr_t Disp /* = 0 */,
178 intptr_t PCAdj /* = 0 */,
179 bool Indirect /* = false */) {
180 intptr_t RelocCST = Disp;
181 if (Reloc == X86::reloc_picrel_word)
182 RelocCST = PICBaseOffset;
183 else if (Reloc == X86::reloc_pcrel_word)
185 MachineRelocation MR = Indirect
186 ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
188 : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
189 GV, RelocCST, false);
190 MCE.addRelocation(MR);
191 // The relocated value will be added to the displacement
192 if (Reloc == X86::reloc_absolute_dword)
193 MCE.emitDWordLE(Disp);
195 MCE.emitWordLE((int32_t)Disp);
198 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
199 /// be emitted to the current location in the function, and allow it to be PC
201 template<class CodeEmitter>
202 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
204 intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
205 MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
206 Reloc, ES, RelocCST));
207 if (Reloc == X86::reloc_absolute_dword)
213 /// emitConstPoolAddress - Arrange for the address of an constant pool
214 /// to be emitted to the current location in the function, and allow it to be PC
216 template<class CodeEmitter>
217 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
218 intptr_t Disp /* = 0 */,
219 intptr_t PCAdj /* = 0 */) {
220 intptr_t RelocCST = 0;
221 if (Reloc == X86::reloc_picrel_word)
222 RelocCST = PICBaseOffset;
223 else if (Reloc == X86::reloc_pcrel_word)
225 MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
226 Reloc, CPI, RelocCST));
227 // The relocated value will be added to the displacement
228 if (Reloc == X86::reloc_absolute_dword)
229 MCE.emitDWordLE(Disp);
231 MCE.emitWordLE((int32_t)Disp);
234 /// emitJumpTableAddress - Arrange for the address of a jump table to
235 /// be emitted to the current location in the function, and allow it to be PC
237 template<class CodeEmitter>
238 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
239 intptr_t PCAdj /* = 0 */) {
240 intptr_t RelocCST = 0;
241 if (Reloc == X86::reloc_picrel_word)
242 RelocCST = PICBaseOffset;
243 else if (Reloc == X86::reloc_pcrel_word)
245 MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
246 Reloc, JTI, RelocCST));
247 // The relocated value will be added to the displacement
248 if (Reloc == X86::reloc_absolute_dword)
254 template<class CodeEmitter>
255 unsigned Emitter<CodeEmitter>::getX86RegNum(unsigned RegNo) const {
256 return II->getRegisterInfo().getX86RegNum(RegNo);
259 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
261 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
262 return RM | (RegOpcode << 3) | (Mod << 6);
265 template<class CodeEmitter>
266 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
267 unsigned RegOpcodeFld){
268 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
271 template<class CodeEmitter>
272 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
273 MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
276 template<class CodeEmitter>
277 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS,
280 // SIB byte is in the same format as the ModRMByte...
281 MCE.emitByte(ModRMByte(SS, Index, Base));
284 template<class CodeEmitter>
285 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
286 // Output the constant in little endian byte order...
287 for (unsigned i = 0; i != Size; ++i) {
288 MCE.emitByte(Val & 255);
293 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
294 /// sign-extended field.
295 static bool isDisp8(int Value) {
296 return Value == (signed char)Value;
299 static bool gvNeedsNonLazyPtr(const MachineOperand &GVOp,
300 const TargetMachine &TM) {
301 // For Darwin-64, simulate the linktime GOT by using the same non-lazy-pointer
302 // mechanism as 32-bit mode.
303 if (TM.getSubtarget<X86Subtarget>().is64Bit() &&
304 !TM.getSubtarget<X86Subtarget>().isTargetDarwin())
307 // Return true if this is a reference to a stub containing the address of the
308 // global, not the global itself.
309 return isGlobalStubReference(GVOp.getTargetFlags());
312 template<class CodeEmitter>
313 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
315 intptr_t Adj /* = 0 */,
316 bool IsPCRel /* = true */) {
317 // If this is a simple integer displacement that doesn't require a relocation,
320 emitConstant(DispVal, 4);
324 // Otherwise, this is something that requires a relocation. Emit it as such
326 unsigned RelocType = Is64BitMode ?
327 (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
328 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
329 if (RelocOp->isGlobal()) {
330 // In 64-bit static small code model, we could potentially emit absolute.
331 // But it's probably not beneficial. If the MCE supports using RIP directly
332 // do it, otherwise fallback to absolute (this is determined by IsPCRel).
333 // 89 05 00 00 00 00 mov %eax,0(%rip) # PC-relative
334 // 89 04 25 00 00 00 00 mov %eax,0x0 # Absolute
335 bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
336 emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
338 } else if (RelocOp->isSymbol()) {
339 emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
340 } else if (RelocOp->isCPI()) {
341 emitConstPoolAddress(RelocOp->getIndex(), RelocType,
342 RelocOp->getOffset(), Adj);
344 assert(RelocOp->isJTI() && "Unexpected machine operand!");
345 emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
349 template<class CodeEmitter>
350 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
351 unsigned Op,unsigned RegOpcodeField,
353 const MachineOperand &Op3 = MI.getOperand(Op+3);
355 const MachineOperand *DispForReloc = 0;
357 // Figure out what sort of displacement we have to handle here.
358 if (Op3.isGlobal()) {
360 } else if (Op3.isSymbol()) {
362 } else if (Op3.isCPI()) {
363 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
366 DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
367 DispVal += Op3.getOffset();
369 } else if (Op3.isJTI()) {
370 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
373 DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
376 DispVal = Op3.getImm();
379 const MachineOperand &Base = MI.getOperand(Op);
380 const MachineOperand &Scale = MI.getOperand(Op+1);
381 const MachineOperand &IndexReg = MI.getOperand(Op+2);
383 unsigned BaseReg = Base.getReg();
385 // Indicate that the displacement will use an pcrel or absolute reference
386 // by default. MCEs able to resolve addresses on-the-fly use pcrel by default
387 // while others, unless explicit asked to use RIP, use absolute references.
388 bool IsPCRel = MCE.earlyResolveAddresses() ? true : false;
390 // Is a SIB byte needed?
391 // If no BaseReg, issue a RIP relative instruction only if the MCE can
392 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
393 // 2-7) and absolute references.
394 if ((!Is64BitMode || DispForReloc || BaseReg != 0) &&
395 IndexReg.getReg() == 0 &&
396 ((BaseReg == 0 && MCE.earlyResolveAddresses()) || BaseReg == X86::RIP ||
397 (BaseReg != 0 && getX86RegNum(BaseReg) != N86::ESP))) {
398 if (BaseReg == 0 || BaseReg == X86::RIP) { // Just a displacement?
399 // Emit special case [disp32] encoding
400 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
401 emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
403 unsigned BaseRegNo = getX86RegNum(BaseReg);
404 if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
405 // Emit simple indirect register encoding... [EAX] f.e.
406 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
407 } else if (!DispForReloc && isDisp8(DispVal)) {
408 // Emit the disp8 encoding... [REG+disp8]
409 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
410 emitConstant(DispVal, 1);
412 // Emit the most general non-SIB encoding: [REG+disp32]
413 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
414 emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
418 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
419 assert(IndexReg.getReg() != X86::ESP &&
420 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
422 bool ForceDisp32 = false;
423 bool ForceDisp8 = false;
425 // If there is no base register, we emit the special case SIB byte with
426 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
427 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
429 } else if (DispForReloc) {
430 // Emit the normal disp32 encoding.
431 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
433 } else if (DispVal == 0 && getX86RegNum(BaseReg) != N86::EBP) {
434 // Emit no displacement ModR/M byte
435 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
436 } else if (isDisp8(DispVal)) {
437 // Emit the disp8 encoding...
438 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
439 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
441 // Emit the normal disp32 encoding...
442 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
445 // Calculate what the SS field value should be...
446 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
447 unsigned SS = SSTable[Scale.getImm()];
450 // Handle the SIB byte for the case where there is no base, see Intel
451 // Manual 2A, table 2-7. The displacement has already been output.
453 if (IndexReg.getReg())
454 IndexRegNo = getX86RegNum(IndexReg.getReg());
455 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
457 emitSIBByte(SS, IndexRegNo, 5);
459 unsigned BaseRegNo = getX86RegNum(BaseReg);
461 if (IndexReg.getReg())
462 IndexRegNo = getX86RegNum(IndexReg.getReg());
464 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
465 emitSIBByte(SS, IndexRegNo, BaseRegNo);
468 // Do we need to output a displacement?
470 emitConstant(DispVal, 1);
471 } else if (DispVal != 0 || ForceDisp32) {
472 emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
477 template<class CodeEmitter>
478 void Emitter<CodeEmitter>::emitInstruction(const MachineInstr &MI,
479 const TargetInstrDesc *Desc) {
482 MCE.processDebugLoc(MI.getDebugLoc(), true);
484 unsigned Opcode = Desc->Opcode;
486 // Emit the lock opcode prefix as needed.
487 if (Desc->TSFlags & X86II::LOCK)
490 // Emit segment override opcode prefix as needed.
491 switch (Desc->TSFlags & X86II::SegOvrMask) {
498 default: llvm_unreachable("Invalid segment!");
499 case 0: break; // No segment override!
502 // Emit the repeat opcode prefix as needed.
503 if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP)
506 // Emit the operand size opcode prefix as needed.
507 if (Desc->TSFlags & X86II::OpSize)
510 // Emit the address size opcode prefix as needed.
511 if (Desc->TSFlags & X86II::AdSize)
514 bool Need0FPrefix = false;
515 switch (Desc->TSFlags & X86II::Op0Mask) {
516 case X86II::TB: // Two-byte opcode prefix
517 case X86II::T8: // 0F 38
518 case X86II::TA: // 0F 3A
521 case X86II::TF: // F2 0F 38
525 case X86II::REP: break; // already handled.
526 case X86II::XS: // F3 0F
530 case X86II::XD: // F2 0F
534 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
535 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
537 (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
538 >> X86II::Op0Shift));
539 break; // Two-byte opcode prefix
540 default: llvm_unreachable("Invalid prefix!");
541 case 0: break; // No prefix!
544 // Handle REX prefix.
546 if (unsigned REX = X86InstrInfo::determineREX(MI))
547 MCE.emitByte(0x40 | REX);
550 // 0x0F escape code must be emitted just before the opcode.
554 switch (Desc->TSFlags & X86II::Op0Mask) {
555 case X86II::TF: // F2 0F 38
556 case X86II::T8: // 0F 38
559 case X86II::TA: // 0F 3A
564 // If this is a two-address instruction, skip one of the register operands.
565 unsigned NumOps = Desc->getNumOperands();
567 if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
569 else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
570 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
573 unsigned char BaseOpcode = II->getBaseOpcodeFor(Desc);
574 switch (Desc->TSFlags & X86II::FormMask) {
576 llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
578 // Remember the current PC offset, this is the PIC relocation
582 llvm_unreachable("psuedo instructions should be removed before code"
585 case TargetInstrInfo::INLINEASM:
586 // We allow inline assembler nodes with empty bodies - they can
587 // implicitly define registers, which is ok for JIT.
588 if (MI.getOperand(0).getSymbolName()[0])
589 llvm_report_error("JIT does not support inline asm!");
591 case TargetInstrInfo::DBG_LABEL:
592 case TargetInstrInfo::EH_LABEL:
593 case TargetInstrInfo::GC_LABEL:
594 MCE.emitLabel(MI.getOperand(0).getImm());
596 case TargetInstrInfo::IMPLICIT_DEF:
597 case TargetInstrInfo::KILL:
598 case X86::FP_REG_KILL:
600 case X86::MOVPC32r: {
601 // This emits the "call" portion of this pseudo instruction.
602 MCE.emitByte(BaseOpcode);
603 emitConstant(0, X86InstrInfo::sizeOfImm(Desc));
604 // Remember PIC base.
605 PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
606 X86JITInfo *JTI = TM.getJITInfo();
607 JTI->setPICBase(MCE.getCurrentPCValue());
613 case X86II::RawFrm: {
614 MCE.emitByte(BaseOpcode);
619 const MachineOperand &MO = MI.getOperand(CurOp++);
621 DEBUG(errs() << "RawFrm CurOp " << CurOp << "\n");
622 DEBUG(errs() << "isMBB " << MO.isMBB() << "\n");
623 DEBUG(errs() << "isGlobal " << MO.isGlobal() << "\n");
624 DEBUG(errs() << "isSymbol " << MO.isSymbol() << "\n");
625 DEBUG(errs() << "isImm " << MO.isImm() << "\n");
628 emitPCRelativeBlockAddress(MO.getMBB());
633 emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
639 emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
643 assert(MO.isImm() && "Unknown RawFrm operand!");
644 if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
645 // Fix up immediate operand for pc relative calls.
646 intptr_t Imm = (intptr_t)MO.getImm();
647 Imm = Imm - MCE.getCurrentPCValue() - 4;
648 emitConstant(Imm, X86InstrInfo::sizeOfImm(Desc));
650 emitConstant(MO.getImm(), X86InstrInfo::sizeOfImm(Desc));
654 case X86II::AddRegFrm: {
655 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
660 const MachineOperand &MO1 = MI.getOperand(CurOp++);
661 unsigned Size = X86InstrInfo::sizeOfImm(Desc);
663 emitConstant(MO1.getImm(), Size);
667 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
668 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
669 if (Opcode == X86::MOV64ri64i32)
670 rt = X86::reloc_absolute_word; // FIXME: add X86II flag?
671 // This should not occur on Darwin for relocatable objects.
672 if (Opcode == X86::MOV64ri)
673 rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?
674 if (MO1.isGlobal()) {
675 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
676 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
678 } else if (MO1.isSymbol())
679 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
680 else if (MO1.isCPI())
681 emitConstPoolAddress(MO1.getIndex(), rt);
682 else if (MO1.isJTI())
683 emitJumpTableAddress(MO1.getIndex(), rt);
687 case X86II::MRMDestReg: {
688 MCE.emitByte(BaseOpcode);
689 emitRegModRMByte(MI.getOperand(CurOp).getReg(),
690 getX86RegNum(MI.getOperand(CurOp+1).getReg()));
693 emitConstant(MI.getOperand(CurOp++).getImm(),
694 X86InstrInfo::sizeOfImm(Desc));
697 case X86II::MRMDestMem: {
698 MCE.emitByte(BaseOpcode);
699 emitMemModRMByte(MI, CurOp,
700 getX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)
702 CurOp += X86AddrNumOperands + 1;
704 emitConstant(MI.getOperand(CurOp++).getImm(),
705 X86InstrInfo::sizeOfImm(Desc));
709 case X86II::MRMSrcReg:
710 MCE.emitByte(BaseOpcode);
711 emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
712 getX86RegNum(MI.getOperand(CurOp).getReg()));
715 emitConstant(MI.getOperand(CurOp++).getImm(),
716 X86InstrInfo::sizeOfImm(Desc));
719 case X86II::MRMSrcMem: {
720 // FIXME: Maybe lea should have its own form?
722 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
723 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
724 AddrOperands = X86AddrNumOperands - 1; // No segment register
726 AddrOperands = X86AddrNumOperands;
728 intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
729 X86InstrInfo::sizeOfImm(Desc) : 0;
731 MCE.emitByte(BaseOpcode);
732 emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
734 CurOp += AddrOperands + 1;
736 emitConstant(MI.getOperand(CurOp++).getImm(),
737 X86InstrInfo::sizeOfImm(Desc));
741 case X86II::MRM0r: case X86II::MRM1r:
742 case X86II::MRM2r: case X86II::MRM3r:
743 case X86II::MRM4r: case X86II::MRM5r:
744 case X86II::MRM6r: case X86II::MRM7r: {
745 MCE.emitByte(BaseOpcode);
747 // Special handling of lfence, mfence, monitor, and mwait.
748 if (Desc->getOpcode() == X86::LFENCE ||
749 Desc->getOpcode() == X86::MFENCE ||
750 Desc->getOpcode() == X86::MONITOR ||
751 Desc->getOpcode() == X86::MWAIT) {
752 emitRegModRMByte((Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
754 switch (Desc->getOpcode()) {
764 emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
765 (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
771 const MachineOperand &MO1 = MI.getOperand(CurOp++);
772 unsigned Size = X86InstrInfo::sizeOfImm(Desc);
774 emitConstant(MO1.getImm(), Size);
778 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
779 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
780 if (Opcode == X86::MOV64ri32)
781 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
782 if (MO1.isGlobal()) {
783 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
784 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
786 } else if (MO1.isSymbol())
787 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
788 else if (MO1.isCPI())
789 emitConstPoolAddress(MO1.getIndex(), rt);
790 else if (MO1.isJTI())
791 emitJumpTableAddress(MO1.getIndex(), rt);
795 case X86II::MRM0m: case X86II::MRM1m:
796 case X86II::MRM2m: case X86II::MRM3m:
797 case X86II::MRM4m: case X86II::MRM5m:
798 case X86II::MRM6m: case X86II::MRM7m: {
799 intptr_t PCAdj = (CurOp + X86AddrNumOperands != NumOps) ?
800 (MI.getOperand(CurOp+X86AddrNumOperands).isImm() ?
801 X86InstrInfo::sizeOfImm(Desc) : 4) : 0;
803 MCE.emitByte(BaseOpcode);
804 emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
806 CurOp += X86AddrNumOperands;
811 const MachineOperand &MO = MI.getOperand(CurOp++);
812 unsigned Size = X86InstrInfo::sizeOfImm(Desc);
814 emitConstant(MO.getImm(), Size);
818 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
819 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
820 if (Opcode == X86::MOV64mi32)
821 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
823 bool Indirect = gvNeedsNonLazyPtr(MO, TM);
824 emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
826 } else if (MO.isSymbol())
827 emitExternalSymbolAddress(MO.getSymbolName(), rt);
829 emitConstPoolAddress(MO.getIndex(), rt);
831 emitJumpTableAddress(MO.getIndex(), rt);
835 case X86II::MRMInitReg:
836 MCE.emitByte(BaseOpcode);
837 // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
838 emitRegModRMByte(MI.getOperand(CurOp).getReg(),
839 getX86RegNum(MI.getOperand(CurOp).getReg()));
844 if (!Desc->isVariadic() && CurOp != NumOps) {
846 errs() << "Cannot encode all operands of: " << MI << "\n";
851 MCE.processDebugLoc(MI.getDebugLoc(), false);
854 // Adapt the Emitter / CodeEmitter interfaces to MCCodeEmitter.
856 // FIXME: This is a total hack designed to allow work on llvm-mc to proceed
857 // without being blocked on various cleanups needed to support a clean interface
858 // to instruction encoding.
862 #include "llvm/DerivedTypes.h"
865 class MCSingleInstructionCodeEmitter : public MachineCodeEmitter {
869 MCSingleInstructionCodeEmitter() { reset(); }
873 BufferEnd = array_endof(Data);
878 return StringRef(reinterpret_cast<char*>(BufferBegin),
879 CurBufferPtr - BufferBegin);
882 virtual void startFunction(MachineFunction &F) {}
883 virtual bool finishFunction(MachineFunction &F) { return false; }
884 virtual void emitLabel(uint64_t LabelID) {}
885 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {}
886 virtual bool earlyResolveAddresses() const { return false; }
887 virtual void addRelocation(const MachineRelocation &MR) { }
888 virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
891 virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const {
894 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
897 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
900 virtual void setModuleInfo(MachineModuleInfo* Info) {}
903 class X86MCCodeEmitter : public MCCodeEmitter {
904 X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
905 void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
908 X86TargetMachine &TM;
909 llvm::Function *DummyF;
911 mutable llvm::MachineFunction *DummyMF;
912 llvm::MachineBasicBlock *DummyMBB;
914 MCSingleInstructionCodeEmitter *InstrEmitter;
915 Emitter<MachineCodeEmitter> *Emit;
918 X86MCCodeEmitter(X86TargetMachine &_TM) : TM(_TM) {
919 // Verily, thou shouldst avert thine eyes.
920 const llvm::FunctionType *FTy =
921 FunctionType::get(llvm::Type::getVoidTy(getGlobalContext()), false);
922 DummyF = Function::Create(FTy, GlobalValue::InternalLinkage);
923 DummyTD = new TargetData("");
924 DummyMF = new MachineFunction(DummyF, TM);
925 DummyMBB = DummyMF->CreateMachineBasicBlock();
927 InstrEmitter = new MCSingleInstructionCodeEmitter();
928 Emit = new Emitter<MachineCodeEmitter>(TM, *InstrEmitter,
932 ~X86MCCodeEmitter() {
939 bool AddRegToInstr(const MCInst &MI, MachineInstr *Instr,
940 unsigned Start) const {
941 if (Start + 1 > MI.getNumOperands())
944 const MCOperand &Op = MI.getOperand(Start);
945 if (!Op.isReg()) return false;
947 Instr->addOperand(MachineOperand::CreateReg(Op.getReg(), false));
951 bool AddImmToInstr(const MCInst &MI, MachineInstr *Instr,
952 unsigned Start) const {
953 if (Start + 1 > MI.getNumOperands())
956 const MCOperand &Op = MI.getOperand(Start);
958 Instr->addOperand(MachineOperand::CreateImm(Op.getImm()));
964 const MCExpr *Expr = Op.getExpr();
965 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) {
966 Instr->addOperand(MachineOperand::CreateImm(CE->getValue()));
970 // FIXME: Relocation / fixup.
971 Instr->addOperand(MachineOperand::CreateImm(0));
975 bool AddLMemToInstr(const MCInst &MI, MachineInstr *Instr,
976 unsigned Start) const {
977 return (AddRegToInstr(MI, Instr, Start + 0) &&
978 AddImmToInstr(MI, Instr, Start + 1) &&
979 AddRegToInstr(MI, Instr, Start + 2) &&
980 AddImmToInstr(MI, Instr, Start + 3));
983 bool AddMemToInstr(const MCInst &MI, MachineInstr *Instr,
984 unsigned Start) const {
985 return (AddRegToInstr(MI, Instr, Start + 0) &&
986 AddImmToInstr(MI, Instr, Start + 1) &&
987 AddRegToInstr(MI, Instr, Start + 2) &&
988 AddImmToInstr(MI, Instr, Start + 3) &&
989 AddRegToInstr(MI, Instr, Start + 4));
992 void EncodeInstruction(const MCInst &MI, raw_ostream &OS) const {
995 // Convert the MCInst to a MachineInstr so we can (ab)use the regular
997 const X86InstrInfo &II = *TM.getInstrInfo();
998 const TargetInstrDesc &Desc = II.get(MI.getOpcode());
999 MachineInstr *Instr = DummyMF->CreateMachineInstr(Desc, DebugLoc());
1000 DummyMBB->push_back(Instr);
1002 unsigned Opcode = MI.getOpcode();
1003 unsigned NumOps = MI.getNumOperands();
1005 if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1) {
1006 Instr->addOperand(MachineOperand::CreateReg(0, false));
1008 } else if (NumOps > 2 &&
1009 Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
1010 // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
1014 switch (Desc.TSFlags & X86II::FormMask) {
1015 case X86II::MRMDestReg:
1016 case X86II::MRMSrcReg:
1017 // Matching doesn't fill this in completely, we have to choose operand 0
1018 // for a tied register.
1019 OK &= AddRegToInstr(MI, Instr, 0); CurOp++;
1020 OK &= AddRegToInstr(MI, Instr, CurOp++);
1022 OK &= AddImmToInstr(MI, Instr, CurOp);
1026 if (CurOp < NumOps) {
1027 // Hack to make branches work.
1028 if (!(Desc.TSFlags & X86II::ImmMask) &&
1029 MI.getOperand(0).isExpr() &&
1030 isa<MCSymbolRefExpr>(MI.getOperand(0).getExpr()))
1031 Instr->addOperand(MachineOperand::CreateMBB(DummyMBB));
1033 OK &= AddImmToInstr(MI, Instr, CurOp);
1037 case X86II::AddRegFrm:
1038 OK &= AddRegToInstr(MI, Instr, CurOp++);
1040 OK &= AddImmToInstr(MI, Instr, CurOp);
1043 case X86II::MRM0r: case X86II::MRM1r:
1044 case X86II::MRM2r: case X86II::MRM3r:
1045 case X86II::MRM4r: case X86II::MRM5r:
1046 case X86II::MRM6r: case X86II::MRM7r:
1047 // Matching doesn't fill this in completely, we have to choose operand 0
1048 // for a tied register.
1049 OK &= AddRegToInstr(MI, Instr, 0); CurOp++;
1051 OK &= AddImmToInstr(MI, Instr, CurOp);
1054 case X86II::MRM0m: case X86II::MRM1m:
1055 case X86II::MRM2m: case X86II::MRM3m:
1056 case X86II::MRM4m: case X86II::MRM5m:
1057 case X86II::MRM6m: case X86II::MRM7m:
1058 OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1060 OK &= AddImmToInstr(MI, Instr, CurOp);
1063 case X86II::MRMSrcMem:
1064 OK &= AddRegToInstr(MI, Instr, CurOp++);
1065 if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
1066 Opcode == X86::LEA16r || Opcode == X86::LEA32r)
1067 OK &= AddLMemToInstr(MI, Instr, CurOp);
1069 OK &= AddMemToInstr(MI, Instr, CurOp);
1072 case X86II::MRMDestMem:
1073 OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1074 OK &= AddRegToInstr(MI, Instr, CurOp);
1078 case X86II::MRMInitReg:
1085 errs() << "couldn't convert inst '";
1087 errs() << "' to machine instr:\n";
1091 InstrEmitter->reset();
1093 Emit->emitInstruction(*Instr, &Desc);
1094 OS << InstrEmitter->str();
1096 Instr->eraseFromParent();
1101 // Ok, now you can look.
1102 MCCodeEmitter *llvm::createX86MCCodeEmitter(const Target &,
1103 TargetMachine &TM) {
1104 return new X86MCCodeEmitter(static_cast<X86TargetMachine&>(TM));