1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
3 // This file contains the pass that transforms the X86 machine instructions into
4 // actual executable machine code.
6 //===----------------------------------------------------------------------===//
8 #define DEBUG_TYPE "jit"
9 #include "X86TargetMachine.h"
11 #include "llvm/PassManager.h"
12 #include "llvm/CodeGen/MachineCodeEmitter.h"
13 #include "llvm/CodeGen/MachineFunctionPass.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Value.h"
16 #include "Support/Debug.h"
17 #include "Support/Statistic.h"
18 #include "Config/alloca.h"
22 NumEmitted("x86-emitter", "Number of machine instructions emitted");
25 MachineCodeEmitter &MCE;
27 // LazyCodeGenMap - Keep track of call sites for functions that are to be
29 std::map<unsigned, Function*> LazyCodeGenMap;
31 // LazyResolverMap - Keep track of the lazy resolver created for a
32 // particular function so that we can reuse them if necessary.
33 std::map<Function*, unsigned> LazyResolverMap;
35 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
36 unsigned getLazyResolver(Function *F);
37 unsigned addFunctionReference(unsigned Address, Function *F);
40 unsigned emitStubForFunction(Function *F);
41 static void CompilationCallback();
42 unsigned resolveFunctionReference(unsigned RetAddr);
45 JITResolver *TheJITResolver;
49 /// addFunctionReference - This method is called when we need to emit the
50 /// address of a function that has not yet been emitted, so we don't know the
51 /// address. Instead, we emit a call to the CompilationCallback method, and
52 /// keep track of where we are.
54 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
55 LazyCodeGenMap[Address] = F;
56 return (intptr_t)&JITResolver::CompilationCallback;
59 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
60 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
61 assert(I != LazyCodeGenMap.end() && "Not in map!");
62 Function *F = I->second;
63 LazyCodeGenMap.erase(I);
64 return MCE.forceCompilationOf(F);
67 unsigned JITResolver::getLazyResolver(Function *F) {
68 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
69 if (I != LazyResolverMap.end() && I->first == F) return I->second;
71 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
73 unsigned Stub = emitStubForFunction(F);
74 LazyResolverMap.insert(I, std::make_pair(F, Stub));
78 void JITResolver::CompilationCallback() {
79 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
80 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
81 assert(StackPtr[1] == RetAddr &&
82 "Could not find return address on the stack!");
84 // It's a stub if there is an interrupt marker after the call...
85 bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
87 // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
88 // pointer elimination has been performed. Having a variable sized alloca
89 // disables frame pointer elimination currently, even if it's dead. This is a
92 // FIXME FIXME FIXME FIXME
94 // The call instruction should have pushed the return value onto the stack...
95 RetAddr -= 4; // Backtrack to the reference itself...
98 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
99 << " ESP=0x" << (unsigned)StackPtr << std::dec
100 << ": Resolving call to function: "
101 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
104 // Sanity check to make sure this really is a call instruction...
105 assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
107 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
109 // Rewrite the call target... so that we don't fault every time we execute
111 *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
114 // If this is a stub, rewrite the call into an unconditional branch
115 // instruction so that two return addresses are not pushed onto the stack
116 // when the requested function finally gets called. This also makes the
117 // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
118 ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
121 // Change the return address to reexecute the call instruction...
125 /// emitStubForFunction - This method is used by the JIT when it needs to emit
126 /// the address of a function for a function whose code has not yet been
127 /// generated. In order to do this, it generates a stub which jumps to the lazy
128 /// function compiler, which will eventually get fixed to call the function
131 unsigned JITResolver::emitStubForFunction(Function *F) {
132 MCE.startFunctionStub(*F, 6);
133 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
135 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
136 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
138 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
139 return (intptr_t)MCE.finishFunctionStub(*F);
145 class Emitter : public MachineFunctionPass {
146 const X86InstrInfo *II;
147 MachineCodeEmitter &MCE;
148 std::map<const BasicBlock*, unsigned> BasicBlockAddrs;
149 std::vector<std::pair<const BasicBlock*, unsigned> > BBRefs;
151 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
153 bool runOnMachineFunction(MachineFunction &MF);
155 virtual const char *getPassName() const {
156 return "X86 Machine Code Emitter";
160 void emitBasicBlock(MachineBasicBlock &MBB);
161 void emitInstruction(MachineInstr &MI);
163 void emitPCRelativeBlockAddress(BasicBlock *BB);
164 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
165 void emitGlobalAddressForCall(GlobalValue *GV);
166 void emitGlobalAddressForPtr(GlobalValue *GV);
168 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
169 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
170 void emitConstant(unsigned Val, unsigned Size);
172 void emitMemModRMByte(const MachineInstr &MI,
173 unsigned Op, unsigned RegOpcodeField);
178 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
179 /// machine code emitted. This uses a MachineCodeEmitter object to handle
180 /// actually outputting the machine code and resolving things like the address
181 /// of functions. This method should returns true if machine code emission is
184 bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
185 MachineCodeEmitter &MCE) {
186 PM.add(new Emitter(MCE));
190 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
191 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
193 MCE.startFunction(MF);
194 MCE.emitConstantPool(MF.getConstantPool());
195 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
197 MCE.finishFunction(MF);
199 // Resolve all forward branches now...
200 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
201 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
202 unsigned Ref = BBRefs[i].second;
203 *(unsigned*)(intptr_t)Ref = Location-Ref-4;
206 BasicBlockAddrs.clear();
210 void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
211 if (uint64_t Addr = MCE.getCurrentPCValue())
212 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
214 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
215 emitInstruction(**I);
219 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
220 /// the specified basic block, or if the basic block hasn't been emitted yet
221 /// (because this is a forward branch), it keeps track of the information
222 /// necessary to resolve this address later (and emits a dummy value).
224 void Emitter::emitPCRelativeBlockAddress(BasicBlock *BB) {
225 // FIXME: Emit backward branches directly
226 BBRefs.push_back(std::make_pair(BB, MCE.getCurrentPCValue()));
227 MCE.emitWord(0); // Emit a dummy value
230 /// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
232 void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
234 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
236 MCE.emitWord(Address);
239 /// emitGlobalAddressForCall - Emit the specified address to the code stream
240 /// assuming this is part of a function call, which is PC relative.
242 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
243 // Get the address from the backend...
244 unsigned Address = MCE.getGlobalValueAddress(GV);
246 // If the machine code emitter doesn't know what the address IS yet, we have
247 // to take special measures.
250 // FIXME: this is JIT specific!
251 if (TheJITResolver == 0)
252 TheJITResolver = new JITResolver(MCE);
253 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
256 emitMaybePCRelativeValue(Address, true);
259 /// emitGlobalAddress - Emit the specified address to the code stream assuming
260 /// this is part of a "take the address of a global" instruction, which is not
263 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
264 // Get the address from the backend...
265 unsigned Address = MCE.getGlobalValueAddress(GV);
267 // If the machine code emitter doesn't know what the address IS yet, we have
268 // to take special measures.
271 // FIXME: this is JIT specific!
272 if (TheJITResolver == 0)
273 TheJITResolver = new JITResolver(MCE);
274 Address = TheJITResolver->getLazyResolver((Function*)GV);
277 emitMaybePCRelativeValue(Address, false);
282 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
286 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
291 // getX86RegNum - This function maps LLVM register identifiers to their X86
292 // specific numbering, which is used in various places encoding instructions.
294 static unsigned getX86RegNum(unsigned RegNo) {
296 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
297 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
298 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
299 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
300 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
301 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
302 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
303 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
305 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
306 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
307 return RegNo-X86::ST0;
309 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
310 "Unknown physical register!");
311 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
316 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
318 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
319 return RM | (RegOpcode << 3) | (Mod << 6);
322 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
323 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
326 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
327 // SIB byte is in the same format as the ModRMByte...
328 MCE.emitByte(ModRMByte(SS, Index, Base));
331 void Emitter::emitConstant(unsigned Val, unsigned Size) {
332 // Output the constant in little endian byte order...
333 for (unsigned i = 0; i != Size; ++i) {
334 MCE.emitByte(Val & 255);
339 static bool isDisp8(int Value) {
340 return Value == (signed char)Value;
343 void Emitter::emitMemModRMByte(const MachineInstr &MI,
344 unsigned Op, unsigned RegOpcodeField) {
345 const MachineOperand &Disp = MI.getOperand(Op+3);
346 if (MI.getOperand(Op).isConstantPoolIndex()) {
347 // Emit a direct address reference [disp32] where the displacement of the
348 // constant pool entry is controlled by the MCE.
349 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
350 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
351 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
352 MCE.emitWord(Address+Disp.getImmedValue());
356 const MachineOperand &BaseReg = MI.getOperand(Op);
357 const MachineOperand &Scale = MI.getOperand(Op+1);
358 const MachineOperand &IndexReg = MI.getOperand(Op+2);
360 // Is a SIB byte needed?
361 if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
362 if (BaseReg.getReg() == 0) { // Just a displacement?
363 // Emit special case [disp32] encoding
364 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
365 emitConstant(Disp.getImmedValue(), 4);
367 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
368 if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
369 // Emit simple indirect register encoding... [EAX] f.e.
370 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
371 } else if (isDisp8(Disp.getImmedValue())) {
372 // Emit the disp8 encoding... [REG+disp8]
373 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
374 emitConstant(Disp.getImmedValue(), 1);
376 // Emit the most general non-SIB encoding: [REG+disp32]
377 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
378 emitConstant(Disp.getImmedValue(), 4);
382 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
383 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
385 bool ForceDisp32 = false;
386 bool ForceDisp8 = false;
387 if (BaseReg.getReg() == 0) {
388 // If there is no base register, we emit the special case SIB byte with
389 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
390 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
392 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
393 // Emit no displacement ModR/M byte
394 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
395 } else if (isDisp8(Disp.getImmedValue())) {
396 // Emit the disp8 encoding...
397 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
398 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
400 // Emit the normal disp32 encoding...
401 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
404 // Calculate what the SS field value should be...
405 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
406 unsigned SS = SSTable[Scale.getImmedValue()];
408 if (BaseReg.getReg() == 0) {
409 // Handle the SIB byte for the case where there is no base. The
410 // displacement has already been output.
411 assert(IndexReg.getReg() && "Index register must be specified!");
412 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
414 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
416 if (IndexReg.getReg())
417 IndexRegNo = getX86RegNum(IndexReg.getReg());
419 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
420 emitSIBByte(SS, IndexRegNo, BaseRegNo);
423 // Do we need to output a displacement?
424 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
425 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
426 emitConstant(Disp.getImmedValue(), 1);
428 emitConstant(Disp.getImmedValue(), 4);
433 static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
434 switch (Desc.TSFlags & X86II::ArgMask) {
435 case X86II::Arg8: return 1;
436 case X86II::Arg16: return 2;
437 case X86II::Arg32: return 4;
438 case X86II::ArgF32: return 4;
439 case X86II::ArgF64: return 8;
440 case X86II::ArgF80: return 10;
441 default: assert(0 && "Memory size not set!");
446 void Emitter::emitInstruction(MachineInstr &MI) {
447 NumEmitted++; // Keep track of the # of mi's emitted
449 unsigned Opcode = MI.getOpcode();
450 const TargetInstrDescriptor &Desc = II->get(Opcode);
452 // Emit instruction prefixes if necessary
453 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
455 switch (Desc.TSFlags & X86II::Op0Mask) {
457 MCE.emitByte(0x0F); // Two-byte opcode prefix
459 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
460 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
462 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
463 >> X86II::Op0Shift));
464 break; // Two-byte opcode prefix
465 default: assert(0 && "Invalid prefix!");
466 case 0: break; // No prefix!
469 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
470 switch (Desc.TSFlags & X86II::FormMask) {
471 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
473 if (Opcode != X86::IMPLICIT_USE && Opcode != X86::IMPLICIT_DEF)
474 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
478 MCE.emitByte(BaseOpcode);
479 if (MI.getNumOperands() == 1) {
480 MachineOperand &MO = MI.getOperand(0);
481 if (MO.isPCRelativeDisp()) {
482 // Conditional branch... FIXME: this should use an MBB destination!
483 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
484 } else if (MO.isGlobalAddress()) {
485 assert(MO.isPCRelative() && "Call target is not PC Relative?");
486 emitGlobalAddressForCall(MO.getGlobal());
487 } else if (MO.isExternalSymbol()) {
488 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
489 assert(Address && "Unknown external symbol!");
490 emitMaybePCRelativeValue(Address, MO.isPCRelative());
492 assert(0 && "Unknown RawFrm operand!");
497 case X86II::AddRegFrm:
498 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
499 if (MI.getNumOperands() == 2) {
500 MachineOperand &MO1 = MI.getOperand(1);
501 if (MO1.isImmediate() || MO1.getVRegValueOrNull() ||
502 MO1.isGlobalAddress() || MO1.isExternalSymbol()) {
503 unsigned Size = sizeOfPtr(Desc);
504 if (Value *V = MO1.getVRegValueOrNull()) {
505 assert(Size == 4 && "Don't know how to emit non-pointer values!");
506 emitGlobalAddressForPtr(cast<GlobalValue>(V));
507 } else if (MO1.isGlobalAddress()) {
508 assert(Size == 4 && "Don't know how to emit non-pointer values!");
509 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
510 emitGlobalAddressForPtr(MO1.getGlobal());
511 } else if (MO1.isExternalSymbol()) {
512 assert(Size == 4 && "Don't know how to emit non-pointer values!");
514 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
515 assert(Address && "Unknown external symbol!");
516 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
518 emitConstant(MO1.getImmedValue(), Size);
524 case X86II::MRMDestReg: {
525 MCE.emitByte(BaseOpcode);
526 MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
527 emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
528 if (MI.getNumOperands() == 4)
529 emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
532 case X86II::MRMDestMem:
533 MCE.emitByte(BaseOpcode);
534 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
537 case X86II::MRMSrcReg:
538 MCE.emitByte(BaseOpcode);
539 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
540 getX86RegNum(MI.getOperand(0).getReg()));
543 case X86II::MRMSrcMem:
544 MCE.emitByte(BaseOpcode);
545 emitMemModRMByte(MI, MI.getNumOperands()-4,
546 getX86RegNum(MI.getOperand(0).getReg()));
549 case X86II::MRMS0r: case X86II::MRMS1r:
550 case X86II::MRMS2r: case X86II::MRMS3r:
551 case X86II::MRMS4r: case X86II::MRMS5r:
552 case X86II::MRMS6r: case X86II::MRMS7r:
553 MCE.emitByte(BaseOpcode);
554 emitRegModRMByte(MI.getOperand(0).getReg(),
555 (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r);
557 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
558 unsigned Size = sizeOfPtr(Desc);
559 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
563 case X86II::MRMS0m: case X86II::MRMS1m:
564 case X86II::MRMS2m: case X86II::MRMS3m:
565 case X86II::MRMS4m: case X86II::MRMS5m:
566 case X86II::MRMS6m: case X86II::MRMS7m:
567 MCE.emitByte(BaseOpcode);
568 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0m);
570 if (MI.getNumOperands() == 5) {
571 unsigned Size = sizeOfPtr(Desc);
572 emitConstant(MI.getOperand(4).getImmedValue(), Size);