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 // actual executable machine code.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
16 #include "X86TargetMachine.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/Function.h"
23 #include "Support/Debug.h"
24 #include "Support/Statistic.h"
25 #include "Config/alloca.h"
29 NumEmitted("x86-emitter", "Number of machine instructions emitted");
32 MachineCodeEmitter &MCE;
34 // LazyCodeGenMap - Keep track of call sites for functions that are to be
36 std::map<unsigned, Function*> LazyCodeGenMap;
38 // LazyResolverMap - Keep track of the lazy resolver created for a
39 // particular function so that we can reuse them if necessary.
40 std::map<Function*, unsigned> LazyResolverMap;
42 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
43 unsigned getLazyResolver(Function *F);
44 unsigned addFunctionReference(unsigned Address, Function *F);
47 unsigned emitStubForFunction(Function *F);
48 static void CompilationCallback();
49 unsigned resolveFunctionReference(unsigned RetAddr);
52 JITResolver *TheJITResolver;
56 /// addFunctionReference - This method is called when we need to emit the
57 /// address of a function that has not yet been emitted, so we don't know the
58 /// address. Instead, we emit a call to the CompilationCallback method, and
59 /// keep track of where we are.
61 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
62 LazyCodeGenMap[Address] = F;
63 return (intptr_t)&JITResolver::CompilationCallback;
66 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
67 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
68 assert(I != LazyCodeGenMap.end() && "Not in map!");
69 Function *F = I->second;
70 LazyCodeGenMap.erase(I);
71 return MCE.forceCompilationOf(F);
74 unsigned JITResolver::getLazyResolver(Function *F) {
75 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
76 if (I != LazyResolverMap.end() && I->first == F) return I->second;
78 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
80 unsigned Stub = emitStubForFunction(F);
81 LazyResolverMap.insert(I, std::make_pair(F, Stub));
85 void JITResolver::CompilationCallback() {
86 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
87 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
88 assert(StackPtr[1] == RetAddr &&
89 "Could not find return address on the stack!");
91 // It's a stub if there is an interrupt marker after the call...
92 bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
94 // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
95 // pointer elimination has been performed. Having a variable sized alloca
96 // disables frame pointer elimination currently, even if it's dead. This is a
99 // FIXME FIXME FIXME FIXME
101 // The call instruction should have pushed the return value onto the stack...
102 RetAddr -= 4; // Backtrack to the reference itself...
105 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
106 << " ESP=0x" << (unsigned)StackPtr << std::dec
107 << ": Resolving call to function: "
108 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
111 // Sanity check to make sure this really is a call instruction...
112 assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
114 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
116 // Rewrite the call target... so that we don't fault every time we execute
118 *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
121 // If this is a stub, rewrite the call into an unconditional branch
122 // instruction so that two return addresses are not pushed onto the stack
123 // when the requested function finally gets called. This also makes the
124 // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
125 ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
128 // Change the return address to reexecute the call instruction...
132 /// emitStubForFunction - This method is used by the JIT when it needs to emit
133 /// the address of a function for a function whose code has not yet been
134 /// generated. In order to do this, it generates a stub which jumps to the lazy
135 /// function compiler, which will eventually get fixed to call the function
138 unsigned JITResolver::emitStubForFunction(Function *F) {
139 MCE.startFunctionStub(*F, 6);
140 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
142 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
143 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
145 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
146 return (intptr_t)MCE.finishFunctionStub(*F);
152 class Emitter : public MachineFunctionPass {
153 const X86InstrInfo *II;
154 MachineCodeEmitter &MCE;
155 std::map<const BasicBlock*, unsigned> BasicBlockAddrs;
156 std::vector<std::pair<const BasicBlock*, unsigned> > BBRefs;
158 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
160 bool runOnMachineFunction(MachineFunction &MF);
162 virtual const char *getPassName() const {
163 return "X86 Machine Code Emitter";
167 void emitBasicBlock(MachineBasicBlock &MBB);
168 void emitInstruction(MachineInstr &MI);
170 void emitPCRelativeBlockAddress(BasicBlock *BB);
171 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
172 void emitGlobalAddressForCall(GlobalValue *GV);
173 void emitGlobalAddressForPtr(GlobalValue *GV);
175 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
176 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
177 void emitConstant(unsigned Val, unsigned Size);
179 void emitMemModRMByte(const MachineInstr &MI,
180 unsigned Op, unsigned RegOpcodeField);
185 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
186 /// machine code emitted. This uses a MachineCodeEmitter object to handle
187 /// actually outputting the machine code and resolving things like the address
188 /// of functions. This method should returns true if machine code emission is
191 bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
192 MachineCodeEmitter &MCE) {
193 PM.add(new Emitter(MCE));
197 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
198 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
200 MCE.startFunction(MF);
201 MCE.emitConstantPool(MF.getConstantPool());
202 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
204 MCE.finishFunction(MF);
206 // Resolve all forward branches now...
207 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
208 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
209 unsigned Ref = BBRefs[i].second;
210 *(unsigned*)(intptr_t)Ref = Location-Ref-4;
213 BasicBlockAddrs.clear();
217 void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
218 if (uint64_t Addr = MCE.getCurrentPCValue())
219 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
221 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
222 emitInstruction(**I);
226 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
227 /// the specified basic block, or if the basic block hasn't been emitted yet
228 /// (because this is a forward branch), it keeps track of the information
229 /// necessary to resolve this address later (and emits a dummy value).
231 void Emitter::emitPCRelativeBlockAddress(BasicBlock *BB) {
232 // FIXME: Emit backward branches directly
233 BBRefs.push_back(std::make_pair(BB, MCE.getCurrentPCValue()));
234 MCE.emitWord(0); // Emit a dummy value
237 /// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
239 void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
241 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
243 MCE.emitWord(Address);
246 /// emitGlobalAddressForCall - Emit the specified address to the code stream
247 /// assuming this is part of a function call, which is PC relative.
249 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
250 // Get the address from the backend...
251 unsigned Address = MCE.getGlobalValueAddress(GV);
254 // FIXME: this is JIT specific!
255 if (TheJITResolver == 0)
256 TheJITResolver = new JITResolver(MCE);
257 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
260 emitMaybePCRelativeValue(Address, true);
263 /// emitGlobalAddress - Emit the specified address to the code stream assuming
264 /// this is part of a "take the address of a global" instruction, which is not
267 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
268 // Get the address from the backend...
269 unsigned Address = MCE.getGlobalValueAddress(GV);
271 // If the machine code emitter doesn't know what the address IS yet, we have
272 // to take special measures.
275 // FIXME: this is JIT specific!
276 if (TheJITResolver == 0)
277 TheJITResolver = new JITResolver(MCE);
278 Address = TheJITResolver->getLazyResolver((Function*)GV);
281 emitMaybePCRelativeValue(Address, false);
286 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
290 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
295 // getX86RegNum - This function maps LLVM register identifiers to their X86
296 // specific numbering, which is used in various places encoding instructions.
298 static unsigned getX86RegNum(unsigned RegNo) {
300 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
301 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
302 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
303 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
304 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
305 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
306 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
307 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
309 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
310 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
311 return RegNo-X86::ST0;
313 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
314 "Unknown physical register!");
315 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
320 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
322 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
323 return RM | (RegOpcode << 3) | (Mod << 6);
326 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
327 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
330 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
331 // SIB byte is in the same format as the ModRMByte...
332 MCE.emitByte(ModRMByte(SS, Index, Base));
335 void Emitter::emitConstant(unsigned Val, unsigned Size) {
336 // Output the constant in little endian byte order...
337 for (unsigned i = 0; i != Size; ++i) {
338 MCE.emitByte(Val & 255);
343 static bool isDisp8(int Value) {
344 return Value == (signed char)Value;
347 void Emitter::emitMemModRMByte(const MachineInstr &MI,
348 unsigned Op, unsigned RegOpcodeField) {
349 const MachineOperand &Disp = MI.getOperand(Op+3);
350 if (MI.getOperand(Op).isConstantPoolIndex()) {
351 // Emit a direct address reference [disp32] where the displacement of the
352 // constant pool entry is controlled by the MCE.
353 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
354 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
355 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
356 MCE.emitWord(Address+Disp.getImmedValue());
360 const MachineOperand &BaseReg = MI.getOperand(Op);
361 const MachineOperand &Scale = MI.getOperand(Op+1);
362 const MachineOperand &IndexReg = MI.getOperand(Op+2);
364 // Is a SIB byte needed?
365 if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
366 if (BaseReg.getReg() == 0) { // Just a displacement?
367 // Emit special case [disp32] encoding
368 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
369 emitConstant(Disp.getImmedValue(), 4);
371 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
372 if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
373 // Emit simple indirect register encoding... [EAX] f.e.
374 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
375 } else if (isDisp8(Disp.getImmedValue())) {
376 // Emit the disp8 encoding... [REG+disp8]
377 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
378 emitConstant(Disp.getImmedValue(), 1);
380 // Emit the most general non-SIB encoding: [REG+disp32]
381 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
382 emitConstant(Disp.getImmedValue(), 4);
386 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
387 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
389 bool ForceDisp32 = false;
390 bool ForceDisp8 = false;
391 if (BaseReg.getReg() == 0) {
392 // If there is no base register, we emit the special case SIB byte with
393 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
394 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
396 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
397 // Emit no displacement ModR/M byte
398 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
399 } else if (isDisp8(Disp.getImmedValue())) {
400 // Emit the disp8 encoding...
401 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
402 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
404 // Emit the normal disp32 encoding...
405 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
408 // Calculate what the SS field value should be...
409 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
410 unsigned SS = SSTable[Scale.getImmedValue()];
412 if (BaseReg.getReg() == 0) {
413 // Handle the SIB byte for the case where there is no base. The
414 // displacement has already been output.
415 assert(IndexReg.getReg() && "Index register must be specified!");
416 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
418 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
420 if (IndexReg.getReg())
421 IndexRegNo = getX86RegNum(IndexReg.getReg());
423 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
424 emitSIBByte(SS, IndexRegNo, BaseRegNo);
427 // Do we need to output a displacement?
428 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
429 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
430 emitConstant(Disp.getImmedValue(), 1);
432 emitConstant(Disp.getImmedValue(), 4);
437 static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
438 switch (Desc.TSFlags & X86II::ArgMask) {
439 case X86II::Arg8: return 1;
440 case X86II::Arg16: return 2;
441 case X86II::Arg32: return 4;
442 case X86II::ArgF32: return 4;
443 case X86II::ArgF64: return 8;
444 case X86II::ArgF80: return 10;
445 default: assert(0 && "Memory size not set!");
450 void Emitter::emitInstruction(MachineInstr &MI) {
451 NumEmitted++; // Keep track of the # of mi's emitted
453 unsigned Opcode = MI.getOpcode();
454 const TargetInstrDescriptor &Desc = II->get(Opcode);
456 // Emit instruction prefixes if necessary
457 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
459 switch (Desc.TSFlags & X86II::Op0Mask) {
461 MCE.emitByte(0x0F); // Two-byte opcode prefix
463 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
464 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
466 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
467 >> X86II::Op0Shift));
468 break; // Two-byte opcode prefix
469 default: assert(0 && "Invalid prefix!");
470 case 0: break; // No prefix!
473 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
474 switch (Desc.TSFlags & X86II::FormMask) {
475 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
477 if (Opcode != X86::IMPLICIT_USE && Opcode != X86::IMPLICIT_DEF)
478 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
482 MCE.emitByte(BaseOpcode);
483 if (MI.getNumOperands() == 1) {
484 MachineOperand &MO = MI.getOperand(0);
485 if (MO.isPCRelativeDisp()) {
486 // Conditional branch... FIXME: this should use an MBB destination!
487 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
488 } else if (MO.isGlobalAddress()) {
489 assert(MO.isPCRelative() && "Call target is not PC Relative?");
490 emitGlobalAddressForCall(MO.getGlobal());
491 } else if (MO.isExternalSymbol()) {
492 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
493 assert(Address && "Unknown external symbol!");
494 emitMaybePCRelativeValue(Address, MO.isPCRelative());
496 assert(0 && "Unknown RawFrm operand!");
501 case X86II::AddRegFrm:
502 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
503 if (MI.getNumOperands() == 2) {
504 MachineOperand &MO1 = MI.getOperand(1);
505 if (MO1.isImmediate() || MO1.getVRegValueOrNull() ||
506 MO1.isGlobalAddress() || MO1.isExternalSymbol()) {
507 unsigned Size = sizeOfPtr(Desc);
508 if (Value *V = MO1.getVRegValueOrNull()) {
509 assert(Size == 4 && "Don't know how to emit non-pointer values!");
510 emitGlobalAddressForPtr(cast<GlobalValue>(V));
511 } else if (MO1.isGlobalAddress()) {
512 assert(Size == 4 && "Don't know how to emit non-pointer values!");
513 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
514 emitGlobalAddressForPtr(MO1.getGlobal());
515 } else if (MO1.isExternalSymbol()) {
516 assert(Size == 4 && "Don't know how to emit non-pointer values!");
518 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
519 assert(Address && "Unknown external symbol!");
520 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
522 emitConstant(MO1.getImmedValue(), Size);
528 case X86II::MRMDestReg: {
529 MCE.emitByte(BaseOpcode);
530 MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
531 emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
532 if (MI.getNumOperands() == 4)
533 emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
536 case X86II::MRMDestMem:
537 MCE.emitByte(BaseOpcode);
538 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
541 case X86II::MRMSrcReg:
542 MCE.emitByte(BaseOpcode);
544 if (MI.getNumOperands() == 2) {
545 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
546 getX86RegNum(MI.getOperand(0).getReg()));
547 } else if (MI.getOperand(2).isImmediate()) {
548 emitRegModRMByte(MI.getOperand(1).getReg(),
549 getX86RegNum(MI.getOperand(0).getReg()));
551 emitConstant(MI.getOperand(2).getImmedValue(), sizeOfPtr(Desc));
553 emitRegModRMByte(MI.getOperand(2).getReg(),
554 getX86RegNum(MI.getOperand(0).getReg()));
558 case X86II::MRMSrcMem:
559 MCE.emitByte(BaseOpcode);
560 emitMemModRMByte(MI, MI.getNumOperands()-4,
561 getX86RegNum(MI.getOperand(0).getReg()));
564 case X86II::MRMS0r: case X86II::MRMS1r:
565 case X86II::MRMS2r: case X86II::MRMS3r:
566 case X86II::MRMS4r: case X86II::MRMS5r:
567 case X86II::MRMS6r: case X86II::MRMS7r:
568 MCE.emitByte(BaseOpcode);
569 emitRegModRMByte(MI.getOperand(0).getReg(),
570 (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r);
572 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
573 unsigned Size = sizeOfPtr(Desc);
574 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
578 case X86II::MRMS0m: case X86II::MRMS1m:
579 case X86II::MRMS2m: case X86II::MRMS3m:
580 case X86II::MRMS4m: case X86II::MRMS5m:
581 case X86II::MRMS6m: case X86II::MRMS7m:
582 MCE.emitByte(BaseOpcode);
583 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0m);
585 if (MI.getNumOperands() == 5) {
586 unsigned Size = sizeOfPtr(Desc);
587 emitConstant(MI.getOperand(4).getImmedValue(), Size);