1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "X86TargetMachine.h"
16 #include "X86Relocations.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Function.h"
24 #include "llvm/ADT/Statistic.h"
30 NumEmitted("x86-emitter", "Number of machine instructions emitted");
34 class Emitter : public MachineFunctionPass {
35 const X86InstrInfo *II;
36 MachineCodeEmitter &MCE;
37 std::map<const MachineBasicBlock*, unsigned> BasicBlockAddrs;
38 std::vector<std::pair<const MachineBasicBlock *, unsigned> > BBRefs;
40 explicit Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
41 Emitter(MachineCodeEmitter &mce, const X86InstrInfo& ii)
42 : II(&ii), MCE(mce) {}
44 bool runOnMachineFunction(MachineFunction &MF);
46 virtual const char *getPassName() const {
47 return "X86 Machine Code Emitter";
50 void emitInstruction(const MachineInstr &MI);
53 void emitBasicBlock(const MachineBasicBlock &MBB);
55 void emitPCRelativeBlockAddress(const MachineBasicBlock *BB);
56 void emitPCRelativeValue(unsigned Address);
57 void emitGlobalAddressForCall(GlobalValue *GV, bool isTailCall);
58 void emitGlobalAddressForPtr(GlobalValue *GV, int Disp = 0);
59 void emitExternalSymbolAddress(const char *ES, bool isPCRelative,
62 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
63 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
64 void emitConstant(unsigned Val, unsigned Size);
66 void emitMemModRMByte(const MachineInstr &MI,
67 unsigned Op, unsigned RegOpcodeField);
72 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
73 /// to the specified MCE object.
74 FunctionPass *llvm::createX86CodeEmitterPass(MachineCodeEmitter &MCE) {
75 return new Emitter(MCE);
78 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
79 II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
81 MCE.startFunction(MF);
82 MCE.emitConstantPool(MF.getConstantPool());
83 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
85 MCE.finishFunction(MF);
87 // Resolve all forward branches now...
88 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
89 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
90 unsigned Ref = BBRefs[i].second;
91 MCE.emitWordAt(Location-Ref-4, (unsigned*)(intptr_t)Ref);
94 BasicBlockAddrs.clear();
98 void Emitter::emitBasicBlock(const MachineBasicBlock &MBB) {
99 if (uint64_t Addr = MCE.getCurrentPCValue())
100 BasicBlockAddrs[&MBB] = Addr;
102 for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end();
107 /// emitPCRelativeValue - Emit a 32-bit PC relative address.
109 void Emitter::emitPCRelativeValue(unsigned Address) {
110 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
113 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
114 /// the specified basic block, or if the basic block hasn't been emitted yet
115 /// (because this is a forward branch), it keeps track of the information
116 /// necessary to resolve this address later (and emits a dummy value).
118 void Emitter::emitPCRelativeBlockAddress(const MachineBasicBlock *MBB) {
119 // If this is a backwards branch, we already know the address of the target,
120 // so just emit the value.
121 std::map<const MachineBasicBlock*, unsigned>::iterator I =
122 BasicBlockAddrs.find(MBB);
123 if (I != BasicBlockAddrs.end()) {
124 emitPCRelativeValue(I->second);
126 // Otherwise, remember where this reference was and where it is to so we can
127 // deal with it later.
128 BBRefs.push_back(std::make_pair(MBB, MCE.getCurrentPCValue()));
133 /// emitGlobalAddressForCall - Emit the specified address to the code stream
134 /// assuming this is part of a function call, which is PC relative.
136 void Emitter::emitGlobalAddressForCall(GlobalValue *GV, bool isTailCall) {
137 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
138 X86::reloc_pcrel_word, GV, 0,
139 !isTailCall /*Doesn'tNeedStub*/));
143 /// emitGlobalAddress - Emit the specified address to the code stream assuming
144 /// this is part of a "take the address of a global" instruction, which is not
147 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV, int Disp /* = 0 */) {
148 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
149 X86::reloc_absolute_word, GV));
150 MCE.emitWord(Disp); // The relocated value will be added to the displacement
153 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
154 /// be emitted to the current location in the function, and allow it to be PC
156 void Emitter::emitExternalSymbolAddress(const char *ES, bool isPCRelative,
158 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
159 isPCRelative ? X86::reloc_pcrel_word : X86::reloc_absolute_word, ES));
163 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
167 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
172 // getX86RegNum - This function maps LLVM register identifiers to their X86
173 // specific numbering, which is used in various places encoding instructions.
175 static unsigned getX86RegNum(unsigned RegNo) {
177 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
178 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
179 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
180 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
181 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
182 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
183 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
184 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
186 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
187 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
188 return RegNo-X86::ST0;
190 assert(MRegisterInfo::isVirtualRegister(RegNo) &&
191 "Unknown physical register!");
192 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
197 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
199 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
200 return RM | (RegOpcode << 3) | (Mod << 6);
203 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
204 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
207 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
208 // SIB byte is in the same format as the ModRMByte...
209 MCE.emitByte(ModRMByte(SS, Index, Base));
212 void Emitter::emitConstant(unsigned Val, unsigned Size) {
213 // Output the constant in little endian byte order...
214 for (unsigned i = 0; i != Size; ++i) {
215 MCE.emitByte(Val & 255);
220 static bool isDisp8(int Value) {
221 return Value == (signed char)Value;
224 void Emitter::emitMemModRMByte(const MachineInstr &MI,
225 unsigned Op, unsigned RegOpcodeField) {
226 const MachineOperand &Op3 = MI.getOperand(Op+3);
230 if (Op3.isGlobalAddress()) {
231 GV = Op3.getGlobal();
232 DispVal = Op3.getOffset();
234 DispVal = Op3.getImmedValue();
237 const MachineOperand &Base = MI.getOperand(Op);
238 const MachineOperand &Scale = MI.getOperand(Op+1);
239 const MachineOperand &IndexReg = MI.getOperand(Op+2);
241 unsigned BaseReg = 0;
243 if (Base.isConstantPoolIndex()) {
244 // Emit a direct address reference [disp32] where the displacement of the
245 // constant pool entry is controlled by the MCE.
246 assert(!GV && "Constant Pool reference cannot be relative to global!");
247 DispVal += MCE.getConstantPoolEntryAddress(Base.getConstantPoolIndex());
249 BaseReg = Base.getReg();
252 // Is a SIB byte needed?
253 if (IndexReg.getReg() == 0 && BaseReg != X86::ESP) {
254 if (BaseReg == 0) { // Just a displacement?
255 // Emit special case [disp32] encoding
256 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
258 emitGlobalAddressForPtr(GV, DispVal);
260 emitConstant(DispVal, 4);
262 unsigned BaseRegNo = getX86RegNum(BaseReg);
264 // Emit the most general non-SIB encoding: [REG+disp32]
265 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
266 emitGlobalAddressForPtr(GV, DispVal);
267 } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
268 // Emit simple indirect register encoding... [EAX] f.e.
269 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
270 } else if (isDisp8(DispVal)) {
271 // Emit the disp8 encoding... [REG+disp8]
272 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
273 emitConstant(DispVal, 1);
275 // Emit the most general non-SIB encoding: [REG+disp32]
276 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
277 emitConstant(DispVal, 4);
281 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
282 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
284 bool ForceDisp32 = false;
285 bool ForceDisp8 = false;
287 // If there is no base register, we emit the special case SIB byte with
288 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
289 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
292 // Emit the normal disp32 encoding...
293 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
295 } else if (DispVal == 0 && BaseReg != X86::EBP) {
296 // Emit no displacement ModR/M byte
297 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
298 } else if (isDisp8(DispVal)) {
299 // Emit the disp8 encoding...
300 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
301 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
303 // Emit the normal disp32 encoding...
304 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
307 // Calculate what the SS field value should be...
308 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
309 unsigned SS = SSTable[Scale.getImmedValue()];
312 // Handle the SIB byte for the case where there is no base. The
313 // displacement has already been output.
314 assert(IndexReg.getReg() && "Index register must be specified!");
315 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
317 unsigned BaseRegNo = getX86RegNum(BaseReg);
319 if (IndexReg.getReg())
320 IndexRegNo = getX86RegNum(IndexReg.getReg());
322 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
323 emitSIBByte(SS, IndexRegNo, BaseRegNo);
326 // Do we need to output a displacement?
327 if (DispVal != 0 || ForceDisp32 || ForceDisp8) {
328 if (!ForceDisp32 && isDisp8(DispVal))
329 emitConstant(DispVal, 1);
331 emitGlobalAddressForPtr(GV, DispVal);
333 emitConstant(DispVal, 4);
338 static unsigned sizeOfImm(const TargetInstrDescriptor &Desc) {
339 switch (Desc.TSFlags & X86II::ImmMask) {
340 case X86II::Imm8: return 1;
341 case X86II::Imm16: return 2;
342 case X86II::Imm32: return 4;
343 default: assert(0 && "Immediate size not set!");
348 void Emitter::emitInstruction(const MachineInstr &MI) {
349 NumEmitted++; // Keep track of the # of mi's emitted
351 unsigned Opcode = MI.getOpcode();
352 const TargetInstrDescriptor &Desc = II->get(Opcode);
354 // Emit the repeat opcode prefix as needed.
355 if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
357 // Emit the operand size opcode prefix as needed.
358 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);
360 // Emit the double precision sse fp opcode prefix as needed.
361 if ((Desc.TSFlags & X86II::Op0Mask) == X86II::XD) {
362 MCE.emitByte(0xF2); MCE.emitByte(0x0F);
365 // Emit the double precision sse fp opcode prefix as needed.
366 if ((Desc.TSFlags & X86II::Op0Mask) == X86II::XS) {
367 MCE.emitByte(0xF3); MCE.emitByte(0x0F);
370 switch (Desc.TSFlags & X86II::Op0Mask) {
372 MCE.emitByte(0x0F); // Two-byte opcode prefix
374 case X86II::REP: break; // already handled.
375 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
376 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
378 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
379 >> X86II::Op0Shift));
380 break; // Two-byte opcode prefix
381 default: assert(0 && "Invalid prefix!");
382 case 0: break; // No prefix!
385 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
386 switch (Desc.TSFlags & X86II::FormMask) {
387 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
389 if (Opcode != X86::IMPLICIT_USE &&
390 Opcode != X86::IMPLICIT_DEF &&
391 Opcode != X86::FP_REG_KILL)
392 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
396 MCE.emitByte(BaseOpcode);
397 if (MI.getNumOperands() == 1) {
398 const MachineOperand &MO = MI.getOperand(0);
399 if (MO.isMachineBasicBlock()) {
400 emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
401 } else if (MO.isGlobalAddress()) {
402 assert(MO.isPCRelative() && "Call target is not PC Relative?");
403 bool isTailCall = Opcode == X86::TAILJMPd ||
404 Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
405 emitGlobalAddressForCall(MO.getGlobal(), isTailCall);
406 } else if (MO.isExternalSymbol()) {
407 bool isTailCall = Opcode == X86::TAILJMPd ||
408 Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
409 emitExternalSymbolAddress(MO.getSymbolName(), true, isTailCall);
410 } else if (MO.isImmediate()) {
411 emitConstant(MO.getImmedValue(), sizeOfImm(Desc));
413 assert(0 && "Unknown RawFrm operand!");
418 case X86II::AddRegFrm:
419 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
420 if (MI.getNumOperands() == 2) {
421 const MachineOperand &MO1 = MI.getOperand(1);
422 if (Value *V = MO1.getVRegValueOrNull()) {
423 assert(sizeOfImm(Desc) == 4 &&
424 "Don't know how to emit non-pointer values!");
425 emitGlobalAddressForPtr(cast<GlobalValue>(V));
426 } else if (MO1.isGlobalAddress()) {
427 assert(sizeOfImm(Desc) == 4 &&
428 "Don't know how to emit non-pointer values!");
429 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
430 emitGlobalAddressForPtr(MO1.getGlobal(), MO1.getOffset());
431 } else if (MO1.isExternalSymbol()) {
432 assert(sizeOfImm(Desc) == 4 &&
433 "Don't know how to emit non-pointer values!");
434 emitExternalSymbolAddress(MO1.getSymbolName(), false, false);
436 emitConstant(MO1.getImmedValue(), sizeOfImm(Desc));
441 case X86II::MRMDestReg: {
442 MCE.emitByte(BaseOpcode);
443 emitRegModRMByte(MI.getOperand(0).getReg(),
444 getX86RegNum(MI.getOperand(1).getReg()));
445 if (MI.getNumOperands() == 3)
446 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
449 case X86II::MRMDestMem:
450 MCE.emitByte(BaseOpcode);
451 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
452 if (MI.getNumOperands() == 6)
453 emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
456 case X86II::MRMSrcReg:
457 MCE.emitByte(BaseOpcode);
459 emitRegModRMByte(MI.getOperand(1).getReg(),
460 getX86RegNum(MI.getOperand(0).getReg()));
461 if (MI.getNumOperands() == 3)
462 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
465 case X86II::MRMSrcMem:
466 MCE.emitByte(BaseOpcode);
467 emitMemModRMByte(MI, 1, getX86RegNum(MI.getOperand(0).getReg()));
468 if (MI.getNumOperands() == 2+4)
469 emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
472 case X86II::MRM0r: case X86II::MRM1r:
473 case X86II::MRM2r: case X86II::MRM3r:
474 case X86II::MRM4r: case X86II::MRM5r:
475 case X86II::MRM6r: case X86II::MRM7r:
476 MCE.emitByte(BaseOpcode);
477 emitRegModRMByte(MI.getOperand(0).getReg(),
478 (Desc.TSFlags & X86II::FormMask)-X86II::MRM0r);
480 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
481 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(),
486 case X86II::MRM0m: case X86II::MRM1m:
487 case X86II::MRM2m: case X86II::MRM3m:
488 case X86II::MRM4m: case X86II::MRM5m:
489 case X86II::MRM6m: case X86II::MRM7m:
490 MCE.emitByte(BaseOpcode);
491 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRM0m);
493 if (MI.getNumOperands() == 5) {
494 if (MI.getOperand(4).isImmediate())
495 emitConstant(MI.getOperand(4).getImmedValue(), sizeOfImm(Desc));
496 else if (MI.getOperand(4).isGlobalAddress())
497 emitGlobalAddressForPtr(MI.getOperand(4).getGlobal(),
498 MI.getOperand(4).getOffset());
500 assert(0 && "Unknown operand!");