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/Debug.h"
16 #include "Support/Statistic.h"
17 #include "Config/alloca.h"
21 NumEmitted("x86-emitter", "Number of machine instructions emitted");
24 MachineCodeEmitter &MCE;
26 // LazyCodeGenMap - Keep track of call sites for functions that are to be
28 std::map<unsigned, Function*> LazyCodeGenMap;
30 // LazyResolverMap - Keep track of the lazy resolver created for a
31 // particular function so that we can reuse them if necessary.
32 std::map<Function*, unsigned> LazyResolverMap;
34 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
35 unsigned getLazyResolver(Function *F);
36 unsigned addFunctionReference(unsigned Address, Function *F);
39 unsigned emitStubForFunction(Function *F);
40 static void CompilationCallback();
41 unsigned resolveFunctionReference(unsigned RetAddr);
44 JITResolver *TheJITResolver;
48 /// addFunctionReference - This method is called when we need to emit the
49 /// address of a function that has not yet been emitted, so we don't know the
50 /// address. Instead, we emit a call to the CompilationCallback method, and
51 /// keep track of where we are.
53 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
54 LazyCodeGenMap[Address] = F;
55 return (intptr_t)&JITResolver::CompilationCallback;
58 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
59 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
60 assert(I != LazyCodeGenMap.end() && "Not in map!");
61 Function *F = I->second;
62 LazyCodeGenMap.erase(I);
63 return MCE.forceCompilationOf(F);
66 unsigned JITResolver::getLazyResolver(Function *F) {
67 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
68 if (I != LazyResolverMap.end() && I->first == F) return I->second;
70 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
72 unsigned Stub = emitStubForFunction(F);
73 LazyResolverMap.insert(I, std::make_pair(F, Stub));
77 void JITResolver::CompilationCallback() {
78 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
79 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
80 assert(StackPtr[1] == RetAddr &&
81 "Could not find return address on the stack!");
83 // It's a stub if there is an interrupt marker after the call...
84 bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
86 // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
87 // pointer elimination has been performed. Having a variable sized alloca
88 // disables frame pointer elimination currently, even if it's dead. This is a
91 // FIXME FIXME FIXME FIXME
93 // The call instruction should have pushed the return value onto the stack...
94 RetAddr -= 4; // Backtrack to the reference itself...
97 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
98 << " ESP=0x" << (unsigned)StackPtr << std::dec
99 << ": Resolving call to function: "
100 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
103 // Sanity check to make sure this really is a call instruction...
104 assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
106 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
108 // Rewrite the call target... so that we don't fault every time we execute
110 *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
113 // If this is a stub, rewrite the call into an unconditional branch
114 // instruction so that two return addresses are not pushed onto the stack
115 // when the requested function finally gets called. This also makes the
116 // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
117 ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
120 // Change the return address to reexecute the call instruction...
124 /// emitStubForFunction - This method is used by the JIT when it needs to emit
125 /// the address of a function for a function whose code has not yet been
126 /// generated. In order to do this, it generates a stub which jumps to the lazy
127 /// function compiler, which will eventually get fixed to call the function
130 unsigned JITResolver::emitStubForFunction(Function *F) {
131 MCE.startFunctionStub(*F, 6);
132 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
134 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
135 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
137 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
138 return (intptr_t)MCE.finishFunctionStub(*F);
144 class Emitter : public MachineFunctionPass {
145 const X86InstrInfo *II;
146 MachineCodeEmitter &MCE;
147 std::map<const BasicBlock*, unsigned> BasicBlockAddrs;
148 std::vector<std::pair<const BasicBlock*, unsigned> > BBRefs;
150 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
152 bool runOnMachineFunction(MachineFunction &MF);
154 virtual const char *getPassName() const {
155 return "X86 Machine Code Emitter";
159 void emitBasicBlock(MachineBasicBlock &MBB);
160 void emitInstruction(MachineInstr &MI);
162 void emitPCRelativeBlockAddress(BasicBlock *BB);
163 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
164 void emitGlobalAddressForCall(GlobalValue *GV);
165 void emitGlobalAddressForPtr(GlobalValue *GV);
167 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
168 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
169 void emitConstant(unsigned Val, unsigned Size);
171 void emitMemModRMByte(const MachineInstr &MI,
172 unsigned Op, unsigned RegOpcodeField);
177 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
178 /// machine code emitted. This uses a MAchineCodeEmitter object to handle
179 /// actually outputting the machine code and resolving things like the address
180 /// of functions. This method should returns true if machine code emission is
183 bool X86TargetMachine::addPassesToEmitMachineCode(PassManager &PM,
184 MachineCodeEmitter &MCE) {
185 PM.add(new Emitter(MCE));
189 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
190 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
192 MCE.startFunction(MF);
193 MCE.emitConstantPool(MF.getConstantPool());
194 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
196 MCE.finishFunction(MF);
198 // Resolve all forward branches now...
199 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
200 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
201 unsigned Ref = BBRefs[i].second;
202 *(unsigned*)(intptr_t)Ref = Location-Ref-4;
205 BasicBlockAddrs.clear();
209 void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
210 if (uint64_t Addr = MCE.getCurrentPCValue())
211 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
213 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
214 emitInstruction(**I);
218 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
219 /// the specified basic block, or if the basic block hasn't been emitted yet
220 /// (because this is a forward branch), it keeps track of the information
221 /// necessary to resolve this address later (and emits a dummy value).
223 void Emitter::emitPCRelativeBlockAddress(BasicBlock *BB) {
224 // FIXME: Emit backward branches directly
225 BBRefs.push_back(std::make_pair(BB, MCE.getCurrentPCValue()));
226 MCE.emitWord(0); // Emit a dummy value
229 /// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
231 void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
233 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
235 MCE.emitWord(Address);
238 /// emitGlobalAddressForCall - Emit the specified address to the code stream
239 /// assuming this is part of a function call, which is PC relative.
241 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
242 // Get the address from the backend...
243 unsigned Address = MCE.getGlobalValueAddress(GV);
245 // If the machine code emitter doesn't know what the address IS yet, we have
246 // to take special measures.
249 // FIXME: this is JIT specific!
250 if (TheJITResolver == 0)
251 TheJITResolver = new JITResolver(MCE);
252 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
255 emitMaybePCRelativeValue(Address, true);
258 /// emitGlobalAddress - Emit the specified address to the code stream assuming
259 /// this is part of a "take the address of a global" instruction, which is not
262 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
263 // Get the address from the backend...
264 unsigned Address = MCE.getGlobalValueAddress(GV);
266 // If the machine code emitter doesn't know what the address IS yet, we have
267 // to take special measures.
270 // FIXME: this is JIT specific!
271 if (TheJITResolver == 0)
272 TheJITResolver = new JITResolver(MCE);
273 Address = TheJITResolver->getLazyResolver((Function*)GV);
276 emitMaybePCRelativeValue(Address, false);
281 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
285 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
290 // getX86RegNum - This function maps LLVM register identifiers to their X86
291 // specific numbering, which is used in various places encoding instructions.
293 static unsigned getX86RegNum(unsigned RegNo) {
295 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
296 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
297 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
298 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
299 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
300 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
301 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
302 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
304 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
305 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
306 return RegNo-X86::ST0;
308 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
309 "Unknown physical register!");
310 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
315 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
317 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
318 return RM | (RegOpcode << 3) | (Mod << 6);
321 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
322 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
325 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
326 // SIB byte is in the same format as the ModRMByte...
327 MCE.emitByte(ModRMByte(SS, Index, Base));
330 void Emitter::emitConstant(unsigned Val, unsigned Size) {
331 // Output the constant in little endian byte order...
332 for (unsigned i = 0; i != Size; ++i) {
333 MCE.emitByte(Val & 255);
338 static bool isDisp8(int Value) {
339 return Value == (signed char)Value;
342 void Emitter::emitMemModRMByte(const MachineInstr &MI,
343 unsigned Op, unsigned RegOpcodeField) {
344 const MachineOperand &Disp = MI.getOperand(Op+3);
345 if (MI.getOperand(Op).isConstantPoolIndex()) {
346 // Emit a direct address reference [disp32] where the displacement of the
347 // constant pool entry is controlled by the MCE.
348 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
349 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
350 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
351 MCE.emitWord(Address+Disp.getImmedValue());
355 const MachineOperand &BaseReg = MI.getOperand(Op);
356 const MachineOperand &Scale = MI.getOperand(Op+1);
357 const MachineOperand &IndexReg = MI.getOperand(Op+2);
359 // Is a SIB byte needed?
360 if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
361 if (BaseReg.getReg() == 0) { // Just a displacement?
362 // Emit special case [disp32] encoding
363 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
364 emitConstant(Disp.getImmedValue(), 4);
366 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
367 if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
368 // Emit simple indirect register encoding... [EAX] f.e.
369 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
370 } else if (isDisp8(Disp.getImmedValue())) {
371 // Emit the disp8 encoding... [REG+disp8]
372 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
373 emitConstant(Disp.getImmedValue(), 1);
375 // Emit the most general non-SIB encoding: [REG+disp32]
376 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
377 emitConstant(Disp.getImmedValue(), 4);
381 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
382 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
384 bool ForceDisp32 = false;
385 bool ForceDisp8 = false;
386 if (BaseReg.getReg() == 0) {
387 // If there is no base register, we emit the special case SIB byte with
388 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
389 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
391 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
392 // Emit no displacement ModR/M byte
393 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
394 } else if (isDisp8(Disp.getImmedValue())) {
395 // Emit the disp8 encoding...
396 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
397 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
399 // Emit the normal disp32 encoding...
400 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
403 // Calculate what the SS field value should be...
404 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
405 unsigned SS = SSTable[Scale.getImmedValue()];
407 if (BaseReg.getReg() == 0) {
408 // Handle the SIB byte for the case where there is no base. The
409 // displacement has already been output.
410 assert(IndexReg.getReg() && "Index register must be specified!");
411 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
413 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
415 if (IndexReg.getReg())
416 IndexRegNo = getX86RegNum(IndexReg.getReg());
418 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
419 emitSIBByte(SS, IndexRegNo, BaseRegNo);
422 // Do we need to output a displacement?
423 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
424 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
425 emitConstant(Disp.getImmedValue(), 1);
427 emitConstant(Disp.getImmedValue(), 4);
432 static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
433 switch (Desc.TSFlags & X86II::ArgMask) {
434 case X86II::Arg8: return 1;
435 case X86II::Arg16: return 2;
436 case X86II::Arg32: return 4;
437 case X86II::ArgF32: return 4;
438 case X86II::ArgF64: return 8;
439 case X86II::ArgF80: return 10;
440 default: assert(0 && "Memory size not set!");
445 void Emitter::emitInstruction(MachineInstr &MI) {
446 NumEmitted++; // Keep track of the # of mi's emitted
448 unsigned Opcode = MI.getOpcode();
449 const TargetInstrDescriptor &Desc = II->get(Opcode);
451 // Emit instruction prefixes if neccesary
452 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
454 switch (Desc.TSFlags & X86II::Op0Mask) {
456 MCE.emitByte(0x0F); // Two-byte opcode prefix
458 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
459 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
461 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
462 >> X86II::Op0Shift));
463 break; // Two-byte opcode prefix
464 default: assert(0 && "Invalid prefix!");
465 case 0: break; // No prefix!
468 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
469 switch (Desc.TSFlags & X86II::FormMask) {
470 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
472 if (Opcode != X86::IMPLICIT_USE)
473 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
477 MCE.emitByte(BaseOpcode);
478 if (MI.getNumOperands() == 1) {
479 MachineOperand &MO = MI.getOperand(0);
480 if (MO.isPCRelativeDisp()) {
481 // Conditional branch... FIXME: this should use an MBB destination!
482 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
483 } else if (MO.isGlobalAddress()) {
484 assert(MO.isPCRelative() && "Call target is not PC Relative?");
485 emitGlobalAddressForCall(MO.getGlobal());
486 } else if (MO.isExternalSymbol()) {
487 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
488 assert(Address && "Unknown external symbol!");
489 emitMaybePCRelativeValue(Address, MO.isPCRelative());
491 assert(0 && "Unknown RawFrm operand!");
496 case X86II::AddRegFrm:
497 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
498 if (MI.getNumOperands() == 2) {
499 MachineOperand &MO1 = MI.getOperand(1);
500 if (MO1.isImmediate() || MO1.getVRegValueOrNull() ||
501 MO1.isGlobalAddress() || MO1.isExternalSymbol()) {
502 unsigned Size = sizeOfPtr(Desc);
503 if (Value *V = MO1.getVRegValueOrNull()) {
504 assert(Size == 4 && "Don't know how to emit non-pointer values!");
505 emitGlobalAddressForPtr(cast<GlobalValue>(V));
506 } else if (MO1.isGlobalAddress()) {
507 assert(Size == 4 && "Don't know how to emit non-pointer values!");
508 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
509 emitGlobalAddressForPtr(MO1.getGlobal());
510 } else if (MO1.isExternalSymbol()) {
511 assert(Size == 4 && "Don't know how to emit non-pointer values!");
513 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
514 assert(Address && "Unknown external symbol!");
515 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
517 emitConstant(MO1.getImmedValue(), Size);
523 case X86II::MRMDestReg: {
524 MCE.emitByte(BaseOpcode);
525 MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
526 emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
527 if (MI.getNumOperands() == 4)
528 emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
531 case X86II::MRMDestMem:
532 MCE.emitByte(BaseOpcode);
533 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
536 case X86II::MRMSrcReg:
537 MCE.emitByte(BaseOpcode);
538 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
539 getX86RegNum(MI.getOperand(0).getReg()));
542 case X86II::MRMSrcMem:
543 MCE.emitByte(BaseOpcode);
544 emitMemModRMByte(MI, MI.getNumOperands()-4,
545 getX86RegNum(MI.getOperand(0).getReg()));
548 case X86II::MRMS0r: case X86II::MRMS1r:
549 case X86II::MRMS2r: case X86II::MRMS3r:
550 case X86II::MRMS4r: case X86II::MRMS5r:
551 case X86II::MRMS6r: case X86II::MRMS7r:
552 MCE.emitByte(BaseOpcode);
553 emitRegModRMByte(MI.getOperand(0).getReg(),
554 (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r);
556 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
557 unsigned Size = sizeOfPtr(Desc);
558 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
562 case X86II::MRMS0m: case X86II::MRMS1m:
563 case X86II::MRMS2m: case X86II::MRMS3m:
564 case X86II::MRMS4m: case X86II::MRMS5m:
565 case X86II::MRMS6m: case X86II::MRMS7m:
566 MCE.emitByte(BaseOpcode);
567 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0m);
569 if (MI.getNumOperands() == 5) {
570 unsigned Size = sizeOfPtr(Desc);
571 emitConstant(MI.getOperand(4).getImmedValue(), Size);