blob: 45d0b8c547eff5eeac7b28d99817d45daff90a28 [file] [log] [blame]
Misha Brukmancd603132003-06-02 03:28:00 +00001//===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
Chris Lattner40ead952002-12-02 21:24:12 +00002//
3// This file contains the pass that transforms the X86 machine instructions into
4// actual executable machine code.
5//
6//===----------------------------------------------------------------------===//
7
8#include "X86TargetMachine.h"
Chris Lattnerea1ddab2002-12-03 06:34:06 +00009#include "X86.h"
Chris Lattner40ead952002-12-02 21:24:12 +000010#include "llvm/PassManager.h"
11#include "llvm/CodeGen/MachineCodeEmitter.h"
Chris Lattner5ae99fe2002-12-28 20:24:48 +000012#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattner76041ce2002-12-02 21:44:34 +000013#include "llvm/CodeGen/MachineInstr.h"
Chris Lattnerdbf30f72002-12-04 06:45:19 +000014#include "llvm/Value.h"
Chris Lattner302de592003-06-06 04:00:05 +000015#include "Support/Statistic.h"
Chris Lattner30d002b2003-06-06 18:25:33 +000016#include <alloca.h>
Chris Lattner40ead952002-12-02 21:24:12 +000017
18namespace {
Chris Lattner302de592003-06-06 04:00:05 +000019 Statistic<>
20 NumEmitted("x86-emitter", "Number of machine instructions emitted");
21
Chris Lattner04b0b302003-06-01 23:23:50 +000022 class JITResolver {
23 MachineCodeEmitter &MCE;
24
25 // LazyCodeGenMap - Keep track of call sites for functions that are to be
26 // lazily resolved.
27 std::map<unsigned, Function*> LazyCodeGenMap;
28
29 // LazyResolverMap - Keep track of the lazy resolver created for a
30 // particular function so that we can reuse them if necessary.
31 std::map<Function*, unsigned> LazyResolverMap;
32 public:
33 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
34 unsigned getLazyResolver(Function *F);
35 unsigned addFunctionReference(unsigned Address, Function *F);
36
37 private:
38 unsigned emitStubForFunction(Function *F);
39 static void CompilationCallback();
40 unsigned resolveFunctionReference(unsigned RetAddr);
41 };
42
43 JITResolver *TheJITResolver;
44}
45
46
47/// addFunctionReference - This method is called when we need to emit the
48/// address of a function that has not yet been emitted, so we don't know the
49/// address. Instead, we emit a call to the CompilationCallback method, and
50/// keep track of where we are.
51///
52unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
53 LazyCodeGenMap[Address] = F;
54 return (intptr_t)&JITResolver::CompilationCallback;
55}
56
57unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
58 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
59 assert(I != LazyCodeGenMap.end() && "Not in map!");
60 Function *F = I->second;
61 LazyCodeGenMap.erase(I);
62 return MCE.forceCompilationOf(F);
63}
64
65unsigned JITResolver::getLazyResolver(Function *F) {
66 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
67 if (I != LazyResolverMap.end() && I->first == F) return I->second;
68
69//std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
70
71 unsigned Stub = emitStubForFunction(F);
72 LazyResolverMap.insert(I, std::make_pair(F, Stub));
73 return Stub;
74}
75
76void JITResolver::CompilationCallback() {
77 unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
Misha Brukmanbc80b222003-06-02 04:13:58 +000078 unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
Chris Lattner04b0b302003-06-01 23:23:50 +000079 assert(StackPtr[1] == RetAddr &&
80 "Could not find return address on the stack!");
Chris Lattner30d002b2003-06-06 18:25:33 +000081
82 // It's a stub if there is an interrupt marker after the call...
83 bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
Chris Lattner04b0b302003-06-01 23:23:50 +000084
Chris Lattner302de592003-06-06 04:00:05 +000085 // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
86 // pointer elimination has been performed. Having a variable sized alloca
87 // disables frame pointer elimination currently, even if it's dead. This is a
88 // gross hack.
89 alloca(10+isStub);
90 // FIXME FIXME FIXME FIXME
91
Chris Lattner04b0b302003-06-01 23:23:50 +000092 // The call instruction should have pushed the return value onto the stack...
93 RetAddr -= 4; // Backtrack to the reference itself...
94
95#if 0
96 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
97 << " ESP=0x" << (unsigned)StackPtr << std::dec
98 << ": Resolving call to function: "
99 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
100#endif
101
102 // Sanity check to make sure this really is a call instruction...
Chris Lattner30d002b2003-06-06 18:25:33 +0000103 assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000104
105 unsigned NewVal = TheJITResolver->resolveFunctionReference(RetAddr);
106
107 // Rewrite the call target... so that we don't fault every time we execute
108 // the call.
Chris Lattner30d002b2003-06-06 18:25:33 +0000109 *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
Chris Lattner04b0b302003-06-01 23:23:50 +0000110
111 if (isStub) {
112 // If this is a stub, rewrite the call into an unconditional branch
113 // instruction so that two return addresses are not pushed onto the stack
114 // when the requested function finally gets called. This also makes the
115 // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
Chris Lattner30d002b2003-06-06 18:25:33 +0000116 ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
Chris Lattner04b0b302003-06-01 23:23:50 +0000117 }
118
119 // Change the return address to reexecute the call instruction...
120 StackPtr[1] -= 5;
121}
122
123/// emitStubForFunction - This method is used by the JIT when it needs to emit
124/// the address of a function for a function whose code has not yet been
125/// generated. In order to do this, it generates a stub which jumps to the lazy
126/// function compiler, which will eventually get fixed to call the function
127/// directly.
128///
129unsigned JITResolver::emitStubForFunction(Function *F) {
130 MCE.startFunctionStub(*F, 6);
131 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
132
133 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
134 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
135
136 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
137 return (intptr_t)MCE.finishFunctionStub(*F);
138}
139
140
141
142namespace {
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000143 class Emitter : public MachineFunctionPass {
144 const X86InstrInfo *II;
Chris Lattner8f04b092002-12-02 21:56:18 +0000145 MachineCodeEmitter &MCE;
Chris Lattner04b0b302003-06-01 23:23:50 +0000146 std::map<BasicBlock*, unsigned> BasicBlockAddrs;
147 std::vector<std::pair<BasicBlock*, unsigned> > BBRefs;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000148 public:
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000149 Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
Chris Lattner40ead952002-12-02 21:24:12 +0000150
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000151 bool runOnMachineFunction(MachineFunction &MF);
Chris Lattner76041ce2002-12-02 21:44:34 +0000152
Chris Lattnerf0eb7be2002-12-15 21:13:40 +0000153 virtual const char *getPassName() const {
154 return "X86 Machine Code Emitter";
155 }
156
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000157 private:
Chris Lattner76041ce2002-12-02 21:44:34 +0000158 void emitBasicBlock(MachineBasicBlock &MBB);
159 void emitInstruction(MachineInstr &MI);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000160
Chris Lattner04b0b302003-06-01 23:23:50 +0000161 void emitPCRelativeBlockAddress(BasicBlock *BB);
162 void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
163 void emitGlobalAddressForCall(GlobalValue *GV);
164 void emitGlobalAddressForPtr(GlobalValue *GV);
165
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000166 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
167 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
168 void emitConstant(unsigned Val, unsigned Size);
169
170 void emitMemModRMByte(const MachineInstr &MI,
171 unsigned Op, unsigned RegOpcodeField);
172
Chris Lattner40ead952002-12-02 21:24:12 +0000173 };
174}
175
Chris Lattner40ead952002-12-02 21:24:12 +0000176/// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
177/// machine code emitted. This uses a MAchineCodeEmitter object to handle
178/// actually outputting the machine code and resolving things like the address
179/// of functions. This method should returns true if machine code emission is
180/// not supported.
181///
182bool X86TargetMachine::addPassesToEmitMachineCode(PassManager &PM,
183 MachineCodeEmitter &MCE) {
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000184 PM.add(new Emitter(MCE));
Chris Lattner40ead952002-12-02 21:24:12 +0000185 return false;
186}
Chris Lattner76041ce2002-12-02 21:44:34 +0000187
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000188bool Emitter::runOnMachineFunction(MachineFunction &MF) {
189 II = &((X86TargetMachine&)MF.getTarget()).getInstrInfo();
Chris Lattner76041ce2002-12-02 21:44:34 +0000190
191 MCE.startFunction(MF);
Chris Lattnere831b6b2003-01-13 00:33:59 +0000192 MCE.emitConstantPool(MF.getConstantPool());
Chris Lattner76041ce2002-12-02 21:44:34 +0000193 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
194 emitBasicBlock(*I);
195 MCE.finishFunction(MF);
Chris Lattner04b0b302003-06-01 23:23:50 +0000196
197 // Resolve all forward branches now...
198 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
199 unsigned Location = BasicBlockAddrs[BBRefs[i].first];
200 unsigned Ref = BBRefs[i].second;
Chris Lattner30d002b2003-06-06 18:25:33 +0000201 *(unsigned*)(intptr_t)Ref = Location-Ref-4;
Chris Lattner04b0b302003-06-01 23:23:50 +0000202 }
203 BBRefs.clear();
204 BasicBlockAddrs.clear();
Chris Lattner76041ce2002-12-02 21:44:34 +0000205 return false;
206}
207
208void Emitter::emitBasicBlock(MachineBasicBlock &MBB) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000209 if (uint64_t Addr = MCE.getCurrentPCValue())
210 BasicBlockAddrs[MBB.getBasicBlock()] = Addr;
211
Chris Lattner76041ce2002-12-02 21:44:34 +0000212 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
213 emitInstruction(**I);
214}
215
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000216
Chris Lattner04b0b302003-06-01 23:23:50 +0000217/// emitPCRelativeBlockAddress - This method emits the PC relative address of
218/// the specified basic block, or if the basic block hasn't been emitted yet
219/// (because this is a forward branch), it keeps track of the information
220/// necessary to resolve this address later (and emits a dummy value).
221///
222void Emitter::emitPCRelativeBlockAddress(BasicBlock *BB) {
223 // FIXME: Emit backward branches directly
224 BBRefs.push_back(std::make_pair(BB, MCE.getCurrentPCValue()));
225 MCE.emitWord(0); // Emit a dummy value
226}
227
228/// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
229///
230void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
231 if (isPCRelative)
232 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
233 else
234 MCE.emitWord(Address);
235}
236
237/// emitGlobalAddressForCall - Emit the specified address to the code stream
238/// assuming this is part of a function call, which is PC relative.
239///
240void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
241 // Get the address from the backend...
242 unsigned Address = MCE.getGlobalValueAddress(GV);
243
244 // If the machine code emitter doesn't know what the address IS yet, we have
245 // to take special measures.
246 //
247 if (Address == 0) {
248 // FIXME: this is JIT specific!
249 if (TheJITResolver == 0)
250 TheJITResolver = new JITResolver(MCE);
251 Address = TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
252 (Function*)GV);
253 }
254 emitMaybePCRelativeValue(Address, true);
255}
256
257/// emitGlobalAddress - Emit the specified address to the code stream assuming
258/// this is part of a "take the address of a global" instruction, which is not
259/// PC relative.
260///
261void Emitter::emitGlobalAddressForPtr(GlobalValue *GV) {
262 // Get the address from the backend...
263 unsigned Address = MCE.getGlobalValueAddress(GV);
264
265 // If the machine code emitter doesn't know what the address IS yet, we have
266 // to take special measures.
267 //
268 if (Address == 0) {
269 // FIXME: this is JIT specific!
270 if (TheJITResolver == 0)
271 TheJITResolver = new JITResolver(MCE);
272 Address = TheJITResolver->getLazyResolver((Function*)GV);
273 }
274
275 emitMaybePCRelativeValue(Address, false);
276}
277
278
279
Chris Lattnerff3261a2003-06-03 15:31:23 +0000280/// N86 namespace - Native X86 Register numbers... used by X86 backend.
281///
282namespace N86 {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000283 enum {
284 EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
285 };
286}
287
288
289// getX86RegNum - This function maps LLVM register identifiers to their X86
290// specific numbering, which is used in various places encoding instructions.
291//
292static unsigned getX86RegNum(unsigned RegNo) {
293 switch(RegNo) {
294 case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
295 case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
296 case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
297 case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
298 case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
299 case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
300 case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
301 case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000302
303 case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
304 case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
305 return RegNo-X86::ST0;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000306 default:
307 assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
308 "Unknown physical register!");
309 assert(0 && "Register allocator hasn't allocated reg correctly yet!");
310 return 0;
311 }
312}
313
314inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
315 unsigned RM) {
316 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
317 return RM | (RegOpcode << 3) | (Mod << 6);
318}
319
320void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
321 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
322}
323
324void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
325 // SIB byte is in the same format as the ModRMByte...
326 MCE.emitByte(ModRMByte(SS, Index, Base));
327}
328
329void Emitter::emitConstant(unsigned Val, unsigned Size) {
330 // Output the constant in little endian byte order...
331 for (unsigned i = 0; i != Size; ++i) {
332 MCE.emitByte(Val & 255);
333 Val >>= 8;
334 }
335}
336
337static bool isDisp8(int Value) {
338 return Value == (signed char)Value;
339}
340
341void Emitter::emitMemModRMByte(const MachineInstr &MI,
342 unsigned Op, unsigned RegOpcodeField) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000343 const MachineOperand &Disp = MI.getOperand(Op+3);
344 if (MI.getOperand(Op).isConstantPoolIndex()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000345 // Emit a direct address reference [disp32] where the displacement of the
346 // constant pool entry is controlled by the MCE.
Chris Lattnere831b6b2003-01-13 00:33:59 +0000347 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
348 unsigned Index = MI.getOperand(Op).getConstantPoolIndex();
Chris Lattner04b0b302003-06-01 23:23:50 +0000349 unsigned Address = MCE.getConstantPoolEntryAddress(Index);
350 MCE.emitWord(Address+Disp.getImmedValue());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000351 return;
352 }
353
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000354 const MachineOperand &BaseReg = MI.getOperand(Op);
355 const MachineOperand &Scale = MI.getOperand(Op+1);
356 const MachineOperand &IndexReg = MI.getOperand(Op+2);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000357
358 // Is a SIB byte needed?
359 if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
360 if (BaseReg.getReg() == 0) { // Just a displacement?
361 // Emit special case [disp32] encoding
362 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
363 emitConstant(Disp.getImmedValue(), 4);
364 } else {
365 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
366 if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
367 // Emit simple indirect register encoding... [EAX] f.e.
368 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
369 } else if (isDisp8(Disp.getImmedValue())) {
370 // Emit the disp8 encoding... [REG+disp8]
371 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
372 emitConstant(Disp.getImmedValue(), 1);
373 } else {
374 // Emit the most general non-SIB encoding: [REG+disp32]
Chris Lattner20671842002-12-13 05:05:05 +0000375 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000376 emitConstant(Disp.getImmedValue(), 4);
377 }
378 }
379
380 } else { // We need a SIB byte, so start by outputting the ModR/M byte first
381 assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
382
383 bool ForceDisp32 = false;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000384 bool ForceDisp8 = false;
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000385 if (BaseReg.getReg() == 0) {
386 // If there is no base register, we emit the special case SIB byte with
387 // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
388 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
389 ForceDisp32 = true;
Brian Gaeke95780cc2002-12-13 07:56:18 +0000390 } else if (Disp.getImmedValue() == 0 && BaseReg.getReg() != X86::EBP) {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000391 // Emit no displacement ModR/M byte
392 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
393 } else if (isDisp8(Disp.getImmedValue())) {
394 // Emit the disp8 encoding...
395 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
Brian Gaeke95780cc2002-12-13 07:56:18 +0000396 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000397 } else {
398 // Emit the normal disp32 encoding...
399 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
400 }
401
402 // Calculate what the SS field value should be...
403 static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
404 unsigned SS = SSTable[Scale.getImmedValue()];
405
406 if (BaseReg.getReg() == 0) {
407 // Handle the SIB byte for the case where there is no base. The
408 // displacement has already been output.
409 assert(IndexReg.getReg() && "Index register must be specified!");
410 emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
411 } else {
412 unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000413 unsigned IndexRegNo;
414 if (IndexReg.getReg())
415 IndexRegNo = getX86RegNum(IndexReg.getReg());
416 else
417 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000418 emitSIBByte(SS, IndexRegNo, BaseRegNo);
419 }
420
421 // Do we need to output a displacement?
Brian Gaeke95780cc2002-12-13 07:56:18 +0000422 if (Disp.getImmedValue() != 0 || ForceDisp32 || ForceDisp8) {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000423 if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
424 emitConstant(Disp.getImmedValue(), 1);
425 else
426 emitConstant(Disp.getImmedValue(), 4);
427 }
428 }
429}
430
Chris Lattner04b0b302003-06-01 23:23:50 +0000431static unsigned sizeOfPtr(const TargetInstrDescriptor &Desc) {
Chris Lattnera0f38c82002-12-13 03:51:55 +0000432 switch (Desc.TSFlags & X86II::ArgMask) {
433 case X86II::Arg8: return 1;
434 case X86II::Arg16: return 2;
435 case X86II::Arg32: return 4;
Chris Lattner5ada8df2002-12-25 05:09:21 +0000436 case X86II::ArgF32: return 4;
437 case X86II::ArgF64: return 8;
438 case X86II::ArgF80: return 10;
Chris Lattnera6a382c2002-12-13 03:50:13 +0000439 default: assert(0 && "Memory size not set!");
Chris Lattnerdf642e12002-12-20 04:12:48 +0000440 return 0;
Misha Brukman5000e432002-12-13 02:13:15 +0000441 }
442}
443
Chris Lattner76041ce2002-12-02 21:44:34 +0000444void Emitter::emitInstruction(MachineInstr &MI) {
Chris Lattner302de592003-06-06 04:00:05 +0000445 NumEmitted++; // Keep track of the # of mi's emitted
446
Chris Lattner76041ce2002-12-02 21:44:34 +0000447 unsigned Opcode = MI.getOpcode();
Chris Lattner3501fea2003-01-14 22:00:31 +0000448 const TargetInstrDescriptor &Desc = II->get(Opcode);
Chris Lattner76041ce2002-12-02 21:44:34 +0000449
450 // Emit instruction prefixes if neccesary
451 if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
Chris Lattner5ada8df2002-12-25 05:09:21 +0000452
453 switch (Desc.TSFlags & X86II::Op0Mask) {
454 case X86II::TB:
455 MCE.emitByte(0x0F); // Two-byte opcode prefix
456 break;
457 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
458 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
Chris Lattnere831b6b2003-01-13 00:33:59 +0000459 MCE.emitByte(0xD8+
460 (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
461 >> X86II::Op0Shift));
Chris Lattner5ada8df2002-12-25 05:09:21 +0000462 break; // Two-byte opcode prefix
Chris Lattnere831b6b2003-01-13 00:33:59 +0000463 default: assert(0 && "Invalid prefix!");
464 case 0: break; // No prefix!
Chris Lattner5ada8df2002-12-25 05:09:21 +0000465 }
Chris Lattner76041ce2002-12-02 21:44:34 +0000466
Chris Lattner5ae99fe2002-12-28 20:24:48 +0000467 unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
Chris Lattner76041ce2002-12-02 21:44:34 +0000468 switch (Desc.TSFlags & X86II::FormMask) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000469 default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
Chris Lattner5ada8df2002-12-25 05:09:21 +0000470 case X86II::Pseudo:
Chris Lattnerc2489032003-05-07 19:21:28 +0000471 if (Opcode != X86::IMPLICIT_USE)
Chris Lattner9dedbcc2003-05-06 21:31:47 +0000472 std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
Chris Lattner5ada8df2002-12-25 05:09:21 +0000473 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000474
Chris Lattner76041ce2002-12-02 21:44:34 +0000475 case X86II::RawFrm:
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000476 MCE.emitByte(BaseOpcode);
Chris Lattner8f04b092002-12-02 21:56:18 +0000477 if (MI.getNumOperands() == 1) {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000478 MachineOperand &MO = MI.getOperand(0);
479 if (MO.isPCRelativeDisp()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000480 // Conditional branch... FIXME: this should use an MBB destination!
481 emitPCRelativeBlockAddress(cast<BasicBlock>(MO.getVRegValue()));
Chris Lattnere831b6b2003-01-13 00:33:59 +0000482 } else if (MO.isGlobalAddress()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000483 assert(MO.isPCRelative() && "Call target is not PC Relative?");
484 emitGlobalAddressForCall(MO.getGlobal());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000485 } else if (MO.isExternalSymbol()) {
Chris Lattner04b0b302003-06-01 23:23:50 +0000486 unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
487 assert(Address && "Unknown external symbol!");
488 emitMaybePCRelativeValue(Address, MO.isPCRelative());
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000489 } else {
Chris Lattnere831b6b2003-01-13 00:33:59 +0000490 assert(0 && "Unknown RawFrm operand!");
Chris Lattnerdbf30f72002-12-04 06:45:19 +0000491 }
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000492 }
493 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000494
495 case X86II::AddRegFrm:
496 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
497 if (MI.getNumOperands() == 2) {
498 MachineOperand &MO1 = MI.getOperand(1);
499 if (MO1.isImmediate() || MO1.getVRegValueOrNull() ||
500 MO1.isGlobalAddress() || MO1.isExternalSymbol()) {
501 unsigned Size = sizeOfPtr(Desc);
502 if (Value *V = MO1.getVRegValueOrNull()) {
503 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000504 emitGlobalAddressForPtr(cast<GlobalValue>(V));
Chris Lattnere831b6b2003-01-13 00:33:59 +0000505 } else if (MO1.isGlobalAddress()) {
506 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000507 assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
508 emitGlobalAddressForPtr(MO1.getGlobal());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000509 } else if (MO1.isExternalSymbol()) {
510 assert(Size == 4 && "Don't know how to emit non-pointer values!");
Chris Lattner04b0b302003-06-01 23:23:50 +0000511
512 unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
513 assert(Address && "Unknown external symbol!");
514 emitMaybePCRelativeValue(Address, MO1.isPCRelative());
Chris Lattnere831b6b2003-01-13 00:33:59 +0000515 } else {
516 emitConstant(MO1.getImmedValue(), Size);
517 }
518 }
519 }
520 break;
521
522 case X86II::MRMDestReg: {
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000523 MCE.emitByte(BaseOpcode);
Chris Lattnere831b6b2003-01-13 00:33:59 +0000524 MachineOperand &SrcOp = MI.getOperand(1+II->isTwoAddrInstr(Opcode));
525 emitRegModRMByte(MI.getOperand(0).getReg(), getX86RegNum(SrcOp.getReg()));
526 if (MI.getNumOperands() == 4)
527 emitConstant(MI.getOperand(3).getImmedValue(), sizeOfPtr(Desc));
Chris Lattner9dedbcc2003-05-06 21:31:47 +0000528 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000529 }
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000530 case X86II::MRMDestMem:
531 MCE.emitByte(BaseOpcode);
532 emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
533 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000534
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000535 case X86II::MRMSrcReg:
536 MCE.emitByte(BaseOpcode);
537 emitRegModRMByte(MI.getOperand(MI.getNumOperands()-1).getReg(),
538 getX86RegNum(MI.getOperand(0).getReg()));
539 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000540
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000541 case X86II::MRMSrcMem:
542 MCE.emitByte(BaseOpcode);
543 emitMemModRMByte(MI, MI.getNumOperands()-4,
544 getX86RegNum(MI.getOperand(0).getReg()));
545 break;
546
547 case X86II::MRMS0r: case X86II::MRMS1r:
548 case X86II::MRMS2r: case X86II::MRMS3r:
549 case X86II::MRMS4r: case X86II::MRMS5r:
550 case X86II::MRMS6r: case X86II::MRMS7r:
551 MCE.emitByte(BaseOpcode);
552 emitRegModRMByte(MI.getOperand(0).getReg(),
553 (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r);
554
Chris Lattnerd9096832002-12-15 08:01:39 +0000555 if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
Misha Brukman5000e432002-12-13 02:13:15 +0000556 unsigned Size = sizeOfPtr(Desc);
Chris Lattnerea1ddab2002-12-03 06:34:06 +0000557 emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), Size);
558 }
559 break;
Chris Lattnere831b6b2003-01-13 00:33:59 +0000560
561 case X86II::MRMS0m: case X86II::MRMS1m:
562 case X86II::MRMS2m: case X86II::MRMS3m:
563 case X86II::MRMS4m: case X86II::MRMS5m:
564 case X86II::MRMS6m: case X86II::MRMS7m:
565 MCE.emitByte(BaseOpcode);
566 emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0m);
567
568 if (MI.getNumOperands() == 5) {
569 unsigned Size = sizeOfPtr(Desc);
570 emitConstant(MI.getOperand(4).getImmedValue(), Size);
571 }
572 break;
Chris Lattner76041ce2002-12-02 21:44:34 +0000573 }
574}