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"
29 NumEmitted("x86-emitter", "Number of machine instructions emitted");
33 class Emitter : public MachineFunctionPass {
34 const X86InstrInfo *II;
35 MachineCodeEmitter &MCE;
36 std::map<const MachineBasicBlock*, unsigned> BasicBlockAddrs;
37 std::vector<std::pair<const MachineBasicBlock *, unsigned> > BBRefs;
39 explicit Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
40 Emitter(MachineCodeEmitter &mce, const X86InstrInfo& ii)
41 : II(&ii), MCE(mce) {}
43 bool runOnMachineFunction(MachineFunction &MF);
45 virtual const char *getPassName() const {
46 return "X86 Machine Code Emitter";
49 void emitInstruction(const MachineInstr &MI);
52 void emitBasicBlock(const MachineBasicBlock &MBB);
54 void emitPCRelativeBlockAddress(const MachineBasicBlock *BB);
55 void emitPCRelativeValue(unsigned Address);
56 void emitGlobalAddressForCall(GlobalValue *GV, bool isTailCall);
57 void emitGlobalAddressForPtr(GlobalValue *GV, int Disp = 0);
58 void emitExternalSymbolAddress(const char *ES, bool isPCRelative,
61 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
62 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
63 void emitConstant(unsigned Val, unsigned Size);
65 void emitMemModRMByte(const MachineInstr &MI,
66 unsigned Op, unsigned RegOpcodeField);
71 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
72 /// to the specified MCE object.
73 FunctionPass *llvm::createX86CodeEmitterPass(MachineCodeEmitter &MCE) {
74 return new Emitter(MCE);
77 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
78 II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
80 MCE.startFunction(MF);
81 MCE.emitConstantPool(MF.getConstantPool());
82 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
84 MCE.finishFunction(MF);
86 // Resolve all forward branches now...
87 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
88 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
89 unsigned Ref = BBRefs[i].second;
90 MCE.emitWordAt(Location-Ref-4, (unsigned*)(intptr_t)Ref);
93 BasicBlockAddrs.clear();
97 void Emitter::emitBasicBlock(const MachineBasicBlock &MBB) {
98 if (uint64_t Addr = MCE.getCurrentPCValue())
99 BasicBlockAddrs[&MBB] = Addr;
101 for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end();
106 /// emitPCRelativeValue - Emit a 32-bit PC relative address.
108 void Emitter::emitPCRelativeValue(unsigned Address) {
109 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
112 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
113 /// the specified basic block, or if the basic block hasn't been emitted yet
114 /// (because this is a forward branch), it keeps track of the information
115 /// necessary to resolve this address later (and emits a dummy value).
117 void Emitter::emitPCRelativeBlockAddress(const MachineBasicBlock *MBB) {
118 // If this is a backwards branch, we already know the address of the target,
119 // so just emit the value.
120 std::map<const MachineBasicBlock*, unsigned>::iterator I =
121 BasicBlockAddrs.find(MBB);
122 if (I != BasicBlockAddrs.end()) {
123 emitPCRelativeValue(I->second);
125 // Otherwise, remember where this reference was and where it is to so we can
126 // deal with it later.
127 BBRefs.push_back(std::make_pair(MBB, MCE.getCurrentPCValue()));
132 /// emitGlobalAddressForCall - Emit the specified address to the code stream
133 /// assuming this is part of a function call, which is PC relative.
135 void Emitter::emitGlobalAddressForCall(GlobalValue *GV, bool isTailCall) {
136 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
137 X86::reloc_pcrel_word, GV, 0,
138 !isTailCall /*Doesn'tNeedStub*/));
142 /// emitGlobalAddress - Emit the specified address to the code stream assuming
143 /// this is part of a "take the address of a global" instruction, which is not
146 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV, int Disp /* = 0 */) {
147 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
148 X86::reloc_absolute_word, GV));
149 MCE.emitWord(Disp); // The relocated value will be added to the displacement
152 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
153 /// be emitted to the current location in the function, and allow it to be PC
155 void Emitter::emitExternalSymbolAddress(const char *ES, bool isPCRelative,
157 MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
158 isPCRelative ? X86::reloc_pcrel_word : X86::reloc_absolute_word, ES));
162 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
166 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
171 // getX86RegNum - This function maps LLVM register identifiers to their X86
172 // specific numbering, which is used in various places encoding instructions.
174 static unsigned getX86RegNum(unsigned RegNo) {
176 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
177 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
178 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
179 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
180 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
181 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
182 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
183 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
185 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
186 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
187 return RegNo-X86::ST0;
189 assert(MRegisterInfo::isVirtualRegister(RegNo) &&
190 "Unknown physical register!");
191 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
196 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
198 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
199 return RM | (RegOpcode << 3) | (Mod << 6);
202 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
203 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
206 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
207 // SIB byte is in the same format as the ModRMByte...
208 MCE.emitByte(ModRMByte(SS, Index, Base));
211 void Emitter::emitConstant(unsigned Val, unsigned Size) {
212 // Output the constant in little endian byte order...
213 for (unsigned i = 0; i != Size; ++i) {
214 MCE.emitByte(Val & 255);
219 static bool isDisp8(int Value) {
220 return Value == (signed char)Value;
223 void Emitter::emitMemModRMByte(const MachineInstr &MI,
224 unsigned Op, unsigned RegOpcodeField) {
225 const MachineOperand &Op3 = MI.getOperand(Op+3);
229 if (Op3.isGlobalAddress()) {
230 GV = Op3.getGlobal();
231 DispVal = Op3.getOffset();
233 DispVal = Op3.getImmedValue();
236 const MachineOperand &Base = MI.getOperand(Op);
237 const MachineOperand &Scale = MI.getOperand(Op+1);
238 const MachineOperand &IndexReg = MI.getOperand(Op+2);
240 unsigned BaseReg = 0;
242 if (Base.isConstantPoolIndex()) {
243 // Emit a direct address reference [disp32] where the displacement of the
244 // constant pool entry is controlled by the MCE.
245 assert(!GV && "Constant Pool reference cannot be relative to global!");
246 DispVal += MCE.getConstantPoolEntryAddress(Base.getConstantPoolIndex());
248 BaseReg = Base.getReg();
251 // Is a SIB byte needed?
252 if (IndexReg.getReg() == 0 && BaseReg != X86::ESP) {
253 if (BaseReg == 0) { // Just a displacement?
254 // Emit special case [disp32] encoding
255 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
257 emitGlobalAddressForPtr(GV, DispVal);
259 emitConstant(DispVal, 4);
261 unsigned BaseRegNo = getX86RegNum(BaseReg);
263 // Emit the most general non-SIB encoding: [REG+disp32]
264 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
265 emitGlobalAddressForPtr(GV, DispVal);
266 } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
267 // Emit simple indirect register encoding... [EAX] f.e.
268 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
269 } else if (isDisp8(DispVal)) {
270 // Emit the disp8 encoding... [REG+disp8]
271 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
272 emitConstant(DispVal, 1);
274 // Emit the most general non-SIB encoding: [REG+disp32]
275 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
276 emitConstant(DispVal, 4);
280 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
281 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
283 bool ForceDisp32 = false;
284 bool ForceDisp8 = false;
286 // If there is no base register, we emit the special case SIB byte with
287 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
288 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
291 // Emit the normal disp32 encoding...
292 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
294 } else if (DispVal == 0 && BaseReg != X86::EBP) {
295 // Emit no displacement ModR/M byte
296 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
297 } else if (isDisp8(DispVal)) {
298 // Emit the disp8 encoding...
299 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
300 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
302 // Emit the normal disp32 encoding...
303 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
306 // Calculate what the SS field value should be...
307 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
308 unsigned SS = SSTable[Scale.getImmedValue()];
311 // Handle the SIB byte for the case where there is no base. The
312 // displacement has already been output.
313 assert(IndexReg.getReg() && "Index register must be specified!");
314 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
316 unsigned BaseRegNo = getX86RegNum(BaseReg);
318 if (IndexReg.getReg())
319 IndexRegNo = getX86RegNum(IndexReg.getReg());
321 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
322 emitSIBByte(SS, IndexRegNo, BaseRegNo);
325 // Do we need to output a displacement?
326 if (DispVal != 0 || ForceDisp32 || ForceDisp8) {
327 if (!ForceDisp32 && isDisp8(DispVal))
328 emitConstant(DispVal, 1);
330 emitGlobalAddressForPtr(GV, DispVal);
332 emitConstant(DispVal, 4);
337 static unsigned sizeOfImm(const TargetInstrDescriptor &Desc) {
338 switch (Desc.TSFlags & X86II::ImmMask) {
339 case X86II::Imm8: return 1;
340 case X86II::Imm16: return 2;
341 case X86II::Imm32: return 4;
342 default: assert(0 && "Immediate size not set!");
347 void Emitter::emitInstruction(const MachineInstr &MI) {
348 NumEmitted++; // Keep track of the # of mi's emitted
350 unsigned Opcode = MI.getOpcode();
351 const TargetInstrDescriptor &Desc = II->get(Opcode);
353 // Emit the repeat opcode prefix as needed.
354 if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
356 // Emit the operand size opcode prefix as needed.
357 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);
359 // Emit the double precision sse fp opcode prefix as needed.
360 if ((Desc.TSFlags & X86II::Op0Mask) == X86II::XD) {
361 MCE.emitByte(0xF2); MCE.emitByte(0x0F);
364 // Emit the double precision sse fp opcode prefix as needed.
365 if ((Desc.TSFlags & X86II::Op0Mask) == X86II::XS) {
366 MCE.emitByte(0xF3); MCE.emitByte(0x0F);
369 switch (Desc.TSFlags & X86II::Op0Mask) {
371 MCE.emitByte(0x0F); // Two-byte opcode prefix
373 case X86II::REP: break; // already handled.
374 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
375 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
377 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
378 >> X86II::Op0Shift));
379 break; // Two-byte opcode prefix
380 default: assert(0 && "Invalid prefix!");
381 case 0: break; // No prefix!
384 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
385 switch (Desc.TSFlags & X86II::FormMask) {
386 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
388 if (Opcode != X86::IMPLICIT_USE &&
389 Opcode != X86::IMPLICIT_DEF &&
390 Opcode != X86::FP_REG_KILL)
391 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
395 MCE.emitByte(BaseOpcode);
396 if (MI.getNumOperands() == 1) {
397 const MachineOperand &MO = MI.getOperand(0);
398 if (MO.isMachineBasicBlock()) {
399 emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
400 } else if (MO.isGlobalAddress()) {
401 assert(MO.isPCRelative() && "Call target is not PC Relative?");
402 bool isTailCall = Opcode == X86::TAILJMPd ||
403 Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
404 emitGlobalAddressForCall(MO.getGlobal(), isTailCall);
405 } else if (MO.isExternalSymbol()) {
406 bool isTailCall = Opcode == X86::TAILJMPd ||
407 Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
408 emitExternalSymbolAddress(MO.getSymbolName(), true, isTailCall);
409 } else if (MO.isImmediate()) {
410 emitConstant(MO.getImmedValue(), sizeOfImm(Desc));
412 assert(0 && "Unknown RawFrm operand!");
417 case X86II::AddRegFrm:
418 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
419 if (MI.getNumOperands() == 2) {
420 const MachineOperand &MO1 = MI.getOperand(1);
421 if (Value *V = MO1.getVRegValueOrNull()) {
422 assert(sizeOfImm(Desc) == 4 &&
423 "Don't know how to emit non-pointer values!");
424 emitGlobalAddressForPtr(cast<GlobalValue>(V));
425 } else if (MO1.isGlobalAddress()) {
426 assert(sizeOfImm(Desc) == 4 &&
427 "Don't know how to emit non-pointer values!");
428 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
429 emitGlobalAddressForPtr(MO1.getGlobal(), MO1.getOffset());
430 } else if (MO1.isExternalSymbol()) {
431 assert(sizeOfImm(Desc) == 4 &&
432 "Don't know how to emit non-pointer values!");
433 emitExternalSymbolAddress(MO1.getSymbolName(), false, false);
435 emitConstant(MO1.getImmedValue(), sizeOfImm(Desc));
440 case X86II::MRMDestReg: {
441 MCE.emitByte(BaseOpcode);
442 emitRegModRMByte(MI.getOperand(0).getReg(),
443 getX86RegNum(MI.getOperand(1).getReg()));
444 if (MI.getNumOperands() == 3)
445 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
448 case X86II::MRMDestMem:
449 MCE.emitByte(BaseOpcode);
450 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
451 if (MI.getNumOperands() == 6)
452 emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
455 case X86II::MRMSrcReg:
456 MCE.emitByte(BaseOpcode);
458 emitRegModRMByte(MI.getOperand(1).getReg(),
459 getX86RegNum(MI.getOperand(0).getReg()));
460 if (MI.getNumOperands() == 3)
461 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
464 case X86II::MRMSrcMem:
465 MCE.emitByte(BaseOpcode);
466 emitMemModRMByte(MI, 1, getX86RegNum(MI.getOperand(0).getReg()));
467 if (MI.getNumOperands() == 2+4)
468 emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
471 case X86II::MRM0r: case X86II::MRM1r:
472 case X86II::MRM2r: case X86II::MRM3r:
473 case X86II::MRM4r: case X86II::MRM5r:
474 case X86II::MRM6r: case X86II::MRM7r:
475 MCE.emitByte(BaseOpcode);
476 emitRegModRMByte(MI.getOperand(0).getReg(),
477 (Desc.TSFlags & X86II::FormMask)-X86II::MRM0r);
479 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
480 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(),
485 case X86II::MRM0m: case X86II::MRM1m:
486 case X86II::MRM2m: case X86II::MRM3m:
487 case X86II::MRM4m: case X86II::MRM5m:
488 case X86II::MRM6m: case X86II::MRM7m:
489 MCE.emitByte(BaseOpcode);
490 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRM0m);
492 if (MI.getNumOperands() == 5) {
493 if (MI.getOperand(4).isImmediate())
494 emitConstant(MI.getOperand(4).getImmedValue(), sizeOfImm(Desc));
495 else if (MI.getOperand(4).isGlobalAddress())
496 emitGlobalAddressForPtr(MI.getOperand(4).getGlobal(),
497 MI.getOperand(4).getOffset());
499 assert(0 && "Unknown operand!");