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 #include "X86TargetMachine.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/CodeGen/MachineCodeEmitter.h"
12 #include "llvm/CodeGen/MachineFunctionPass.h"
13 #include "llvm/CodeGen/MachineInstr.h"
14 #include "llvm/Value.h"
15 #include "Support/Statistic.h"
19 NumEmitted("x86-emitter", "Number of machine instructions emitted");
22 MachineCodeEmitter &MCE;
24 // LazyCodeGenMap - Keep track of call sites for functions that are to be
26 std::map<unsigned, Function*> LazyCodeGenMap;
28 // LazyResolverMap - Keep track of the lazy resolver created for a
29 // particular function so that we can reuse them if necessary.
30 std::map<Function*, unsigned> LazyResolverMap;
32 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
33 unsigned getLazyResolver(Function *F);
34 unsigned addFunctionReference(unsigned Address, Function *F);
37 unsigned emitStubForFunction(Function *F);
38 static void CompilationCallback();
39 unsigned resolveFunctionReference(unsigned RetAddr);
42 JITResolver *TheJITResolver;
46 /// addFunctionReference - This method is called when we need to emit the
47 /// address of a function that has not yet been emitted, so we don't know the
48 /// address. Instead, we emit a call to the CompilationCallback method, and
49 /// keep track of where we are.
51 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
52 LazyCodeGenMap[Address] = F;
53 return (intptr_t)&JITResolver::CompilationCallback;
56 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
57 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
58 assert(I != LazyCodeGenMap.end() && "Not in map!");
59 Function *F = I->second;
60 LazyCodeGenMap.erase(I);
61 return MCE.forceCompilationOf(F);
64 unsigned JITResolver::getLazyResolver(Function *F) {
65 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
66 if (I != LazyResolverMap.end() && I->first == F) return I->second;
68 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
70 unsigned Stub = emitStubForFunction(F);
71 LazyResolverMap.insert(I, std::make_pair(F, Stub));
75 void JITResolver::CompilationCallback() {
76 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
77 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
78 assert(StackPtr[1] == RetAddr &&
79 "Could not find return address on the stack!");
80 bool isStub = ((unsigned char*)RetAddr)[0] == 0xCD; // Interrupt marker?
82 // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
83 // pointer elimination has been performed. Having a variable sized alloca
84 // disables frame pointer elimination currently, even if it's dead. This is a
87 // FIXME FIXME FIXME FIXME
89 // The call instruction should have pushed the return value onto the stack...
90 RetAddr -= 4; // Backtrack to the reference itself...
93 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
94 << " ESP=0x" << (unsigned)StackPtr << std::dec
95 << ": Resolving call to function: "
96 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
99 // Sanity check to make sure this really is a call instruction...
100 assert(((unsigned char*)RetAddr)[-1] == 0xE8 && "Not a call instr!");
102 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
104 // Rewrite the call target... so that we don't fault every time we execute
106 *(unsigned*)RetAddr = NewVal-RetAddr-4;
109 // If this is a stub, rewrite the call into an unconditional branch
110 // instruction so that two return addresses are not pushed onto the stack
111 // when the requested function finally gets called. This also makes the
112 // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
113 ((unsigned char*)RetAddr)[-1] = 0xE9;
116 // Change the return address to reexecute the call instruction...
120 /// emitStubForFunction - This method is used by the JIT when it needs to emit
121 /// the address of a function for a function whose code has not yet been
122 /// generated. In order to do this, it generates a stub which jumps to the lazy
123 /// function compiler, which will eventually get fixed to call the function
126 unsigned JITResolver::emitStubForFunction(Function *F) {
127 MCE.startFunctionStub(*F, 6);
128 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
130 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
131 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
133 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
134 return (intptr_t)MCE.finishFunctionStub(*F);
140 class Emitter : public MachineFunctionPass {
141 const X86InstrInfo *II;
142 MachineCodeEmitter &MCE;
143 std::map<BasicBlock*, unsigned> BasicBlockAddrs;
144 std::vector<std::pair<BasicBlock*, unsigned> > BBRefs;
146 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
148 bool runOnMachineFunction(MachineFunction &MF);
150 virtual const char *getPassName() const {
151 return "X86 Machine Code Emitter";
155 void emitBasicBlock(MachineBasicBlock &MBB);
156 void emitInstruction(MachineInstr &MI);
158 void emitPCRelativeBlockAddress(BasicBlock *BB);
159 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
160 void emitGlobalAddressForCall(GlobalValue *GV);
161 void emitGlobalAddressForPtr(GlobalValue *GV);
163 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
164 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
165 void emitConstant(unsigned Val, unsigned Size);
167 void emitMemModRMByte(const MachineInstr &MI,
168 unsigned Op, unsigned RegOpcodeField);
173 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
174 /// machine code emitted. This uses a MAchineCodeEmitter object to handle
175 /// actually outputting the machine code and resolving things like the address
176 /// of functions. This method should returns true if machine code emission is
179 bool X86TargetMachine::addPassesToEmitMachineCode(PassManager &PM,
180 MachineCodeEmitter &MCE) {
181 PM.add(new Emitter(MCE));
185 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
186 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
188 MCE.startFunction(MF);
189 MCE.emitConstantPool(MF.getConstantPool());
190 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
192 MCE.finishFunction(MF);
194 // Resolve all forward branches now...
195 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
196 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
197 unsigned Ref = BBRefs[i].second;
198 *(unsigned*)Ref = Location-Ref-4;
201 BasicBlockAddrs.clear();
205 void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
206 if (uint64_t Addr = MCE.getCurrentPCValue())
207 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
209 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
210 emitInstruction(**I);
214 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
215 /// the specified basic block, or if the basic block hasn't been emitted yet
216 /// (because this is a forward branch), it keeps track of the information
217 /// necessary to resolve this address later (and emits a dummy value).
219 void Emitter::emitPCRelativeBlockAddress(BasicBlock *BB) {
220 // FIXME: Emit backward branches directly
221 BBRefs.push_back(std::make_pair(BB, MCE.getCurrentPCValue()));
222 MCE.emitWord(0); // Emit a dummy value
225 /// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
227 void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
229 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
231 MCE.emitWord(Address);
234 /// emitGlobalAddressForCall - Emit the specified address to the code stream
235 /// assuming this is part of a function call, which is PC relative.
237 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
238 // Get the address from the backend...
239 unsigned Address = MCE.getGlobalValueAddress(GV);
241 // If the machine code emitter doesn't know what the address IS yet, we have
242 // to take special measures.
245 // FIXME: this is JIT specific!
246 if (TheJITResolver == 0)
247 TheJITResolver = new JITResolver(MCE);
248 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
251 emitMaybePCRelativeValue(Address, true);
254 /// emitGlobalAddress - Emit the specified address to the code stream assuming
255 /// this is part of a "take the address of a global" instruction, which is not
258 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
259 // Get the address from the backend...
260 unsigned Address = MCE.getGlobalValueAddress(GV);
262 // If the machine code emitter doesn't know what the address IS yet, we have
263 // to take special measures.
266 // FIXME: this is JIT specific!
267 if (TheJITResolver == 0)
268 TheJITResolver = new JITResolver(MCE);
269 Address = TheJITResolver->getLazyResolver((Function*)GV);
272 emitMaybePCRelativeValue(Address, false);
277 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
281 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
286 // getX86RegNum - This function maps LLVM register identifiers to their X86
287 // specific numbering, which is used in various places encoding instructions.
289 static unsigned getX86RegNum(unsigned RegNo) {
291 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
292 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
293 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
294 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
295 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
296 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
297 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
298 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
300 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
301 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
302 return RegNo-X86::ST0;
304 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
305 "Unknown physical register!");
306 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
311 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
313 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
314 return RM | (RegOpcode << 3) | (Mod << 6);
317 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
318 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
321 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
322 // SIB byte is in the same format as the ModRMByte...
323 MCE.emitByte(ModRMByte(SS, Index, Base));
326 void Emitter::emitConstant(unsigned Val, unsigned Size) {
327 // Output the constant in little endian byte order...
328 for (unsigned i = 0; i != Size; ++i) {
329 MCE.emitByte(Val & 255);
334 static bool isDisp8(int Value) {
335 return Value == (signed char)Value;
338 void Emitter::emitMemModRMByte(const MachineInstr &MI,
339 unsigned Op, unsigned RegOpcodeField) {
340 const MachineOperand &Disp = MI.getOperand(Op+3);
341 if (MI.getOperand(Op).isConstantPoolIndex()) {
342 // Emit a direct address reference [disp32] where the displacement of the
343 // constant pool entry is controlled by the MCE.
344 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
345 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
346 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
347 MCE.emitWord(Address+Disp.getImmedValue());
351 const MachineOperand &BaseReg = MI.getOperand(Op);
352 const MachineOperand &Scale = MI.getOperand(Op+1);
353 const MachineOperand &IndexReg = MI.getOperand(Op+2);
355 // Is a SIB byte needed?
356 if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
357 if (BaseReg.getReg() == 0) { // Just a displacement?
358 // Emit special case [disp32] encoding
359 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
360 emitConstant(Disp.getImmedValue(), 4);
362 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
363 if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
364 // Emit simple indirect register encoding... [EAX] f.e.
365 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
366 } else if (isDisp8(Disp.getImmedValue())) {
367 // Emit the disp8 encoding... [REG+disp8]
368 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
369 emitConstant(Disp.getImmedValue(), 1);
371 // Emit the most general non-SIB encoding: [REG+disp32]
372 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
373 emitConstant(Disp.getImmedValue(), 4);
377 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
378 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
380 bool ForceDisp32 = false;
381 bool ForceDisp8 = false;
382 if (BaseReg.getReg() == 0) {
383 // If there is no base register, we emit the special case SIB byte with
384 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
385 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
387 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
388 // Emit no displacement ModR/M byte
389 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
390 } else if (isDisp8(Disp.getImmedValue())) {
391 // Emit the disp8 encoding...
392 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
393 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
395 // Emit the normal disp32 encoding...
396 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
399 // Calculate what the SS field value should be...
400 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
401 unsigned SS = SSTable[Scale.getImmedValue()];
403 if (BaseReg.getReg() == 0) {
404 // Handle the SIB byte for the case where there is no base. The
405 // displacement has already been output.
406 assert(IndexReg.getReg() && "Index register must be specified!");
407 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
409 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
411 if (IndexReg.getReg())
412 IndexRegNo = getX86RegNum(IndexReg.getReg());
414 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
415 emitSIBByte(SS, IndexRegNo, BaseRegNo);
418 // Do we need to output a displacement?
419 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
420 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
421 emitConstant(Disp.getImmedValue(), 1);
423 emitConstant(Disp.getImmedValue(), 4);
428 static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
429 switch (Desc.TSFlags & X86II::ArgMask) {
430 case X86II::Arg8: return 1;
431 case X86II::Arg16: return 2;
432 case X86II::Arg32: return 4;
433 case X86II::ArgF32: return 4;
434 case X86II::ArgF64: return 8;
435 case X86II::ArgF80: return 10;
436 default: assert(0 && "Memory size not set!");
441 void Emitter::emitInstruction(MachineInstr &MI) {
442 NumEmitted++; // Keep track of the # of mi's emitted
444 unsigned Opcode = MI.getOpcode();
445 const TargetInstrDescriptor &Desc = II->get(Opcode);
447 // Emit instruction prefixes if neccesary
448 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
450 switch (Desc.TSFlags & X86II::Op0Mask) {
452 MCE.emitByte(0x0F); // Two-byte opcode prefix
454 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
455 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
457 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
458 >> X86II::Op0Shift));
459 break; // Two-byte opcode prefix
460 default: assert(0 && "Invalid prefix!");
461 case 0: break; // No prefix!
464 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
465 switch (Desc.TSFlags & X86II::FormMask) {
466 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
468 if (Opcode != X86::IMPLICIT_USE)
469 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
473 MCE.emitByte(BaseOpcode);
474 if (MI.getNumOperands() == 1) {
475 MachineOperand &MO = MI.getOperand(0);
476 if (MO.isPCRelativeDisp()) {
477 // Conditional branch... FIXME: this should use an MBB destination!
478 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
479 } else if (MO.isGlobalAddress()) {
480 assert(MO.isPCRelative() && "Call target is not PC Relative?");
481 emitGlobalAddressForCall(MO.getGlobal());
482 } else if (MO.isExternalSymbol()) {
483 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
484 assert(Address && "Unknown external symbol!");
485 emitMaybePCRelativeValue(Address, MO.isPCRelative());
487 assert(0 && "Unknown RawFrm operand!");
492 case X86II::AddRegFrm:
493 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
494 if (MI.getNumOperands() == 2) {
495 MachineOperand &MO1 = MI.getOperand(1);
496 if (MO1.isImmediate() || MO1.getVRegValueOrNull() ||
497 MO1.isGlobalAddress() || MO1.isExternalSymbol()) {
498 unsigned Size = sizeOfPtr(Desc);
499 if (Value *V = MO1.getVRegValueOrNull()) {
500 assert(Size == 4 && "Don't know how to emit non-pointer values!");
501 emitGlobalAddressForPtr(cast<GlobalValue>(V));
502 } else if (MO1.isGlobalAddress()) {
503 assert(Size == 4 && "Don't know how to emit non-pointer values!");
504 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
505 emitGlobalAddressForPtr(MO1.getGlobal());
506 } else if (MO1.isExternalSymbol()) {
507 assert(Size == 4 && "Don't know how to emit non-pointer values!");
509 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
510 assert(Address && "Unknown external symbol!");
511 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
513 emitConstant(MO1.getImmedValue(), Size);
519 case X86II::MRMDestReg: {
520 MCE.emitByte(BaseOpcode);
521 MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
522 emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
523 if (MI.getNumOperands() == 4)
524 emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
527 case X86II::MRMDestMem:
528 MCE.emitByte(BaseOpcode);
529 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
532 case X86II::MRMSrcReg:
533 MCE.emitByte(BaseOpcode);
534 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
535 getX86RegNum(MI.getOperand(0).getReg()));
538 case X86II::MRMSrcMem:
539 MCE.emitByte(BaseOpcode);
540 emitMemModRMByte(MI, MI.getNumOperands()-4,
541 getX86RegNum(MI.getOperand(0).getReg()));
544 case X86II::MRMS0r: case X86II::MRMS1r:
545 case X86II::MRMS2r: case X86II::MRMS3r:
546 case X86II::MRMS4r: case X86II::MRMS5r:
547 case X86II::MRMS6r: case X86II::MRMS7r:
548 MCE.emitByte(BaseOpcode);
549 emitRegModRMByte(MI.getOperand(0).getReg(),
550 (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r);
552 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
553 unsigned Size = sizeOfPtr(Desc);
554 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
558 case X86II::MRMS0m: case X86II::MRMS1m:
559 case X86II::MRMS2m: case X86II::MRMS3m:
560 case X86II::MRMS4m: case X86II::MRMS5m:
561 case X86II::MRMS6m: case X86II::MRMS7m:
562 MCE.emitByte(BaseOpcode);
563 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0m);
565 if (MI.getNumOperands() == 5) {
566 unsigned Size = sizeOfPtr(Desc);
567 emitConstant(MI.getOperand(4).getImmedValue(), Size);