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"
18 MachineCodeEmitter &MCE;
20 // LazyCodeGenMap - Keep track of call sites for functions that are to be
22 std::map<unsigned, Function*> LazyCodeGenMap;
24 // LazyResolverMap - Keep track of the lazy resolver created for a
25 // particular function so that we can reuse them if necessary.
26 std::map<Function*, unsigned> LazyResolverMap;
28 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
29 unsigned getLazyResolver(Function *F);
30 unsigned addFunctionReference(unsigned Address, Function *F);
33 unsigned emitStubForFunction(Function *F);
34 static void CompilationCallback();
35 unsigned resolveFunctionReference(unsigned RetAddr);
38 JITResolver *TheJITResolver;
42 /// addFunctionReference - This method is called when we need to emit the
43 /// address of a function that has not yet been emitted, so we don't know the
44 /// address. Instead, we emit a call to the CompilationCallback method, and
45 /// keep track of where we are.
47 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
48 LazyCodeGenMap[Address] = F;
49 return (intptr_t)&JITResolver::CompilationCallback;
52 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
53 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
54 assert(I != LazyCodeGenMap.end() && "Not in map!");
55 Function *F = I->second;
56 LazyCodeGenMap.erase(I);
57 return MCE.forceCompilationOf(F);
60 unsigned JITResolver::getLazyResolver(Function *F) {
61 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
62 if (I != LazyResolverMap.end() && I->first == F) return I->second;
64 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
66 unsigned Stub = emitStubForFunction(F);
67 LazyResolverMap.insert(I, std::make_pair(F, Stub));
71 void JITResolver::CompilationCallback() {
72 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
73 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
75 assert(StackPtr[1] == RetAddr &&
76 "Could not find return address on the stack!");
77 bool isStub = ((unsigned char*)RetAddr)[0] == 0xCD; // Interrupt marker?
79 // The call instruction should have pushed the return value onto the stack...
80 RetAddr -= 4; // Backtrack to the reference itself...
83 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
84 << " ESP=0x" << (unsigned)StackPtr << std::dec
85 << ": Resolving call to function: "
86 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
89 // Sanity check to make sure this really is a call instruction...
90 assert(((unsigned char*)RetAddr)[-1] == 0xE8 && "Not a call instr!");
92 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
94 // Rewrite the call target... so that we don't fault every time we execute
96 *(unsigned*)RetAddr = NewVal-RetAddr-4;
99 // If this is a stub, rewrite the call into an unconditional branch
100 // instruction so that two return addresses are not pushed onto the stack
101 // when the requested function finally gets called. This also makes the
102 // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
103 ((unsigned char*)RetAddr)[-1] = 0xE9;
106 // Change the return address to reexecute the call instruction...
110 /// emitStubForFunction - This method is used by the JIT when it needs to emit
111 /// the address of a function for a function whose code has not yet been
112 /// generated. In order to do this, it generates a stub which jumps to the lazy
113 /// function compiler, which will eventually get fixed to call the function
116 unsigned JITResolver::emitStubForFunction(Function *F) {
117 MCE.startFunctionStub(*F, 6);
118 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
120 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
121 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
123 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
124 return (intptr_t)MCE.finishFunctionStub(*F);
130 class Emitter : public MachineFunctionPass {
131 const X86InstrInfo *II;
132 MachineCodeEmitter &MCE;
133 std::map<BasicBlock*, unsigned> BasicBlockAddrs;
134 std::vector<std::pair<BasicBlock*, unsigned> > BBRefs;
136 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
138 bool runOnMachineFunction(MachineFunction &MF);
140 virtual const char *getPassName() const {
141 return "X86 Machine Code Emitter";
145 void emitBasicBlock(MachineBasicBlock &MBB);
146 void emitInstruction(MachineInstr &MI);
148 void emitPCRelativeBlockAddress(BasicBlock *BB);
149 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
150 void emitGlobalAddressForCall(GlobalValue *GV);
151 void emitGlobalAddressForPtr(GlobalValue *GV);
153 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
154 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
155 void emitConstant(unsigned Val, unsigned Size);
157 void emitMemModRMByte(const MachineInstr &MI,
158 unsigned Op, unsigned RegOpcodeField);
163 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
164 /// machine code emitted. This uses a MAchineCodeEmitter object to handle
165 /// actually outputting the machine code and resolving things like the address
166 /// of functions. This method should returns true if machine code emission is
169 bool X86TargetMachine::addPassesToEmitMachineCode(PassManager &PM,
170 MachineCodeEmitter &MCE) {
171 PM.add(new Emitter(MCE));
175 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
176 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
178 MCE.startFunction(MF);
179 MCE.emitConstantPool(MF.getConstantPool());
180 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
182 MCE.finishFunction(MF);
184 // Resolve all forward branches now...
185 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
186 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
187 unsigned Ref = BBRefs[i].second;
188 *(unsigned*)Ref = Location-Ref-4;
191 BasicBlockAddrs.clear();
195 void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
196 if (uint64_t Addr = MCE.getCurrentPCValue())
197 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
199 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
200 emitInstruction(**I);
204 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
205 /// the specified basic block, or if the basic block hasn't been emitted yet
206 /// (because this is a forward branch), it keeps track of the information
207 /// necessary to resolve this address later (and emits a dummy value).
209 void Emitter::emitPCRelativeBlockAddress(BasicBlock *BB) {
210 // FIXME: Emit backward branches directly
211 BBRefs.push_back(std::make_pair(BB, MCE.getCurrentPCValue()));
212 MCE.emitWord(0); // Emit a dummy value
215 /// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
217 void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
219 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
221 MCE.emitWord(Address);
224 /// emitGlobalAddressForCall - Emit the specified address to the code stream
225 /// assuming this is part of a function call, which is PC relative.
227 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
228 // Get the address from the backend...
229 unsigned Address = MCE.getGlobalValueAddress(GV);
231 // If the machine code emitter doesn't know what the address IS yet, we have
232 // to take special measures.
235 // FIXME: this is JIT specific!
236 if (TheJITResolver == 0)
237 TheJITResolver = new JITResolver(MCE);
238 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
241 emitMaybePCRelativeValue(Address, true);
244 /// emitGlobalAddress - Emit the specified address to the code stream assuming
245 /// this is part of a "take the address of a global" instruction, which is not
248 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
249 // Get the address from the backend...
250 unsigned Address = MCE.getGlobalValueAddress(GV);
252 // If the machine code emitter doesn't know what the address IS yet, we have
253 // to take special measures.
256 // FIXME: this is JIT specific!
257 if (TheJITResolver == 0)
258 TheJITResolver = new JITResolver(MCE);
259 Address = TheJITResolver->getLazyResolver((Function*)GV);
262 emitMaybePCRelativeValue(Address, false);
267 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
271 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
276 // getX86RegNum - This function maps LLVM register identifiers to their X86
277 // specific numbering, which is used in various places encoding instructions.
279 static unsigned getX86RegNum(unsigned RegNo) {
281 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
282 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
283 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
284 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
285 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
286 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
287 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
288 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
290 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
291 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
292 return RegNo-X86::ST0;
294 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
295 "Unknown physical register!");
296 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
301 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
303 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
304 return RM | (RegOpcode << 3) | (Mod << 6);
307 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
308 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
311 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
312 // SIB byte is in the same format as the ModRMByte...
313 MCE.emitByte(ModRMByte(SS, Index, Base));
316 void Emitter::emitConstant(unsigned Val, unsigned Size) {
317 // Output the constant in little endian byte order...
318 for (unsigned i = 0; i != Size; ++i) {
319 MCE.emitByte(Val & 255);
324 static bool isDisp8(int Value) {
325 return Value == (signed char)Value;
328 void Emitter::emitMemModRMByte(const MachineInstr &MI,
329 unsigned Op, unsigned RegOpcodeField) {
330 const MachineOperand &Disp = MI.getOperand(Op+3);
331 if (MI.getOperand(Op).isConstantPoolIndex()) {
332 // Emit a direct address reference [disp32] where the displacement of the
333 // constant pool entry is controlled by the MCE.
334 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
335 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
336 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
337 MCE.emitWord(Address+Disp.getImmedValue());
341 const MachineOperand &BaseReg = MI.getOperand(Op);
342 const MachineOperand &Scale = MI.getOperand(Op+1);
343 const MachineOperand &IndexReg = MI.getOperand(Op+2);
345 // Is a SIB byte needed?
346 if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
347 if (BaseReg.getReg() == 0) { // Just a displacement?
348 // Emit special case [disp32] encoding
349 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
350 emitConstant(Disp.getImmedValue(), 4);
352 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
353 if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
354 // Emit simple indirect register encoding... [EAX] f.e.
355 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
356 } else if (isDisp8(Disp.getImmedValue())) {
357 // Emit the disp8 encoding... [REG+disp8]
358 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
359 emitConstant(Disp.getImmedValue(), 1);
361 // Emit the most general non-SIB encoding: [REG+disp32]
362 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
363 emitConstant(Disp.getImmedValue(), 4);
367 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
368 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
370 bool ForceDisp32 = false;
371 bool ForceDisp8 = false;
372 if (BaseReg.getReg() == 0) {
373 // If there is no base register, we emit the special case SIB byte with
374 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
375 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
377 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
378 // Emit no displacement ModR/M byte
379 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
380 } else if (isDisp8(Disp.getImmedValue())) {
381 // Emit the disp8 encoding...
382 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
383 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
385 // Emit the normal disp32 encoding...
386 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
389 // Calculate what the SS field value should be...
390 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
391 unsigned SS = SSTable[Scale.getImmedValue()];
393 if (BaseReg.getReg() == 0) {
394 // Handle the SIB byte for the case where there is no base. The
395 // displacement has already been output.
396 assert(IndexReg.getReg() && "Index register must be specified!");
397 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
399 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
401 if (IndexReg.getReg())
402 IndexRegNo = getX86RegNum(IndexReg.getReg());
404 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
405 emitSIBByte(SS, IndexRegNo, BaseRegNo);
408 // Do we need to output a displacement?
409 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
410 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
411 emitConstant(Disp.getImmedValue(), 1);
413 emitConstant(Disp.getImmedValue(), 4);
418 static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
419 switch (Desc.TSFlags & X86II::ArgMask) {
420 case X86II::Arg8: return 1;
421 case X86II::Arg16: return 2;
422 case X86II::Arg32: return 4;
423 case X86II::ArgF32: return 4;
424 case X86II::ArgF64: return 8;
425 case X86II::ArgF80: return 10;
426 default: assert(0 && "Memory size not set!");
431 void Emitter::emitInstruction(MachineInstr &MI) {
432 unsigned Opcode = MI.getOpcode();
433 const TargetInstrDescriptor &Desc = II->get(Opcode);
435 // Emit instruction prefixes if neccesary
436 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
438 switch (Desc.TSFlags & X86II::Op0Mask) {
440 MCE.emitByte(0x0F); // Two-byte opcode prefix
442 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
443 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
445 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
446 >> X86II::Op0Shift));
447 break; // Two-byte opcode prefix
448 default: assert(0 && "Invalid prefix!");
449 case 0: break; // No prefix!
452 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
453 switch (Desc.TSFlags & X86II::FormMask) {
454 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
456 if (Opcode != X86::IMPLICIT_USE)
457 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
461 MCE.emitByte(BaseOpcode);
462 if (MI.getNumOperands() == 1) {
463 MachineOperand &MO = MI.getOperand(0);
464 if (MO.isPCRelativeDisp()) {
465 // Conditional branch... FIXME: this should use an MBB destination!
466 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
467 } else if (MO.isGlobalAddress()) {
468 assert(MO.isPCRelative() && "Call target is not PC Relative?");
469 emitGlobalAddressForCall(MO.getGlobal());
470 } else if (MO.isExternalSymbol()) {
471 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
472 assert(Address && "Unknown external symbol!");
473 emitMaybePCRelativeValue(Address, MO.isPCRelative());
475 assert(0 && "Unknown RawFrm operand!");
480 case X86II::AddRegFrm:
481 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
482 if (MI.getNumOperands() == 2) {
483 MachineOperand &MO1 = MI.getOperand(1);
484 if (MO1.isImmediate() || MO1.getVRegValueOrNull() ||
485 MO1.isGlobalAddress() || MO1.isExternalSymbol()) {
486 unsigned Size = sizeOfPtr(Desc);
487 if (Value *V = MO1.getVRegValueOrNull()) {
488 assert(Size == 4 && "Don't know how to emit non-pointer values!");
489 emitGlobalAddressForPtr(cast<GlobalValue>(V));
490 } else if (MO1.isGlobalAddress()) {
491 assert(Size == 4 && "Don't know how to emit non-pointer values!");
492 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
493 emitGlobalAddressForPtr(MO1.getGlobal());
494 } else if (MO1.isExternalSymbol()) {
495 assert(Size == 4 && "Don't know how to emit non-pointer values!");
497 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
498 assert(Address && "Unknown external symbol!");
499 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
501 emitConstant(MO1.getImmedValue(), Size);
507 case X86II::MRMDestReg: {
508 MCE.emitByte(BaseOpcode);
509 MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
510 emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
511 if (MI.getNumOperands() == 4)
512 emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
515 case X86II::MRMDestMem:
516 MCE.emitByte(BaseOpcode);
517 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
520 case X86II::MRMSrcReg:
521 MCE.emitByte(BaseOpcode);
522 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
523 getX86RegNum(MI.getOperand(0).getReg()));
526 case X86II::MRMSrcMem:
527 MCE.emitByte(BaseOpcode);
528 emitMemModRMByte(MI, MI.getNumOperands()-4,
529 getX86RegNum(MI.getOperand(0).getReg()));
532 case X86II::MRMS0r: case X86II::MRMS1r:
533 case X86II::MRMS2r: case X86II::MRMS3r:
534 case X86II::MRMS4r: case X86II::MRMS5r:
535 case X86II::MRMS6r: case X86II::MRMS7r:
536 MCE.emitByte(BaseOpcode);
537 emitRegModRMByte(MI.getOperand(0).getReg(),
538 (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r);
540 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
541 unsigned Size = sizeOfPtr(Desc);
542 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
546 case X86II::MRMS0m: case X86II::MRMS1m:
547 case X86II::MRMS2m: case X86II::MRMS3m:
548 case X86II::MRMS4m: case X86II::MRMS5m:
549 case X86II::MRMS6m: case X86II::MRMS7m:
550 MCE.emitByte(BaseOpcode);
551 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0m);
553 if (MI.getNumOperands() == 5) {
554 unsigned Size = sizeOfPtr(Desc);
555 emitConstant(MI.getOperand(4).getImmedValue(), Size);